package com.yonge.cooleshow.admin.controller.open;

import com.yonge.cooleshow.admin.io.request.coupon.CouponOrderVO;
import com.yonge.cooleshow.api.feign.dto.CouponInfoApi;
import com.yonge.cooleshow.api.feign.dto.EmployeeApi;
import com.yonge.cooleshow.api.feign.dto.StudentApi;
import com.yonge.cooleshow.api.feign.dto.TeacherApi;
import com.yonge.cooleshow.biz.dal.entity.Employee;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.coupon.CouponCategoryEnum;
import com.yonge.cooleshow.biz.dal.enums.coupon.CouponUseStateEnum;
import com.yonge.cooleshow.biz.dal.queryInfo.CouponInfoQuery;
import com.yonge.cooleshow.biz.dal.service.CouponInfoService;
import com.yonge.cooleshow.biz.dal.service.EmployeeService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.UserFirstTimeService;
import com.yonge.cooleshow.biz.dal.wrapper.coupon.CouponOrderWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.UserFirstTimeTypeEnum;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/open/adminClient")
public class AdminClient extends BaseController {
    private final static Logger log = LoggerFactory.getLogger(UserOrderClient.class);

    @Autowired
    private UserFirstTimeService userFirstTimeService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private CouponInfoService couponInfoService;

    @GetMapping("/recordTime")
    public HttpResponseResult<Boolean> recordTime(
            @RequestParam("userId") Long userId,
            @RequestParam("userType") String userType,
            @RequestParam("firstTimeType") UserFirstTimeTypeEnum firstTimeType
    ) {
        ClientEnum clientEnum = ClientEnum.valueOf(userType);
        userFirstTimeService.recordTime(userId, clientEnum, firstTimeType);
        return succeed(true);
    }

    @GetMapping("/getTeacher")
    public HttpResponseResult<TeacherApi> getTeacher(@RequestParam("userId") Long userId) {
        Teacher teacher = teacherService.getById(userId);

        TeacherApi teacherApi = new TeacherApi();
        BeanUtils.copyProperties(teacher, teacherApi);
        return succeed(teacherApi);
    }

    @GetMapping("/getStudent")
    public HttpResponseResult<StudentApi> getStudent(@RequestParam("userId") Long userId) {
        Student student = studentService.getById(userId);

        StudentApi studentApi = new StudentApi();
        BeanUtils.copyProperties(student, studentApi);
        return succeed(studentApi);
    }

    @GetMapping("/getEmployee")
    public HttpResponseResult<EmployeeApi> getEmployee(@RequestParam("userId") Long userId) {
        Employee employee = employeeService.get(userId);

        EmployeeApi employeeApi = new EmployeeApi();
        BeanUtils.copyProperties(employee, employeeApi);
        return succeed(employeeApi);
    }

    /**
     * 订单优惠券信息
     * @return HttpResponseResult<CouponOrderVO.CouponPageInfo>
     */
    @PostMapping(value = "/orderInfo", consumes="application/json", produces="application/json")
    @ApiOperation(value = "查询订单优惠券信息", notes = "CouponOrderVO.PageRequest")
    public HttpResponseResult<CouponInfoApi> queryCouponOrderPageInfo(@RequestParam Long userId, @RequestParam String issueIds, @RequestParam BigDecimal orderAmount, @RequestParam ClientEnum client) {

        List<Long> collect = Arrays.stream(issueIds.split(","))
                                   .map(Long::valueOf)
                                   .collect(Collectors.toList());

        CouponOrderVO.PageRequest request = new CouponOrderVO.PageRequest();
        request.setClientType(client);
        request.setCouponTypes(CouponCategoryEnum.getCategory("MALL"));
        request.setIssueIds(collect);
        request.setUseState(CouponUseStateEnum.USABLE);
        request.setTimestamp(DateTime.now().getMillis());
        request.setAmount(orderAmount.doubleValue());

        CouponInfoApi couponInfoApi = new CouponInfoApi();
        couponInfoApi.setDiscountedPrices(BigDecimal.ZERO);

        if (CollectionUtils.isNotEmpty(collect)) {

            // 订单优惠券信息
            CouponOrderWrapper wrapper = couponInfoService.queryUserOrderCouponInfo(request.getUserId(),
                    CouponInfoQuery.CouponOrderQuery.from(request.jsonString()));

            couponInfoApi.setDiscountedPrices(BigDecimal.valueOf(wrapper.getDiscountedPrices()));
        }

        return succeed(couponInfoApi);
    }

    /**
     * 更新订单优惠券信息
     * @return HttpResponseResult<Boolean>
     */
    @PostMapping(value = "/orderUpdate", consumes="application/json", produces="application/json")
    @ApiOperation(value = "更新订单优惠券信息")
    public HttpResponseResult<Boolean> updateCouponOrderInfo(@RequestParam String couponIssueId,@RequestParam Boolean returnCoupon,@RequestParam String orderNo) {

        CouponOrderVO.CouponUpdateRequest  request = new CouponOrderVO.CouponUpdateRequest();
        request.setOrderNo(orderNo);
        request.setReset(returnCoupon);
        request.setUseType(CouponCategoryEnum.MALL);
        List<Long> collect = Arrays.stream(couponIssueId.split(","))
                                   .map(Long::valueOf)
                                   .collect(Collectors.toList());
        request.setIssueIds(collect);
        // 更新受影响优惠券数据
        int ret = couponInfoService.updateUserOrderCouponInfo(CouponOrderWrapper.from(request.jsonString()));

        return succeed(ret > 0);
    }
}
