package com.hfkj.schedule;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.LaKaLaTradeSeparateService;
import com.hfkj.channel.weixin.utils.WxOrderConfig;
import com.hfkj.entity.BsTradeOrder;
import com.hfkj.entity.BsTradeOrderProfitSharing;
import com.hfkj.entity.BsTradeOrderProfitSharingReceiver;
import com.hfkj.service.BsTradeOrderProfitSharingReceiverService;
import com.hfkj.service.BsTradeOrderProfitSharingService;
import com.hfkj.service.BsTradeOrderService;
import com.hfkj.service.BsTradeTakeConfigService;
import com.hfkj.sysenum.*;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 交易订单定时任务
 *
 */
@Configuration
public class TradeOrderSchedule {

    private static final Logger log = LoggerFactory.getLogger(TradeOrderSchedule.class);

    @Resource
    private BsTradeOrderProfitSharingService tradeOrderProfitSharingService;

    @Resource
    private BsTradeOrderProfitSharingReceiverService tradeOrderProfitSharingReceiverService;

    @Resource
    private LaKaLaTradeSeparateService laKaLaTradeSeparateService;

    /**
     * 订单发起分账
     * 5分钟扫描一次需要分账的订单
     */
    @Scheduled(cron="0 0/1 * * * ?")
    public void profitSharing() {
        List<BsTradeOrderProfitSharing> tradeOrderProfitSharingList = tradeOrderProfitSharingService.getNeedProfitSharingOrder();
        for (BsTradeOrderProfitSharing tradeOrderProfitSharing : tradeOrderProfitSharingList) {
            try {
                if (tradeOrderProfitSharing.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
                    // 拉卡拉分账
                    if (tradeOrderProfitSharing.getCmdType().equals(ProfitSharingCmdTypeEnum.CMD_TYPE_1.getNumber())) {
                        if (tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status0.getNumber())) {
                            laKaLaTradeSeparateService.separate(tradeOrderProfitSharing.getProfitSharingOrderNo());

                        } else if (tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status2.getNumber())
                            || tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status3.getNumber())) {
                            // 查询拉卡拉分账记录
                            JSONObject queryProfitSharing = laKaLaTradeSeparateService.query(tradeOrderProfitSharing.getProfitSharingOrderNo());
                            if (queryProfitSharing != null) {
                                // ACCEPTED:已受理,PROCESSING:处理中,FAIL:失败,SUCCESS:成功,
                                //（如果分账指令后有反向操作指令，则原分账指令会变更成以下的状态之一：）
                                //CANCELING:撤销中,CANCELED:撤销成功,CANCEL_FAIL:撤销失败,FALLBACKING:回退中,FALLBACK_END:回退结束
                                String status = queryProfitSharing.getString("status");
                                if (status.equals("PROCESSING")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status3.getNumber());
                                } else if (status.equals("ACCEPTED")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status2.getNumber());
                                } else if (status.equals("SUCCESS")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status1.getNumber());
                                    tradeOrderProfitSharing.setFinishTime(new Date());
                                    // 修改接收方状态
                                    List<BsTradeOrderProfitSharingReceiver> receiverList = tradeOrderProfitSharingReceiverService.getReceiverListByProfitSharingId(tradeOrderProfitSharing.getId());
                                    for (BsTradeOrderProfitSharingReceiver receiver : receiverList) {
                                        receiver.setStatus(ProfitSharingReceiverStatusEnum.status1.getNumber());
                                        tradeOrderProfitSharingReceiverService.editData(receiver);
                                    }
                                } else if (status.equals("FAIL")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status4.getNumber());
                                }
                                tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
                            }
                        }
                    } else if (tradeOrderProfitSharing.getCmdType().equals(ProfitSharingCmdTypeEnum.CMD_TYPE_2.getNumber())) {
                        if (tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status0.getNumber())) {
                            laKaLaTradeSeparateService.cancel(tradeOrderProfitSharing.getProfitSharingOrderNo());

                        } else if (tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status2.getNumber())
                                || tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status3.getNumber())) {
                            // 查询拉卡拉分账记录
                            JSONObject queryProfitSharing = laKaLaTradeSeparateService.query(tradeOrderProfitSharing.getProfitSharingOrderNo());
                            if (queryProfitSharing != null) {
                                // ACCEPTED:已受理,PROCESSING:处理中,FAIL:失败,SUCCESS:成功,
                                //（如果分账指令后有反向操作指令，则原分账指令会变更成以下的状态之一：）
                                //CANCELING:撤销中,CANCELED:撤销成功,CANCEL_FAIL:撤销失败,FALLBACKING:回退中,FALLBACK_END:回退结束
                                String status = queryProfitSharing.getString("status");
                                if (status.equals("PROCESSING")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status3.getNumber());
                                } else if (status.equals("ACCEPTED")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status2.getNumber());
                                } else if (status.equals("SUCCESS")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status1.getNumber());
                                    tradeOrderProfitSharing.setFinishTime(new Date());
                                    // 修改接收方状态
                                    List<BsTradeOrderProfitSharingReceiver> receiverList = tradeOrderProfitSharingReceiverService.getReceiverListByProfitSharingId(tradeOrderProfitSharing.getId());
                                    for (BsTradeOrderProfitSharingReceiver receiver : receiverList) {
                                        receiver.setStatus(ProfitSharingReceiverStatusEnum.status1.getNumber());
                                        tradeOrderProfitSharingReceiverService.editData(receiver);
                                    }
                                } else if (status.equals("FAIL")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status4.getNumber());
                                }
                                tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
                            }
                        }
                    } else if (tradeOrderProfitSharing.getCmdType().equals(ProfitSharingCmdTypeEnum.CMD_TYPE_3.getNumber())) {
                        if (tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status0.getNumber())) {
                            laKaLaTradeSeparateService.fallback(tradeOrderProfitSharing.getProfitSharingOrderNo());

                        } else if (tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status2.getNumber())
                                || tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status3.getNumber())) {
                            // 查询拉卡拉分账记录
                            JSONObject queryProfitSharing = laKaLaTradeSeparateService.query(tradeOrderProfitSharing.getProfitSharingOrderNo());
                            if (queryProfitSharing != null) {
                                // ACCEPTED:已受理,PROCESSING:处理中,FAIL:失败,SUCCESS:成功,
                                //（如果分账指令后有反向操作指令，则原分账指令会变更成以下的状态之一：）
                                //CANCELING:撤销中,CANCELED:撤销成功,CANCEL_FAIL:撤销失败,FALLBACKING:回退中,FALLBACK_END:回退结束
                                String status = queryProfitSharing.getString("status");
                                if (status.equals("PROCESSING")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status3.getNumber());
                                } else if (status.equals("ACCEPTED")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status2.getNumber());
                                } else if (status.equals("SUCCESS")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status1.getNumber());
                                    tradeOrderProfitSharing.setFinishTime(new Date());
                                    // 修改接收方状态
                                    List<BsTradeOrderProfitSharingReceiver> receiverList = tradeOrderProfitSharingReceiverService.getReceiverListByProfitSharingId(tradeOrderProfitSharing.getId());
                                    for (BsTradeOrderProfitSharingReceiver receiver : receiverList) {
                                        receiver.setStatus(ProfitSharingReceiverStatusEnum.status1.getNumber());
                                        tradeOrderProfitSharingReceiverService.editData(receiver);
                                    }
                                } else if (status.equals("FAIL")) {
                                    tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status4.getNumber());
                                }
                                tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
                            }
                        }
                    }

                } else if (tradeOrderProfitSharing.getPlatformType().equals(PlatformTypeEnum.type4.getNumber())) {
                    List<Map<String,Object>> receiversList = new ArrayList<>();
                    Map<String,Object> receiversMap;

                    // 分账接收方
                    Map<String,Object> param = new HashMap<>();
                    param.put("tradeOrderProfitSharingId", tradeOrderProfitSharing.getId());
                    List<BsTradeOrderProfitSharingReceiver> profitSharingReceivers = tradeOrderProfitSharingReceiverService.getProfitSharingList(param);
                    for (BsTradeOrderProfitSharingReceiver receiver : profitSharingReceivers) {
                        if (!receiver.getReceiverAccount().equals(new BigDecimal("0"))) {
                            receiversMap = new HashMap<>();
                            receiversMap.put("type", "MERCHANT_ID");
                            receiversMap.put("account", receiver.getReceiverAccount());
                            receiversMap.put("amount", receiver.getReceiverAmount().multiply(new BigDecimal("100")).intValue());
                            receiversMap.put("description", "分给商户：" + receiver.getReceiverName());
                            receiversList.add(receiversMap);
                        }
                    }

                    if (tradeOrderProfitSharing.getPlatformType().equals(PlatformTypeEnum.type4.getNumber())) {
                        // 微信分账
                        TreeMap<String, String> refundModel = WxOrderConfig.profitsharingCreate(
                                tradeOrderProfitSharing.getPlatformAppid(),
                                tradeOrderProfitSharing.getPlatformMerNo(),
                                tradeOrderProfitSharing.getPlatformTradeNo(),
                                tradeOrderProfitSharing.getTradeOrderNo(),
                                receiversList
                        );
                        if("SUCCESS".equals(MapUtils.getString(refundModel, "return_code"))
                                && "SUCCESS".equals(MapUtils.getString(refundModel, "result_code"))) {
                            tradeOrderProfitSharing.setPlatformProfitSharingOrderNo(MapUtils.getString(refundModel, "order_id"));
                            tradeOrderProfitSharing.setStatus(1);
                            tradeOrderProfitSharing.setProfitSharingTime(new Date());
                            tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);

                            for (BsTradeOrderProfitSharingReceiver receiver : profitSharingReceivers) {
                                receiver.setStatus(1);
                                receiver.setProfitSharingTime(new Date());
                                tradeOrderProfitSharingReceiverService.editData(receiver);
                            }
                        } else {
                            tradeOrderProfitSharing.setExt1(MapUtils.getString(refundModel,"description"));
                            tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
                        }
                    }
                }

            } catch (Exception e) {
                tradeOrderProfitSharing.setExt1("分账失败");
                tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
            }
        }
    }

    /**
     * 完结分账
     * 每分钟扫描一次需要完结的订单
     */
    @Scheduled(cron="0 0/1 * * * ?")
    public void profitSharingFinish() {
        List<BsTradeOrderProfitSharing> tradeOrderProfitSharingList = tradeOrderProfitSharingService.getNeedFinishProfitSharingOrder();
        for (BsTradeOrderProfitSharing tradeOrderProfitSharing : tradeOrderProfitSharingList) {
            try {

                TreeMap<String, String> refundModel = WxOrderConfig.profitSharingFinish(
                        tradeOrderProfitSharing.getPlatformAppid(),
                        tradeOrderProfitSharing.getPlatformMerNo(),
                        tradeOrderProfitSharing.getPlatformTradeNo(),
                        tradeOrderProfitSharing.getPlatformProfitSharingOrderNo(),
                        "分账已完成");

                if("SUCCESS".equals(MapUtils.getString(refundModel, "return_code"))
                        && "SUCCESS".equals(MapUtils.getString(refundModel, "result_code"))) {
                    tradeOrderProfitSharing.setPlatformProfitSharingOrderNo(MapUtils.getString(refundModel, "order_id"));
                    tradeOrderProfitSharing.setStatus(2);
                    tradeOrderProfitSharing.setFinishTime(new Date());
                    tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);

                    // 分账接收方
                    Map<String,Object> param = new HashMap<>();
                    param.put("tradeOrderProfitSharingId", tradeOrderProfitSharing.getId());
                    List<BsTradeOrderProfitSharingReceiver> profitSharingReceivers = tradeOrderProfitSharingReceiverService.getProfitSharingList(param);
                    for (BsTradeOrderProfitSharingReceiver receiver : profitSharingReceivers) {
                        receiver.setStatus(2);
                        receiver.setFinishTime(new Date());
                        tradeOrderProfitSharingReceiverService.editData(receiver);
                    }
                } else {
                    tradeOrderProfitSharing.setExt1(MapUtils.getString(refundModel,"description"));
                    tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
                }

            } catch (Exception e) {
                tradeOrderProfitSharing.setExt1("完结分账失败");
                tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
            }
        }
    }

}
