package com.kmall.schedule.service;

import com.google.common.collect.Maps;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import com.kmall.common.utils.wechat.ReaderXmlForDOM4J;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.WechatRefundQueryResult;
import com.kmall.manager.dao.TemplateConfDao;
import com.kmall.manager.entity.pay.TemplateConfVo;
import com.kmall.manager.manager.pay.data.open.cus.CusPropertiesBuilder;
import com.kmall.manager.manager.pingan.PinganUtil;
import com.kmall.manager.manager.pingan.dto.PinganPayOrderDto;
import com.kmall.manager.manager.pingan.dto.PinganResponseDto;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.manager.manager.wechat.wxglobal.WechatGlobalUtil;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalQueryApiResult;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundQueryResult;
import com.kmall.manager.manager.wechat.wxtemplate.TemplateData;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplate;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplateUtil;
import com.kmall.schedule.dao.*;
import com.kmall.schedule.entity.MkDistSellStatisEntity;
import com.kmall.schedule.entity.MngChangeJobEntity;
import com.kmall.schedule.entity.StoreMngChangeJobEntity;
import com.kmall.schedule.quartz.OrderTask;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 渠道推广定时任务
 *
 * @author HUANGYAQIN(CN)
 * @date 2019/5/5
 */
@Service
public class QzStorePromService {
    private static Log logger = LogFactory.getLog(QzStorePromService.class);
    @Autowired
    private QzStorePromMapper qzStorePromMapper;

    /**
     * 修改过期门店推广数据结束状态为已结束，修改未开始且开始时间已小于或等于当前时间的门店推广结束状态为进行中
     */
    @Transactional
    public void updateQueryStoreProm() {
        logger.info(">>>>>>>>>>>>>>>>>>>>updateQueryStoreProm is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>修改过期门店推广数据结束状态为已结束，修改未开始且开始时间已小于或等于当前时间的门店推广结束状态为进行中");
        //查询过期门店推广数据
        List<Map> storePromList = qzStorePromMapper.queryStorePromList();
        if (null != storePromList && storePromList.size() > 0) {
            for (Map map : storePromList) {
                Integer promId = MapUtils.getInteger("promId", map);
                Map param = Maps.newHashMap();
                param.put("promId", promId);
                param.put("isFinished", Dict.isFinished.item_0.getItem());
                qzStorePromMapper.updateStoreProm(param);//修改状态
            }
        }
        //查询当渠道活动开始时间小于当前时间的渠道信息
        List<Map> storePromNotStartList = qzStorePromMapper.queryStorePromByNotStartList();
        if (null != storePromNotStartList && storePromNotStartList.size() > 0) {
            for (Map map : storePromNotStartList) {
                Integer promId = MapUtils.getInteger("promId", map);
                Date promBegTime = MapUtils.getDate("promBegTime", map);
                //当渠道活动开始时间小于当前时间，则将活动状态修改为进行中
                if(promBegTime.getTime() <= new Date().getTime()) {
                    Map param = Maps.newHashMap();
                    param.put("promId", promId);
                    param.put("isFinished", Dict.isFinished.item_1.getItem());
                    qzStorePromMapper.updateStoreProm(param);//修改状态
                }
            }
        }

        logger.info(">>>>>>>>>>>>>>>>>>>>updateQueryStoreProm is end ");
    }

