package com.ghy.web.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.PayParam;
import com.ghy.common.adapay.model.WxpayExpend;
import com.ghy.common.config.WxConfig;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.enums.PayStatus;
import com.ghy.common.utils.StringUtils;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.domain.PaymentRelation;
import com.ghy.payment.service.AdapayService;
import com.ghy.payment.service.FinancialChangeRecordService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.payment.service.IPaymentRelationService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/pay/wx")
public class WxPayController extends BaseController {

    @Resource
    private WxConfig wxConfig;
    @Resource
    private AdapayService adapayService;
    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private IPaymentRelationService paymentRelationService;
    @Resource
    private FinancialChangeRecordService financialChangeRecordService;

    @PostMapping("drawCash")
    @ResponseBody
    public AjaxResult drawCash(@RequestBody JSONObject object) {
        try {
            Long deptId = object.getLong("deptId");
            String orderNo = object.getString("orderNo");
            String cashType = object.getString("cashType");
            String cashAmt = object.getString("cashAmt");
            String memberId = object.getString("memberId");
            String remark = object.getString("remark");
            adapayService.drawCash(deptId, orderNo, cashType, cashAmt, memberId, remark, null);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 微信小程序支付
     */
    @PostMapping("lite")
    @ResponseBody
    public AjaxResult litePay(HttpServletRequest request) {
        String openId = request.getHeader("code");
        String orderMasterCode = request.getHeader("orderMasterCode");
        OrderMaster orderMaster = orderMasterService.selectByCode(orderMasterCode);
        Assert.notNull(orderMaster, "找不到对应的订单");
        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMaster.getId());
        BigDecimal payMoney = BigDecimal.ZERO;
        ArrayList<PaymentRelation> relations = new ArrayList<>();
        if (PayStatus.WAIT_PAY.getCode().equals(financialMaster.getPayStatus())) {
            payMoney = financialMaster.getPayMoney();
            relations.add(new PaymentRelation(null, financialMaster.getId(), PaymentRelation.FINANCIAL_MASTER, financialMaster.getPayMoney()));
        }
        List<Long> idList = orderDetailService.selectByOrderMasterId(orderMaster.getId()).stream().map(OrderDetail::getId).collect(Collectors.toList());
        List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService.selectByDetailIds(StringUtils.join(idList, ","));
        List<Long> financialChangeRecordIds = new ArrayList<>();
        for (FinancialChangeRecord fcr : financialChangeRecords) {
            if (PayStatus.WAIT_PAY.getCode().equals(fcr.getPayStatus())) {
                payMoney = payMoney.add(fcr.getChangeMoney());
                financialChangeRecordIds.add(fcr.getId());
                relations.add(new PaymentRelation(null, fcr.getId(), PaymentRelation.FINANCIAL_CHANGE, fcr.getChangeMoney()));
            }
        }
        //调用adapay微信公众号支付.
        WxpayExpend expend = new WxpayExpend();
        expend.setOpenId(openId);
        try {
            // TODO 订单里需要补充支付金额、tittle、简要描述、分账信息、description
            String changeRecordIdStr = financialChangeRecordIds.size() > 0 ? StringUtils.join(financialChangeRecordIds, ",") + "_" : "";
            PayParam payParam = PayParam.delayPayParam(orderMaster.getCode() + "_" + changeRecordIdStr + System.currentTimeMillis(),
                    String.valueOf(payMoney), "工圈子居家设备", "工圈子居家设备购买付费");
            JSONObject response = adapayService.wxLitePay(orderMaster.getDeptId(), payParam, expend, null, null);
            String paymentId = response.getString("id");
            
            // 更新财务主单的paymentId
            if (PayStatus.WAIT_PAY.getCode().equals(financialMaster.getPayStatus())) {
                FinancialMaster fm2update = new FinancialMaster();
                fm2update.setId(financialMaster.getId());
                fm2update.setPaymentId(paymentId);
                financialMasterService.updateFinancialMaster(fm2update);
            }
            
            // 更新财务变更记录的paymentId
            for (FinancialChangeRecord fcr : financialChangeRecords) {
                if (PayStatus.WAIT_PAY.getCode().equals(fcr.getPayStatus())) {
                    FinancialChangeRecord fcr2update = new FinancialChangeRecord();
                    fcr2update.setId(fcr.getId());
                    fcr2update.setPaymentId(paymentId);
                    financialChangeRecordService.update(fcr2update);
                }
            }
            
            // 保存支付ID与订单ID到关系表
            for (PaymentRelation relation : relations) {
                relation.setPaymentId(paymentId);
                paymentRelationService.insert(relation);
            }
            return AjaxResult.success(response);
        } catch (BaseAdaPayException e) {
            logger.error("获取微信用户信息失败", e);
            return AjaxResult.error();
        }
    }

//    /**
//     * 微信公众号支付.暂时用不着
//     * https://open.weixin.qq.com/connect/oauth2/authorize?
//     * appid=wx404f2439a8c24e15
//     * &redirect_uri=http%3A%2F%2Fwww.opsoul.com%2Fpay%2Fwx%2Fpub
//     * &response_type=code
//     * &scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect
//     */
//    @GetMapping("/pub")
//    @ResponseBody
//    public AjaxResult pubPay(HttpServletRequest request) {
//        String openId = request.getParameter("openId");
//        String orderMasterCode = request.getHeader("orderMasterCode");
//        OrderMaster orderMaster = orderMasterService.selectByCode(orderMasterCode);
//        if (orderMaster == null) {
//            return AjaxResult.error("订单不存在");
//        }
//        try {
//            logger.info("open id is " + openId);
//            //调用adapay微信公众号支付.
//            WxpayExpend expend = new WxpayExpend();
//            expend.setOpenId(openId);
//            Map<String, Object> map;
//            PayParam payParam = PayParam.delayPayParam(orderMaster.getCode(), "0.01", "工圈子测试", "工圈子测试描述");
//            map = adapayService.wxPubPay(orderMaster.getDeptId(), payParam, expend, null, null);
//            return AjaxResult.success(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(ExceptionUtil.getExceptionMessage(e));
//        }
//        return AjaxResult.success();
//    }

}
