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

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.licence.LicenceOrderPageDTO;
import com.gic.haoban.manage.api.dto.qdto.licence.LicenceOrderPageQDTO;
import com.gic.haoban.manage.api.dto.qdto.licence.LicenceOrderQDTO;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.dao.mapper.licence.TabHaobanLicenceOrderMapper;
import com.gic.haoban.manage.service.dao.mapper.licence.TabHaobanLicenceOrderProgressMapper;
import com.gic.haoban.manage.service.entity.licence.TabHaobanLicenceOrder;
import com.gic.haoban.manage.service.entity.licence.TabHaobanLicenceOrderProgress;
import com.gic.haoban.manage.service.service.licence.LicenceOrderService;
import com.gic.haoban.manage.service.util.DingUtils;
import com.gic.marketing.api.dto.SmsSendResponseDTO;
import com.gic.marketing.api.service.AccountOverdueSmsSendService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @description:
 * @Author: wenhua
 * @Date: 2023/3/9 17:01
 */
@Service
public class LicenceOrderServiceImpl implements LicenceOrderService {
    private static Logger logger = LogManager.getLogger(LicenceOrderServiceImpl.class);
    @Autowired
    private TabHaobanLicenceOrderMapper tabHaobanLicenceOrderMapper;
    @Autowired
    private TabHaobanLicenceOrderProgressMapper tabHaobanLicenceOrderProgressMapper;
    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private AccountOverdueSmsSendService accountOverdueSmsSendService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private Config config;

    @Override
    public TabHaobanLicenceOrder getLicenceOrderDetail(Long orderId) {
        TabHaobanLicenceOrder tabHaobanLicenceOrder = tabHaobanLicenceOrderMapper.selectById(orderId);
        return tabHaobanLicenceOrder;
    }

