package com.gic.haoban.manage.service.service.out.impl.licence;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.licence.AppOrderCheckDTO;
import com.gic.haoban.manage.api.dto.licence.AppOrderNoticeDTO;
import com.gic.haoban.manage.api.dto.licence.AppOrderPageDTO;
import com.gic.haoban.manage.api.dto.qdto.licence.AppOrderPageQDTO;
import com.gic.haoban.manage.api.dto.qdto.licence.AppOrderQDTO;
import com.gic.haoban.manage.api.service.licence.AppOrderApiService;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanAppOrder;
import com.gic.haoban.manage.service.service.TabHaobanAppOrderService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.util.SignatureGetterUtil;
import com.gic.wechat.api.dto.qywx.fee.OpenOrderResponseDTO;
import com.gic.wechat.api.dto.qywx.response.QywxResponseDTO;
import com.gic.wechat.api.service.qywx.QywxOrderApiService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @description:
 * @Author: wenhua
 * @Date: 2023/6/25 15:44
 */
@Service("AppOrderApiServiceImpl")
public class AppOrderApiServiceImpl implements AppOrderApiService {

    private static final Logger logger = LogManager.getLogger(AppOrderApiServiceImpl.class);

    @Autowired
    private TabHaobanAppOrderService tabHaobanAppOrderService;
    @Autowired
    private QywxOrderApiService qywxOrderApiService;
    @Autowired
    private Config config;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;

    @Override
    public ServiceResponse<Page<AppOrderPageDTO>> getAppOrderPage(AppOrderPageQDTO qdto) {
        Page<AppOrderPageDTO> orderPage = tabHaobanAppOrderService.getAppOrderPage(qdto);
        List<AppOrderPageDTO> list = orderPage.getResult();
        if (CollUtil.isNotEmpty(list)){
            Date now = new Date();
            //判断支付时间是否过期，需要更改订单状态，已过期的订单默认取消
            for (AppOrderPageDTO dto : list){
                if (dto.getOrderStatus() == 1 && now.after(dto.getExpireTime())){
                    dto.setOrderStatus(3);
                    //需要取消订单
                    cancelAppOrder(dto.getId());
                }
            }
            orderPage.setResult(list);
        }
        return ServiceResponse.success(orderPage);
    }

    @Override
    public ServiceResponse<Boolean> saveAppOrder(AppOrderQDTO qdto) {
        //调用企业微信接口，创建付款订单
        if (null == qdto) {
            return ServiceResponse.failure("-9999", "参数不能为空！");
        }
        String wxEnterpriseId = qdto.getWxEnterpriseId();
        String secret = config.getQywxCashierSecret();
        String promotionCaseName = config.getPromotionCaseName();
        String promotionCaseId = config.getPromotionCaseId();
        String buySuiteId = config.getBuySuiteId();
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseService.selectById(wxEnterpriseId);
        String openCorpid = wxEnterpriseDTO.getOpenCorpid();
        String serviceCorpid = config.getCorpid();
        /**
         * 按照企业微信接口提供参数
         * {
         *   "business_type": 3,
         *   "custom_corpid": "wx979abee1572365f9",
         *   "pay_type": 1,
         *   "product_list": {
         *     "promotion_case": {
         *       "order_type": 0,
         *       "case_id": "slne7508097f40c4f8e",
         *       "promotion_edition_name": "固定单价",
         *       "duration_days": 30,
         *       "buy_info_list": [{
         *           "suiteid": "wx8838a73b0f57a7b5",
         *           "appid": 2,
         *           "user_count": 10
         *         },
         *         {
         *           "suiteid": "wx15ab15f7b1ced876",
         *           "user_count": 20
         *         }
         *       ],
         *     }
         *   },
         *   "nonce_str": "129031823",
         *   "ts": 1548302135,
         *   "sig": "mPOwVW/vQ74xN+b+Yu1KMa9RrmhKJaJjAtXHTof+EpU="
         * }
         */
        JSONObject json = new JSONObject();
        HashMap<String, Object> map1 = new HashMap<>();
        HashMap<String, Object> map2 = new HashMap<>();
        List<HashMap<String, Object>> buyInfoList = new ArrayList<>();
        HashMap<String, Object> buyInfoMap = new HashMap<>();
        buyInfoMap.put("suiteid", buySuiteId);
        buyInfoMap.put("user_count", qdto.getUserNum());
        buyInfoList.add(buyInfoMap);
        //获取秒级时间戳
        long timeStamp = System.currentTimeMillis() / 1000;
        //签名算法
        SignatureGetterUtil signatureGetterUtil = new SignatureGetterUtil(secret);
        String nonceStr = signatureGetterUtil.genNonce();
        String sig = null;
        map2.put("order_type", qdto.getOrderType());
        map2.put("case_id", promotionCaseId);
        map2.put("promotion_edition_name", promotionCaseName);
        map2.put("duration_days", qdto.getDuration());
        map2.put("buy_info_list", buyInfoList);
        map1.put("promotion_case", map2);
        json.put("business_type", 3);
        json.put("custom_corpid", openCorpid);
        json.put("pay_type", 0);
        json.put("product_list", map1);
        json.put("nonce_str", nonceStr);
        json.put("ts", timeStamp);
        try {
            logger.info("签名算法参数校验：{}",JSON.toJSONString(json));
            sig = signatureGetterUtil.get(JSON.toJSONString(json));
        } catch (Exception e) {
            logger.info("签名算法异常！");
            throw new RuntimeException(e);
        }
        json.put("sig", sig);
        //调用企业微信创建收款订单接口
        ServiceResponse<OpenOrderResponseDTO> response = qywxOrderApiService.createOpenOrder(serviceCorpid, openCorpid, JSON.toJSONString(json));
        logger.info("调用企业微信创建收款订单返回信息：{}", JSON.toJSONString(response));
        if (response.isSuccess()) {
            OpenOrderResponseDTO dto = response.getResult();
            TabHaobanAppOrder appOrder = JSONObject.parseObject(JSONObject.toJSONString(qdto), TabHaobanAppOrder.class);
            Date now = new Date();
            appOrder.setOrderId(dto.getOrderId());
            appOrder.setOrderUrl(dto.getOrderUrl());
            appOrder.setOriginPrice(dto.getOriginPrice());
            appOrder.setPaidPrice(dto.getPaidPrice());
            appOrder.setId(UniqueIdUtils.uniqueLong());
            appOrder.setOrderStatus(1);
            appOrder.setCreateTime(now);
            appOrder.setUpdateTime(now);
            appOrder.setDeleteFlag(0);
            //默认6天支付有效期
            appOrder.setExpireTime(DateUtil.addDay(now,6));
            tabHaobanAppOrderService.insert(appOrder);
            return ServiceResponse.success(true);
        }
        return ServiceResponse.failure(response.getCode(), response.getMessage());
    }

