package com.sptg.pay.biz.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.estate.api.entity.FaceChargeProject;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.FaceChargeProjectFeign;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.pay.api.dto.PayCertificateDto;
import com.sptg.pay.api.dto.UserOrderDto;
import com.sptg.pay.api.entity.PayCertificate;
import com.sptg.pay.api.entity.UserOrder;
import com.sptg.pay.api.feigns.UserOrderFeign;
import com.sptg.pay.biz.service.PayCertificateServiceInterface;
import com.sptg.pay.biz.service.UserOrderServiceInterface;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zwx
 * @create 2020/5/16 9:47
 */
@RestController
@RequiredArgsConstructor
public class UserOrderController implements UserOrderFeign {

    private final UserOrderServiceInterface userOrderServiceInterface;
    private final PayCertificateServiceInterface payCertificateServiceInterface;
    private final UserFeign userFeign;
    private final FaceChargeProjectFeign faceChargeProjectFeign;


    @Override
    @PostMapping(value = "/userOrder/showUserOrderPage")
    public ResultBean<Page<UserOrder>> showUserOrderPage(@RequestBody UserOrderDto userOrderDto) {
        return this.userOrderServiceInterface.showUserOrderPage(userOrderDto);
    }

    @Override
    @PostMapping(value = "/userOrder/getUserOrderList")
    public List<UserOrder> getUserOrderList(@RequestBody UserOrderDto userOrderDto) {
        return this.userOrderServiceInterface.getUserOrderList(userOrderDto);
    }

    @Override
    @PostMapping(value = "/userOrder/addUserOrder")
    public ResultBean<UserOrder> addUserOrder(@RequestBody UserOrderDto userOrderDto) {
        Assert.isNull(userOrderDto.getId(),"用户订单已存在，请勿重复添加");
        Assert.notNull(userOrderDto.getGoodsId(), "商品ID不存在，不能下单");
        FaceChargeProject faceChargeProject = faceChargeProjectFeign.getFaceChargeProjectById(userOrderDto.getGoodsId());
        if (faceChargeProject.getTypeItem() == 11){
            userOrderDto.setFeeType("试用");
        }
        if (faceChargeProject.getTypeItem() == 12){
            userOrderDto.setFeeType("长期");
        }
        if (faceChargeProject.getTypeItem() == 21){
            userOrderDto.setFeeType("押金");
        }
        if (faceChargeProject.getTypeItem() == 22){
            userOrderDto.setFeeType("套餐");
        }
        return this.userOrderServiceInterface.addUserOrder(userOrderDto);
    }

    @Override
    @PostMapping(value = "/userOrder/updateUserOrder")
    public ResultBean<Boolean> updateUserOrder(@RequestBody UserOrder userOrder) {
        return this.userOrderServiceInterface.updateUserOrder(userOrder);
    }

    @Override
    @PostMapping(value = "/userOrder/findUserOrderById")
    public UserOrder findUserOrderById(@RequestParam Long id) {
        return this.userOrderServiceInterface.findUserOrderById(id);
    }

    @Override
    @PostMapping(value = "/userOrder/findUserOrderByCondition")
    public UserOrder findUserOrderByCondition(@RequestBody UserOrderDto userOrderDto) {
        return this.userOrderServiceInterface.findUserOrderByCondition(userOrderDto);
    }