    @Override
    public Integer deleteLicenceOrder(Long orderId) {
        return tabHaobanLicenceOrderMapper.deleteById(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveOrUpdateLicenceOrder(LicenceOrderQDTO licenceOrderQDTO) {
        long orderId = UniqueIdUtils.uniqueLong();
        //订单不支持修改，只能新增
        TabHaobanLicenceOrder order = JSONObject.parseObject(JSONObject.toJSONString(licenceOrderQDTO), TabHaobanLicenceOrder.class);
        Date now = new Date();
        order.setOrderId(orderId);
        //默认支付状态为待支付
        order.setOrderStatus(0);
        order.setQywxOrderStatus(0);
        order.setCreateTime(now);
        order.setUpdateTime(now);
        //生成订单编号
        String num = "ZH"+orderId;
        order.setOrderNumber(num);
        Date expireTime;
        if(order.getPayType()==1){
            expireTime = DateUtil.addNumForMinute(now, 30);
        }else {
            expireTime = DateUtil.addDay(now, 3);
        }
        order.setExpireTime(expireTime);
        tabHaobanLicenceOrderMapper.insert(order);
        //记录订单进度
        saveOrderProgress(orderId,"创建订单",licenceOrderQDTO.getEnterpriseId(),licenceOrderQDTO.getWxEnterpriseId(),licenceOrderQDTO.getCreatorName(),1,null,null);
        //记录企业微信订单进度
        saveOrderProgress(orderId,"创建订单",licenceOrderQDTO.getEnterpriseId(),licenceOrderQDTO.getWxEnterpriseId(),licenceOrderQDTO.getCreatorName(),2,null,null);

        return String.valueOf(orderId);
    }

    private void saveOrderProgress(Long orderId,String orderStatus,String enterpriseId,String wxEnterpriseId,String creatorName,Integer type,String voucher,String reason){
        TabHaobanLicenceOrderProgress orderProgress = new TabHaobanLicenceOrderProgress();
        orderProgress.setId(UniqueIdUtils.uniqueLong());
        orderProgress.setEnterpriseId(enterpriseId);
        orderProgress.setWxEnterpriseId(wxEnterpriseId);
        orderProgress.setOrderId(orderId);
        orderProgress.setOrderStatus(orderStatus);
        orderProgress.setType(type);
        orderProgress.setVoucher(voucher);
        orderProgress.setReason(reason);
        orderProgress.setCreatorName(creatorName);
        tabHaobanLicenceOrderProgressMapper.insert(orderProgress);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateLicenceOrderType(Long orderId, Integer type,String enterpriseId,String wxEnterpriseId,String creatorName,Integer wxFlag) {
        if(wxFlag == 1){
            //更新微信订单状态
            tabHaobanLicenceOrderMapper.updateLicenceOrderType(orderId,type);
        }else {
            //更新企业微信订单状态
            tabHaobanLicenceOrderMapper.updateQywxOrderType(orderId,type);
        }
        //记录订单进度
        switch (type){
            case 0:
                saveOrderProgress(orderId,"创建订单",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 1:
                saveOrderProgress(orderId,"已支付",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 2:
                saveOrderProgress(orderId,"已取消",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 3:
                saveOrderProgress(orderId,"已过期",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 4:
                if (wxFlag==1){
                    saveOrderProgress(orderId,"已退款",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                    break;
                }
                saveOrderProgress(orderId,"退款中",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 5:
                saveOrderProgress(orderId,"退款被拒绝",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 6:
                saveOrderProgress(orderId,"已退款",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            case 7:
                saveOrderProgress(orderId,"以失效",enterpriseId,wxEnterpriseId,creatorName,wxFlag,null,null);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean uploadLicenceOrderVoucher(Long orderId, String voucher,String enterpriseId,String wxEnterpriseId,String creatorName) {
        TabHaobanLicenceOrder tabHaobanLicenceOrder = tabHaobanLicenceOrderMapper.selectById(orderId);
        if (tabHaobanLicenceOrder == null){
            return  false;
        }
        tabHaobanLicenceOrderMapper.uploadLicenceOrderVoucher(orderId,voucher);
        //记录订单进度
        if (StrUtil.isNotBlank(tabHaobanLicenceOrder.getVoucher())){
            saveOrderProgress(orderId,"凭证已重新上传，审核中",enterpriseId,wxEnterpriseId,creatorName,1,voucher,null);
        }else {
            saveOrderProgress(orderId,"凭证已上传，审核中",enterpriseId,wxEnterpriseId,creatorName,1,voucher,null);
        }
        //查询gic品牌名称
        String enterpriseName="";
        String wxEnterpriseName="";
        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
        if (ObjectUtil.isNotNull(enterpriseDTO)){
            enterpriseName=enterpriseDTO.getEnterpriseName();
        }
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (ObjectUtil.isNotNull(wxEnterpriseDTO)){
            wxEnterpriseName=wxEnterpriseDTO.getCorpName();
        }
        String dateToStr = DateUtil.dateToStr(new Date(), DateUtil.FORMAT_DATETIME_19);
        //发送钉钉消息通知
        String host = config.getHost();
        //拿到钉钉群机器人url
        String dingUrl = config.getDingUrl();
        // 最后一个分隔符位置
        int lastIndex = host.lastIndexOf("/");
        // 倒数第二个分隔符位置
        int secondLastIndex = host.lastIndexOf("/", lastIndex - 1);
        String subHost = host.substring(0, secondLastIndex + 1);
        String url = subHost + "enterprise-operation/#/finance-config/wx-order-detail?tabId=wx_account_order&orderId="+orderId;
        String msg = "标题：企微账号许可通知\n品牌名称：" + enterpriseName + "\n" + "企业名称：" + wxEnterpriseName + "\n" + "消息内容：" + dateToStr +
                "新增订单（编号：" + tabHaobanLicenceOrder.getOrderNumber() + "）,请尽快处理！\n" + url;
        DingUtils.send(msg,dingUrl,false);
        return true;
    }

    @Override
    public String isPayLicenceOrder(String wxEnterpriseId) {
        String orderId = tabHaobanLicenceOrderMapper.selectByWxEnterpriseId(wxEnterpriseId);
        if (StrUtil.isNotBlank(orderId)){
            return orderId;
        }
        return null;
    }

    @Override
    public Page<LicenceOrderPageDTO> getLicenceOrderPage(LicenceOrderPageQDTO qdto) {
        //时间处理
        if (StringUtils.isNotBlank(qdto.getStartTime())) {
            qdto.setStartTime(qdto.getStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(qdto.getEndTime())) {
            qdto.setEndTime(qdto.getEndTime() + " 23:59:59");
        }
        PageHelper.startPage(qdto);
        List<TabHaobanLicenceOrder> licenceOrderPage = tabHaobanLicenceOrderMapper.getLicenceOrderPage(qdto);
        //判断订单状态，支付时间已过的订单的需要更改订单状态为已过期
        for (TabHaobanLicenceOrder dto : licenceOrderPage){
            if (dto.getExpireTime().before(new Date()) && dto.getOrderStatus() == 0){
                dto.setOrderStatus(3);
                updateLicenceOrderType(dto.getOrderId(), 3,dto.getEnterpriseId(), dto.getWxEnterpriseId(), "系统",1);
            }
        }
        return PageHelperUtils.changePageHelperToCurrentPage(licenceOrderPage, LicenceOrderPageDTO.class);

    }

    @Override
    public Integer saveTransactionCode(Long orderId, String transactionCode, String prepayId, String wxOrderId,Date payTime,String wxUrl) {
        return tabHaobanLicenceOrderMapper.saveTransactionCode(orderId,transactionCode,prepayId,wxOrderId,payTime,wxUrl);
    }

    @Override
    public TabHaobanLicenceOrder selectByTransactionId(String transactionId) {
        return tabHaobanLicenceOrderMapper.selectByTransactionId(transactionId);
    }

    @Override
    public TabHaobanLicenceOrder selectByQywxOrderId(String qywxOrderId) {
        return tabHaobanLicenceOrderMapper.selectByQywxOrderId(qywxOrderId);
    }

    @Override
    public Integer saveQywxOrderId(Long orderId, String qywxOrderId) {
        return tabHaobanLicenceOrderMapper.saveQywxOrderId(orderId,qywxOrderId);
    }

    @Override
    public List<String> getOrderIdList(String param, Integer type, String wxEnterpriseId) {
        List<String> result = new ArrayList<>();
        if (type == 0){
            result = tabHaobanLicenceOrderMapper.getTransactionIdList(param,wxEnterpriseId);
        }else if(type == 1){
            result = tabHaobanLicenceOrderMapper.getQywxOrderId(param,wxEnterpriseId);
        }else {
            result = tabHaobanLicenceOrderMapper.getWxOrderId(param,wxEnterpriseId);
        }
        return result;
    }

    @Override
    public Boolean checkLicenceOrder(Long orderId, Integer flag, String reason,String creatorName) {
        TabHaobanLicenceOrder order = tabHaobanLicenceOrderMapper.selectById(orderId);
        if (null ==order){
            return  false;
        }
        String enterpriseId = order.getEnterpriseId();
        String wxEnterpriseId = order.getWxEnterpriseId();
        String wxEnterpriseName = "";
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (ObjectUtil.isNotNull(wxEnterpriseDTO)){
            wxEnterpriseName=wxEnterpriseDTO.getCorpName();
        }
        if (flag == 0){
            //更新微信订单状态
            tabHaobanLicenceOrderMapper.saveOrderCheckReason(orderId,reason,0);
            //记录订单进度
            saveOrderProgress(orderId,"审核未通过，请重新上传凭证",enterpriseId,wxEnterpriseId,creatorName,1,null,reason);
            //短信通知
            ClerkDTO clerkDTO = clerkService.getClerkByClerkId(order.getCreatorId());
            if (clerkDTO!=null){
                Map<String, String> params = new HashMap<>();
                params.put("1", wxEnterpriseName);
                params.put("2", order.getOrderNumber());
                SmsSendResponseDTO resp  = accountOverdueSmsSendService.smsSend("-1", clerkDTO.getPhoneNumber(),
                        "86", 106, params);
                logger.info("许可账号支付凭证审核不通过短信通知返回信息：{}", JSON.toJSONString(resp));
            }
        }else {
            //更新微信订单状态
            tabHaobanLicenceOrderMapper.updateLicenceOrderType(orderId,1);
            //记录订单进度
            saveOrderProgress(orderId,"已支付",enterpriseId,wxEnterpriseId,creatorName,1,null,null);
        }
        return true;
    }

    @Override
    public Boolean saveCallBackTime(Long orderId, Integer type, Date time) {
        tabHaobanLicenceOrderMapper.saveCallBackTime(orderId,type,time);
        return true;
    }

    @Override
    public Integer selectCountByWxEnterpriseId(String wxEnterpriseId) {
        return tabHaobanLicenceOrderMapper.selectCountByWxEnterpriseId(wxEnterpriseId);
    }
}
