package com.njyunzhi.pet_identity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.njyunzhi.pet_identity.common.BaseController;
import com.njyunzhi.pet_identity.common.Constants;
import com.njyunzhi.pet_identity.common.ResponseBean;
import com.njyunzhi.pet_identity.common.WxPayUtils;
import com.njyunzhi.pet_identity.entity.SysSetting;
import com.njyunzhi.pet_identity.entity.TaApplication;
import com.njyunzhi.pet_identity.entity.TaPerson;
import com.njyunzhi.pet_identity.service.ISysSettingService;
import com.njyunzhi.pet_identity.service.ITaApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.njyunzhi.pet_identity.service.ITaOrderService;
import com.njyunzhi.pet_identity.entity.TaOrder;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
    * 订单表 前端控制器
    * </p>
 *
 * @author yansen
 * @since 2022-05-24
 */

@Api(tags = "订单表")
@RestController
@RequestMapping("/")
public class TaOrderController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaOrderController.class);

    @Autowired
    public ITaOrderService iTaOrderService;

    @Autowired
    public ITaApplicationService iTaApplicationService;

    @Autowired
    public ISysSettingService iSysSettingService;

    @Autowired
    WxPayUtils wxPayUtils;


//    /**
//     * 分页查询列表
//     * @param pageNum
//     * @param pageSize
//     * @return
//     */
//    @RequestMapping(value="/taOrder",method= RequestMethod.GET)
//    @ApiOperation(value="列表", notes = "列表", httpMethod = "GET", response = ResponseBean.class)
//    public ResponseBean taOrderList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
//									 @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize) throws Exception{
//
//        IPage<TaOrder> pg = new Page<>(pageNum, pageSize);
//        QueryWrapper<TaOrder> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("create_date");
//
//        IPage<TaOrder> result = iTaOrderService.page(pg, queryWrapper);
//        return ResponseBean.success(result);
//    }

    /**
     * 保存对象
     * @param applyId 实体对象
     * @return
     */
    @RequestMapping(value="/wx/{clientId}/order",method= RequestMethod.POST)
    @ApiOperation(value="生成订单", notes = "生成订单", httpMethod = "POST", response = ResponseBean.class)
    public ResponseBean taOrderAdd(@ApiParam("申请单ID") @RequestParam String applyId) throws Exception {
        TaPerson taPerson = currentPerson();

        TaApplication taApplication = iTaApplicationService.getExistBy("apply_id", applyId, false, true);
        if (null == taApplication) {
            return ResponseBean.error("未找到申请单");
        }

        if (!taPerson.getPersonId().equals(taApplication.getPersonId())) {
            return ResponseBean.error("非本人订单, 不能支付");
        }

        if (Constants.PAY_STATUS_PAID == taApplication.getPayStatus()) {
            return ResponseBean.error("当前申请已支付");
        }

        // 快递费
        SysSetting expressFeeSetting = iSysSettingService.getById(Constants.SYSSETTING_EXPRESS_FEE);
        float expressFee = Float.parseFloat(expressFeeSetting.getContent());
        // 工本费
        SysSetting productionCostSetting = iSysSettingService.getById(Constants.SYSSETTING_PRODUCTION_COST);
        float productionCost = Float.parseFloat(productionCostSetting.getContent());

        TaOrder taOrder = new TaOrder();
        String orderNo = iTaOrderService.createOrderNo();
        taOrder.setOrderNo(orderNo);
        taOrder.setApplyId(applyId);
        taOrder.setProductionCost((int) (productionCost * 100));
        // 如果没有选择快递提取, 则没有快递费用
        taOrder.setExpressFee(taApplication.getApplyMethod() == 2 ? (int) (expressFee * 100) : 0);
        taOrder.setCharges(taOrder.getExpressFee() + taOrder.getProductionCost());
        taOrder.setStatus(Constants.PAY_STATUS_READY);
        taOrder.setCreateDate(LocalDateTime.now());

        if (taOrder.getCharges() < 1) {
            return ResponseBean.error("支付金额不能为0");
        }

        boolean isSuccess = iTaOrderService.save(taOrder);
        if (!isSuccess) {
            return ResponseBean.error("生成订单失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 生成微信预支付信息
        WxPayUnifiedOrderV3Request.Amount amount = new  WxPayUnifiedOrderV3Request.Amount();
        amount.setTotal(taOrder.getCharges());

        WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
        payer.setOpenid(taPerson.getOpenid());

        WxPayUnifiedOrderV3Request req = new WxPayUnifiedOrderV3Request();
        req.setDescription(taApplication.getApplyMethod() == 2 ? "工本费+快递费" : "工本费");
        req.setOutTradeNo(orderNo);
        req.setAmount(amount);
        req.setPayer(payer);

        try {
            WxPayUnifiedOrderV3Result.JsapiResult result = wxPayUtils.createOrder(req);

            // 订单信息变成支付中
            taOrder.setStatus(Constants.PAY_STATUS_PAYING);
            iTaOrderService.updateById(taOrder);

            Map<String, Object> rtn = new HashMap<>();
            rtn.put("order", taOrder);
            rtn.put("prepay", result);

            return ResponseBean.success(rtn);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error("生成微信预支付信息失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

//    /**
//     * 根据id删除对象
//     * @param id  实体ID
//     */
//    @RequestMapping(value="/taOrder/{id}", method= RequestMethod.DELETE)
//    @ApiOperation(value="删除", notes = "删除", httpMethod = "DELETE", response = ResponseBean.class)
//    public ResponseBean taOrderDelete(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
//        if(iTaOrderService.removeById(id)){
//            return ResponseBean.success("success");
//        }else {
//            return ResponseBean.error("删除失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
//        }
//    }
//
//    /**
//     * 修改对象
//     * @param id  实体ID
//     * @param taOrder 实体对象
//     * @return
//     */
//    @RequestMapping(value="/taOrder/{id}",method= RequestMethod.PUT)
//    @ApiOperation(value="更新", notes = "更新", httpMethod = "PUT", response = ResponseBean.class)
//    public ResponseBean taOrderUpdate(@ApiParam("对象ID") @PathVariable Integer id,
//                                        @ApiParam("更新内容") @RequestBody TaOrder taOrder) throws Exception{
//
//        if (iTaOrderService.updateById(taOrder)){
//            return ResponseBean.success(iTaOrderService.getById(id));
//        }else {
//            return ResponseBean.error("修改失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
//        }
//    }
//
//    /**
//     * 根据id查询对象
//     * @param id  实体ID
//     */
//    @RequestMapping(value="/taOrder/{id}",method= RequestMethod.GET)
//    @ApiOperation(value="详情", notes = "详情", httpMethod = "GET", response = ResponseBean.class)
//    public ResponseBean taOrderGet(@ApiParam("对象ID") @PathVariable Integer id) throws Exception{
//        return ResponseBean.success(iTaOrderService.getById(id));
//    }
}