    @Override
    @PostMapping(value = "/userOrder/payFinish")
    public boolean payFinish(@RequestBody UserOrder userOrder) {
        boolean success = true;
        if(userOrder != null){
            String orderType = userOrder.getOrderType();
            switch (orderType){
                case "FACE_ENABLE":{
                    User user = this.userFeign.findUserById(userOrder.getUserId());
                    Date faceBeginDate = user.getFaceBeginDate();
                    Date faceEndDate = user.getFaceEndDate();
                    FaceChargeProject faceChargeProject = faceChargeProjectFeign.getFaceChargeProjectById(userOrder.getGoodsId());
                    if(faceChargeProject != null) {
                        PayCertificateDto payCertificateDto = new PayCertificateDto();
                        payCertificateDto.setOrderNo(userOrder.getBizOrderNo());
                        PayCertificate queryPayCertificate = payCertificateServiceInterface.findPayCertificateByCondition(payCertificateDto);
                        Date today = new Date();
                        if (null != queryPayCertificate){
                            if (faceChargeProject.getTypeItem() == 21){
                                queryPayCertificate.setCanRefund(OperationConstant.ZERO);
                            }else {
                                queryPayCertificate.setCanRefund(OperationConstant.MINUS_ONE);
                            }
                            this.payCertificateServiceInterface.updatePayCertificate(queryPayCertificate);
                        }
                        if(faceEndDate != null){
                            //延长激活日期
                            int compare = DateUtil.compare(faceEndDate, today);
                            if(compare >= 0){
                                user.setFaceEndDate(DateUtils.addDays(user.getFaceEndDate(), faceChargeProject.getDays()));
                            }else{
                                user.setFaceEndDate(DateUtils.addDays(today, faceChargeProject.getDays()));
                            }
                        }else{
                            user.setFaceBeginDate(today);
                            user.setFaceEndDate(DateUtils.addDays(today, faceChargeProject.getDays()));
                        }
                        user.setFaceEnable(OperationConstant.ONE);
                        return this.userFeign.faceEnable(user);
                    }else{
                        success = false;
                    }
                }
                break;
            }
        }else{
            success = false;
        }
        return success;
    }

    @Override
    public ResultBean<Boolean> orderQuery(@RequestBody UserOrderDto userOrderDto) {
        Map<String, String> map = this.userOrderServiceInterface.orderQuery(userOrderDto);
        Assert.notNull(map, "第三方订单查询为空");
        String return_code = map.get("return_code");
        String result_code = map.get("result_code");
        Assert.isTrue(return_code.equals("SUCCESS") && result_code.equals("SUCCESS"), "第三方订单查询失败，失败原因：" + map.get("return_msg"));
        String trade_state = map.get("trade_state");
        Assert.isTrue(trade_state.equals("SUCCESS"), map.get("trade_state_msg"));
        return new ResultBean<>(ResultEnum.SUCCESS);
    }

    @Override
    @PostMapping("/userOrder/addUserOrderByImport")
    public UserOrder addUserOrderByImport(@RequestBody UserOrderDto userOrderDto){
        UserOrder userOrder = this.userOrderServiceInterface.addUserOrderByImport(userOrderDto);
        //判断有没有orderNo
        if (StringUtils.isNotEmpty(userOrderDto.getBizOrderNo())) {
            PayCertificateDto payCertificateDto = new PayCertificateDto();
            payCertificateDto.setOrderNo(userOrderDto.getBizOrderNo());
            payCertificateDto.setChannelCode(userOrderDto.getPayType());
            payCertificateDto.setPayStatus(userOrderDto.getPayStatus());
            payCertificateDto.setPayTime(userOrderDto.getPayTime());
            payCertificateDto.setStatus(OperationConstant.ZERO);
            payCertificateDto.setRefund(OperationConstant.ZERO);
            payCertificateDto.setOrderId(userOrder.getId());
            payCertificateDto.setPayment(userOrderDto.getActualPayAmount());
            payCertificateDto.setUserId(userOrderDto.getUserId());
            payCertificateDto.setApplyRefund(OperationConstant.ZERO);
            payCertificateDto.setCanRefund(OperationConstant.MINUS_ONE);
            ResultBean<Boolean> resultBean = payCertificateServiceInterface.addPayCertificate(payCertificateDto);
            if (resultBean.getMsg().equals(true)) {
                return userOrder;
            }
        }
        return null;
    }

    @Override
    @GetMapping(value = "/userOrder/getByOldId/{oldId}")
    public UserOrder getByOldId(@PathVariable(value = "oldId") String oldId) {
        return this.userOrderServiceInterface.getByOldId(oldId);
    }

}