    @Override
    public ServiceResponse<Boolean> cancelAppOrder(Long orderId) {
        TabHaobanAppOrder appOrder = tabHaobanAppOrderService.queryById(orderId);
        if (null == appOrder){
            return ServiceResponse.failure("-9999", "无效的orderId！");
        }
        String wxEnterpriseId = appOrder.getWxEnterpriseId();
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseService.selectById(wxEnterpriseId);
        String openCorpid = wxEnterpriseDTO.getOpenCorpid();
        String serviceCorpid = config.getCorpid();
        String secret = config.getQywxCashierSecret();
        //获取秒级时间戳
        long timeStamp = System.currentTimeMillis() / 1000;
        //签名算法
        SignatureGetterUtil signatureGetterUtil = new SignatureGetterUtil(secret);
        String nonceStr = signatureGetterUtil.genNonce();
        String sig = null;
        JSONObject json = new JSONObject();
        json.put("order_id",appOrder.getOrderId());
        json.put("nonce_str", nonceStr);
        json.put("ts", timeStamp);
        try {
            logger.info("签名算法参数校验：{}",JSON.toJSONString(json));
            sig = signatureGetterUtil.get(JSON.toJSONString(json));
        } catch (Exception e) {
            logger.info("签名算法异常！");
            throw new RuntimeException(e);
        }
        json.put("sig", sig);
        //调用企业微信创建收款订单接口
        ServiceResponse<QywxResponseDTO> response = qywxOrderApiService.cancelOpenOrder(serviceCorpid, openCorpid, JSON.toJSONString(json));
        logger.info("调用企业微信创建收款订单返回信息：{}", JSON.toJSONString(response));
        if (response.isSuccess()){
            TabHaobanAppOrder newAppOrder = new TabHaobanAppOrder();
            newAppOrder.setId(appOrder.getId());
            newAppOrder.setOrderStatus(3);
            newAppOrder.setUpdateTime(new Date());
            tabHaobanAppOrderService.update(newAppOrder);
            return ServiceResponse.success(true);
        }
        return ServiceResponse.failure(response.getCode(), response.getMessage());
    }

    @Override
    public ServiceResponse<AppOrderCheckDTO> checkAppOrder(String wxEnterpriseId) {

        return null;
    }

    @Override
    public ServiceResponse<AppOrderNoticeDTO> noticeAppOrder(String wxEnterpriseId) {

        return null;
    }

    @Override
    public ServiceResponse<Boolean> qywxCallBack(String param) {

        return null;
    }
}
