package com.gree.mall.manager.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.gree.mall.manager.bean.ums.SubsidyApplyTraceBean;
import com.gree.mall.manager.logic.common.UMSLogic;
import com.gree.mall.manager.logic.ums.FileSftpUploaderLogic;
import com.gree.mall.manager.plus.entity.AdminWebsit;
import com.gree.mall.manager.plus.entity.UmsSupplementRecord;
import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
import com.gree.mall.manager.plus.service.AdminWebsitService;
import com.gree.mall.manager.plus.service.UmsSupplementRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
@Slf4j
public class YueHuanXinSchedule {

    @Resource
    UmsSupplementRecordService umsSupplementRecordService;
    @Resource
    FileSftpUploaderLogic fileSftpUploaderLogic;
    @Resource
    UMSLogic umsLogic;
    @Resource
    AdminCompanyWechatService adminCompanyWechatService;
    @Resource
    AdminWebsitService adminWebsitService;

    /**
     * 对提交的补贴记录上传
     */
    @Scheduled(fixedDelay = 60 * 1000)
    public void recordUploadTask() {
        List<UmsSupplementRecord> recordList = umsSupplementRecordService.lambdaQuery()
                .eq(UmsSupplementRecord::getStatus,"SUBMIT")
                .lt(UmsSupplementRecord::getErrCount, 5)
                .list();

        if (CollectionUtil.isEmpty(recordList)) {
            return;
        }

        final List<AdminWebsit> websitList = adminWebsitService.lambdaQuery()
                .in(AdminWebsit::getWebsitId, recordList.stream()
                        .map(UmsSupplementRecord::getWebsitId)
                        .collect(Collectors.toList()))
                .list();

        final Map<String, AdminWebsit> adminWebsitMap = websitList.stream()
                .collect(Collectors.toMap(AdminWebsit::getWebsitId, Function.identity()));

        for (UmsSupplementRecord record : recordList) {
            final AdminWebsit websit = adminWebsitMap.get(record.getWebsitId());
            if (Objects.isNull(websit)) {
                record.setErrCount(record.getErrCount() + 1)
                        .setSysErr("缺少商家信息");
                continue;
            }

            record.setReqSn((DateUtil.format(DateUtil.date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + IdUtil.fastSimpleUUID()));

            SubsidyApplyTraceBean reqBean = new SubsidyApplyTraceBean();
            BeanUtils.copyProperties(record, reqBean);

            try {
                // 上传文件到粤换新平台
                this.handleImageUpload(websit, record, reqBean);

                // 调起申请接口
                final JSONObject resultJson = umsLogic.querySubsidyApplyTrace(websit.getYunSpCode(), record.getReqSn(), JSONUtil.toJsonStr(reqBean),
                        websit.getUmsPublicKey(), websit.getUmsPrivateKey());

                final String traceStatus = resultJson.getObject("traceStatus", String.class);
                final String traceMsg = resultJson.getObject("traceMsg", String.class);

                record.setStatus("END")
                        .setTraceStatus(traceStatus)
                        .setTraceMsg(traceMsg)
                        .setErrCount(0)
                        .setSysErr("");

            } catch (Exception e) {
                record.setErrCount(record.getErrCount() + 1)
                        .setSysErr(e.getMessage());
            }
        }

        umsSupplementRecordService.saveOrUpdateBatch(recordList);
    }

    private void handleImageUpload(AdminWebsit websit, UmsSupplementRecord record,
                                   SubsidyApplyTraceBean reqBean) throws IOException {
        if (StringUtils.isNotBlank(record.getIdCardFrontPicKey())) {
            reqBean.setNewCelecAppInvPicKey(fileSftpUploaderLogic.uploadFromUrl(record.getIdCardFrontPicKey(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()));
        } else {
            reqBean.setIdCardFrontPicKey(null);
        }

        if (StringUtils.isNotBlank(record.getIdCardBackPicKey())) {
            reqBean.setNewCelecAppInvPicKey(fileSftpUploaderLogic.uploadFromUrl(record.getIdCardBackPicKey(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()));
        } else {
            reqBean.setIdCardBackPicKey(null);
        }

        if (StringUtils.isNotBlank(record.getNewCelecAppInvPicKey())) {
            reqBean.setNewCelecAppInvPicKey(fileSftpUploaderLogic.uploadFromUrl(record.getNewCelecAppInvPicKey(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()));
        }

        StringBuilder goodsSb = new StringBuilder();
        if (StringUtils.isNotBlank(record.getNewElecAppPicKey1())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewElecAppPicKey1(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewElecAppPicKey2())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewElecAppPicKey2(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewElecAppPicKey3())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewElecAppPicKey3(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewElecAppPicKey4())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewElecAppPicKey4(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewElecAppPicKey5())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewElecAppPicKey5(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(goodsSb.toString())) {
            final String goodsKeys = StringUtils.chop(goodsSb.toString());
            if (StringUtils.isNotBlank(goodsKeys)) {
                reqBean.setNewElecAppPicKey(goodsKeys);
            }
        }

        StringBuilder picSb = new StringBuilder();
        if (StringUtils.isNotBlank(record.getNewTransRecPicKey1())) {
            picSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewTransRecPicKey1(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewTransRecPicKey2())) {
            picSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewTransRecPicKey2(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewTransRecPicKey3())) {
            picSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewTransRecPicKey3(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewTransRecPicKey4())) {
            picSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewTransRecPicKey4(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewTransRecPicKey5())) {
            picSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewTransRecPicKey5(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(picSb.toString())) {
            final String picKeys = StringUtils.chop(picSb.toString());
            if (StringUtils.isNotBlank(picKeys)) {
                reqBean.setNewTransRecPicKey(picKeys);
            }
        }

        StringBuilder otherSb = new StringBuilder();
        if (StringUtils.isNotBlank(record.getNewOtherFile1Key1())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewOtherFile1Key1(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewOtherFile1Key2())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewOtherFile1Key2(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewOtherFile1Key3())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewOtherFile1Key3(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewOtherFile1Key4())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewOtherFile1Key4(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(record.getNewOtherFile1Key5())) {
            goodsSb.append(fileSftpUploaderLogic.uploadFromUrl(record.getNewOtherFile1Key5(),
                    websit.getYunSpCode(), websit.getUmsUser(), websit.getUmsPassword()))
                    .append("|");
        }
        if (StringUtils.isNotBlank(otherSb.toString())) {
            final String otherKeys = StringUtils.chop(otherSb.toString());
            if (StringUtils.isNotBlank(otherKeys)) {
                reqBean.setNewOtherFile1Key(otherKeys);
            }
        }
    }

    /**
     * 对已补贴记录上传的轮询
     */
    @Scheduled(fixedDelay = 60 * 1000)
    public void uploadTraceRecordTask() {
        List<UmsSupplementRecord> recordList = umsSupplementRecordService.lambdaQuery()
                .eq(UmsSupplementRecord::getStatus,"END")
                .eq(UmsSupplementRecord::getTraceStatus, "0")
                .lt(UmsSupplementRecord::getErrCount, 5)
                .list();

        if (CollectionUtil.isEmpty(recordList)) {
            return;
        }

        final List<AdminWebsit> websitList = adminWebsitService.lambdaQuery()
                .in(AdminWebsit::getWebsitId, recordList.stream()
                        .map(UmsSupplementRecord::getWebsitId)
                        .collect(Collectors.toList()))
                .list();

        final Map<String, AdminWebsit> adminWebsitMap = websitList.stream()
                .collect(Collectors.toMap(AdminWebsit::getWebsitId, Function.identity()));

        for (UmsSupplementRecord record : recordList) {
            final AdminWebsit websit = adminWebsitMap.get(record.getWebsitId());

            if (Objects.isNull(websit)) {
                record.setErrCount(record.getErrCount() + 1)
                        .setSysErr("缺少商家信息");
                continue;
            }

            record.setReqSn((DateUtil.format(DateUtil.date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + IdUtil.fastSimpleUUID()));

            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("traceId", record.getTraceId());

            try {
                final JSONObject resultJson = umsLogic.querySubsidyApplyTrace(websit.getYunSpCode(), record.getReqSn(), JSONUtil.toJsonStr(reqMap),
                        websit.getUmsPublicKey(), websit.getUmsPrivateKey());

                final String traceStatus = resultJson.getObject("traceStatus", String.class);
                final String billId = resultJson.getObject("billId", String.class);
                final String remark = resultJson.getObject("Remark", String.class);

                record.setTraceStatus(traceStatus)
                        .setBillId(billId)
                        .setRemark(remark)
                        .setErrCount(0)
                        .setSysErr("");

            } catch (Exception e) {
                record.setErrCount(record.getErrCount() + 1)
                        .setSysErr(e.getMessage());
            }
        }

        umsSupplementRecordService.saveOrUpdateBatch(recordList);
    }

    /**
     * 对已补贴记录上传处理成功的轮询
     */
    @Scheduled(fixedDelay = 60 * 1000)
    public void uploadTraceRecordSuccessTask() {
        // 审核状态 状态  D1:待复审 D2：复审成功 D3:复审失败 E1:待终审 E2:终审成功 E3:终审失败 E:已放款  ER:异常 ED:失败 UN:未知 QN：退资格未知
        List<UmsSupplementRecord> recordList = umsSupplementRecordService.lambdaQuery()
                .eq(UmsSupplementRecord::getStatus,"END")
                .eq(UmsSupplementRecord::getTraceStatus, "1")
                .in(UmsSupplementRecord::getCheckStatus, "", "D1", "D2", "E1", "E2")
                .lt(UmsSupplementRecord::getErrCount, 5)
                .list();

        if (CollectionUtil.isEmpty(recordList)) {
            return;
        }

        final List<AdminWebsit> websitList = adminWebsitService.lambdaQuery()
                .in(AdminWebsit::getWebsitId, recordList.stream()
                        .map(UmsSupplementRecord::getWebsitId)
                        .collect(Collectors.toList()))
                .list();

        final Map<String, AdminWebsit> adminWebsitMap = websitList.stream()
                .collect(Collectors.toMap(AdminWebsit::getWebsitId, Function.identity()));

        for (UmsSupplementRecord record : recordList) {
            final AdminWebsit websit = adminWebsitMap.get(record.getWebsitId());
            if (Objects.isNull(websit)) {
                record.setErrCount(record.getErrCount() + 1)
                        .setSysErr("缺少商家信息");
                continue;
            }

            record.setReqSn((DateUtil.format(DateUtil.date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + IdUtil.fastSimpleUUID()));

            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("billId", record.getBillId());
            reqMap.put("activeBigClass", "ELEC");

            try {
                final JSONObject resultJson = umsLogic.querySubsidyApply(websit.getYunSpCode(), record.getReqSn(), JSONUtil.toJsonStr(reqMap),
                        websit.getUmsPublicKey(), websit.getUmsPrivateKey());

                final String checkStatus = resultJson.getObject("checkStatus", String.class);
                final String grantFlag = resultJson.getObject("grantFlag", String.class);
                final String reason = resultJson.getObject("reason", String.class);

                record.setCheckStatus(checkStatus)
                        .setGrantFlag(grantFlag)
                        .setReason(reason)
                        .setErrCount(0)
                        .setSysErr("");

            } catch (Exception e) {
                record.setErrCount(record.getErrCount() + 1)
                        .setSysErr(e.getMessage());
            }
        }

        umsSupplementRecordService.saveOrUpdateBatch(recordList);
    }
}