    /**
     * 支付成功且是渠道推广订单统计支付数据
     */
    @Transactional
    public void updatePromStatByPaySuccess() {
        logger.info(">>>>>>>>>>>>>>>>>>>>updatePromStatByPaySuccess is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询支付成功的渠道推广订单，修改渠道推广统计数据 ");
        Integer[] statusList = {201};
        List<Map> promByPaySuccessList = qzStorePromMapper.queryStorePromByPaySuccess(statusList);
        if (null != promByPaySuccessList && promByPaySuccessList.size() > 0) {
            for (Map map : promByPaySuccessList) {
                Integer promId = MapUtils.getInteger("promId", map);
                Integer promStatId = MapUtils.getInteger("promStatId", map);
                Integer goodsId = MapUtils.getInteger("goodsId", map);
                Map updateParam = Maps.newHashMap();

                Map statDataMap = qzStorePromMapper.getStatDataByGoodsId(goodsId,statusList);
                Double receivMoney = parseDoubleValid(MapUtils.getDouble("receivMoney", statDataMap));
                Double orderActualPrice = parseDoubleValid(MapUtils.getDouble("orderActualPrice", statDataMap));
                Integer payCaseNum = parseIntegerValid(MapUtils.getInteger("payCaseNum", statDataMap));
                Integer payOrderNum = parseIntegerValid(MapUtils.getInteger("payOrderNum", statDataMap));
                Integer payerNum = parseIntegerValid(MapUtils.getInteger("payerNum", statDataMap));

                Map queryMap = new HashMap();
                queryMap.put("goodsId", goodsId);
                queryMap.put("statusListOne", statusList);
                queryMap.put("statusListTwo", statusList);
                Map actMoneyByOutGoodsMap = qzStorePromMapper.getActMoneyDataByGoodsId(queryMap);
                //获取排除掉不是渠道推广的订单详情金额数据
                Double actMoneyByOutGoods = 0d;
                if(actMoneyByOutGoodsMap != null){
                    actMoneyByOutGoods = parseDoubleValid(MapUtils.getDouble("actMoney", actMoneyByOutGoodsMap));
                }

                //实收金额 // TODO: 2019/5/6 实收金额：还需要计算优惠券、运费等
                Double actMoney = orderActualPrice - actMoneyByOutGoods;
                updateParam.put("receivMoney", receivMoney);
                updateParam.put("actMoney", actMoney);
                updateParam.put("payCaseNum", payCaseNum);
                updateParam.put("payOrderNum", payOrderNum);
                updateParam.put("payerNum", payerNum);

                updateParam.put("promStatId", promStatId);
                updateParam.put("promId", promId);
                qzStorePromMapper.updateStorePromStat(updateParam);//修改状态

                List<Map> realByGoodsIdList = qzStorePromMapper.getStoreRealByGoodsIdList(goodsId,statusList);
                if (null != realByGoodsIdList && realByGoodsIdList.size() > 0) {
                    for (Map realMap : realByGoodsIdList) {
                        Integer promOrderRealId = MapUtils.getInteger("prom_order_real_id", realMap);
                        Map updateIsScanParam = Maps.newHashMap();
                        updateIsScanParam.put("promOrderRealId", promOrderRealId);
                        updateIsScanParam.put("isPromStatScan", 1);
                        qzStorePromMapper.updatePromRealIsPromScan(updateIsScanParam);
                    }
                }
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>updatePromStatByPaySuccess is end ");
    }

    /**
     * 退款成功且是渠道推广订单统计支付数据
     */
    @Transactional
    public void updatePromStatByRefundSuccess() {
        logger.info(">>>>>>>>>>>>>>>>>>>>updatePromStatByRefundSuccess is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询退款成功的渠道推广订单，修改渠道推广统计数据 ");

        Integer[] statusList = {401};
        //查询退款成功的渠道推广订单
        List<Map> promByRefundSuccessList = qzStorePromMapper.queryStorePromByPaySuccess(statusList);
        if (null != promByRefundSuccessList && promByRefundSuccessList.size() > 0) {
            for (Map refundMap : promByRefundSuccessList) {
                Integer promId = MapUtils.getInteger("promId", refundMap);
                Integer goodsId = MapUtils.getInteger("goodsId", refundMap);
                Integer promStatId = MapUtils.getInteger("promStatId", refundMap);
                //查出退款推广单的原统计数据
                Double orgReceivMoney = parseDoubleValid(MapUtils.getDouble("receivMoney", refundMap));
                Double orgActMoney = parseDoubleValid(MapUtils.getDouble("actMoney", refundMap));
                Integer orgPayCaseNum = parseIntegerValid(MapUtils.getInteger("payCaseNum", refundMap));
                Integer orgPayOrderNum = parseIntegerValid(MapUtils.getInteger("payOrderNum", refundMap));
                Integer orgPayerNum = parseIntegerValid(MapUtils.getInteger("payerNum", refundMap));
                Map updateParam = Maps.newHashMap();

                //查出该商品的总退款统计数据
                Map statDataMap = qzStorePromMapper.getStatDataByGoodsId(goodsId,statusList);
                Double receivMoney = parseDoubleValid(MapUtils.getDouble("receivMoney", statDataMap));
                Double orderActualPrice = parseDoubleValid(MapUtils.getDouble("orderActualPrice", statDataMap));
                Integer payCaseNum = parseIntegerValid(MapUtils.getInteger("payCaseNum", statDataMap));
                Integer payOrderNum = parseIntegerValid(MapUtils.getInteger("payOrderNum", statDataMap));
                Integer payerNum = parseIntegerValid(MapUtils.getInteger("payerNum", statDataMap));

                //获取排除掉不是渠道推广的订单详情金额数据
                Map queryMap = new HashMap();
                queryMap.put("goodsId", goodsId);
                queryMap.put("statusListOne", statusList);
                queryMap.put("statusListTwo", statusList);
                Map actMoneyByOutGoodsMap = qzStorePromMapper.getActMoneyDataByGoodsId(queryMap);
                Double actMoneyByOutGoods = 0d;
                if(actMoneyByOutGoodsMap != null) {
                    actMoneyByOutGoods = parseDoubleValid(MapUtils.getDouble("actMoney", actMoneyByOutGoodsMap));
                }
                //实收金额=订单实付金额-排除的金额 // TODO: 2019/5/6 实收金额：还需要计算优惠券、运费等
                Double actMoney = orderActualPrice - actMoneyByOutGoods;
                updateParam.put("receivMoney", orgReceivMoney - receivMoney);
                updateParam.put("actMoney", orgActMoney - actMoney);
                updateParam.put("payCaseNum", orgPayCaseNum - payCaseNum);
                updateParam.put("payOrderNum", orgPayOrderNum - payOrderNum);
                updateParam.put("payerNum", orgPayerNum - payerNum);

                updateParam.put("promStatId", promStatId);
                updateParam.put("promId", promId);
                qzStorePromMapper.updateStorePromStat(updateParam);//修改状态

                List<Map> realByGoodsIdList = qzStorePromMapper.getStoreRealByGoodsIdList(goodsId,statusList);
                if (null != realByGoodsIdList && realByGoodsIdList.size() > 0) {
                    for (Map realMap : realByGoodsIdList) {
                        Integer promOrderRealId = MapUtils.getInteger("prom_order_real_id", realMap);
                        Map updateIsScanParam = Maps.newHashMap();
                        updateIsScanParam.put("isPromStatScan", 1);
                        updateIsScanParam.put("promOrderRealId", promOrderRealId);
                        qzStorePromMapper.updatePromRealIsPromScan(updateIsScanParam);
                    }
                }
            }
        }else{
            logger.info(">>>>>>>>>>>>>>>>>>>>查询退款成功的渠道推广订单没有数据 ");
        }

        logger.info(">>>>>>>>>>>>>>>>>>>>updatePromStatByRefundSuccess is end ");
    }

    private Double parseDoubleValid(Double param){
        param = param == null ? 0 : param;
        return param;
    }

    private Integer parseIntegerValid(Integer param){
        param = param == null ? 0 : param;
        return param;
    }

    public static void main(String[] args) {

    }
}
