package com.nzwz.serivce.impl;

import com.nzwz.common.response.RestResponse;
import com.nzwz.quartz.model.QuartzJob;
import com.nzwz.quartz.transfer.QuartzJobPauseInVo;
import com.nzwz.quartz.transfer.QuartzJobResumeInVo;
import com.nzwz.transfer.synchronization.InitConnectParmCreateInVo;
import com.nzwz.transfer.synchronization.InitConnectParmOutVo;
import com.nzwz.utils.JsonUtil;
import com.nzwz.utils.StringUtil;
import com.nzwz.api.KingDeeApi;
import com.nzwz.api.KingDeeK3CloudApi;
import com.nzwz.config.ThreadLocalConfig;
import com.nzwz.dao.InitConnectParmMapper;
import com.nzwz.dao.LogMapper;
import com.nzwz.dao.TableRelationMapper;
import com.nzwz.model.InitConnectParm;
import com.nzwz.model.Log;
import com.nzwz.model.TableRelation;
import com.nzwz.quartz.service.IQuartzJobService;
import com.nzwz.serivce.ISynchronizationService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Inori
 */
@Service
public class SynchronizationServiceImpl implements ISynchronizationService {

    @Autowired
    private KingDeeApi kingDeeApi;

    @Autowired
    private TableRelationMapper tableRelationMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private IQuartzJobService quartzJobService;

    @Autowired
    private InitConnectParmMapper initConnectParmMapper;


    @Override
    public RestResponse startSynchronization() {
        QuartzJob quartzJob = quartzJobService.getBaseMapper().selectById("1");

        if (StringUtil.isNotNull(quartzJob)) {
            if (quartzJob.getStatus() == 1) {
                quartzJobService.quartzJobResume(new QuartzJobResumeInVo(quartzJob.getJobClassName()));
                return RestResponse.success();
            }
        } else {
            return RestResponse.fail("自动同步定时任务不存在！");
        }

        return RestResponse.fail("自动同步已经启动，请勿重复启动！");
    }

    @Override
    public RestResponse turnOffSynchronization() {
        QuartzJob quartzJob = quartzJobService.getBaseMapper().selectById("1");

        if (StringUtil.isNotNull(quartzJob)) {
            if (quartzJob.getStatus() == 0) {
                quartzJobService.quartzJobPause(new QuartzJobPauseInVo(quartzJob.getJobClassName()));
                return RestResponse.success();
            }
        } else {
            return RestResponse.fail("自动同步定时任务不存在！");
        }

        return RestResponse.fail("自动同步已经关闭，请勿重复关闭！");
    }

    @Override
    public InitConnectParmOutVo initConnectParm() {
        return initConnectParmMapper.initConnectParm();
    }

    @Override
    public RestResponse initConnectParmCreate(InitConnectParmCreateInVo inVo) {
        QuartzJob quartzJob = quartzJobService.getBaseMapper().selectById("1");

        if (StringUtil.isNotNull(quartzJob)) {
            if (quartzJob.getStatus() == 1) {
                return RestResponse.fail("请先关闭同步再保存!");
            }
        } else {
            return RestResponse.fail("自动同步定时任务不存在！");
        }

        InitConnectParm initConnectParm = new InitConnectParm();
        initConnectParm.setId(1);
        initConnectParm.setK3CloudUrl(inVo.getK3CloudUrl());
        initConnectParm.setDbid(inVo.getDbid());
        initConnectParm.setLang(inVo.getLang());
        initConnectParm.setUid(inVo.getUid());
        initConnectParm.setPwd(inVo.getPwd());
        initConnectParmMapper.updateById(initConnectParm);

        KingDeeK3CloudApi kingDeeK3CloudApi = new KingDeeK3CloudApi(inVo.getK3CloudUrl());
        Boolean flag = null;
        try {
            flag = kingDeeK3CloudApi.login(inVo.getDbid(), inVo.getUid(), inVo.getPwd(), inVo.getLang());
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }

        kingDeeApi.setFlag(flag);
        kingDeeApi.setKingDeeK3CloudApi(kingDeeK3CloudApi);

        if (!flag) {
            return RestResponse.fail("参数错误，金蝶登陆失败！");
        }

        return RestResponse.success();
    }

    @Override
    public void synchronization() {
        List<TableRelation> tableRelationList = tableRelationMapper.selectList(null);

        List<TableRelation> temp01List = tableRelationList.stream().filter(m -> StringUtil.isNotBlank(m.getTableDate())).collect(Collectors.toList());
        for (TableRelation tableRelation : temp01List) {
            this.reload(tableRelation);
        }

        List<TableRelation> temp02List = tableRelationList.stream().filter(m -> !"-1".equals(m.getSubTableHeader()) && StringUtil.isBlank(m.getTableDate())).collect(Collectors.toList());
        for (TableRelation tableRelation : temp02List) {
            this.reload(tableRelation);
        }
    }

    private void reload(TableRelation tableRelation) {
        Map<String, Object> data = new HashMap<>(6);
        data.put("TABLE_HEADER", tableRelation.getTableHeader());
        data.put("TABLE_DATE", tableRelation.getTableDate());
        data.put("SUB_TABLE_HEADER", tableRelation.getSubTableHeader());
        data.put("PRIMARY_KEY", tableRelation.getPrimaryKey());
        data.put("FOREIGN_KEY", tableRelation.getForeignKey());
        data.put("IS_TABLE_HEADER", tableRelation.getForeignKey());

        if (StringUtil.isNotBlank(tableRelation.getTableDate())) {
            String dateForm = logMapper.slectOrderCreateTimeByContent(tableRelation.getTableHeader());
            if (StringUtil.isNotBlank(dateForm)) {
                data.put("DATE_FORM", dateForm);
                data.put("DATE_TO", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            }
        }

        //记录日志
        Log log = new Log(tableRelation.getTableName(), tableRelation.getTableHeader(), JsonUtil.toString(Collections.singletonList(data)));
        logMapper.insert(log);

        //发送请求并修改日志
        loadResult(data, log);
    }

    @Override
    public void abnormalAgainSynchronization() {
        List<Log> logList = logMapper.selectLogByFlag(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        for (Log log : logList) {
            Map<String, Object> data = JsonUtil.toMap(log.getData(), String.class, Object.class);
            loadResult(data, log);
        }
    }

    private void loadResult(Map<String, Object> data, Log log) {
        System.out.println("金蝶请求参数: " + data);

        String result = this.send(Collections.singletonList(data), 3);

        System.out.println("金蝶返回值: " + result);

        Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class);
        if (!CollectionUtils.isEmpty(map)) {
            Map<String, Object> tempMap = ThreadLocalConfig.get();
            int costime = StringUtil.isNotNull(tempMap.get("costime")) ? Integer.parseInt(tempMap.get("costime").toString()) : 0;
            if (map.containsKey("Prompt")) {
                if ("同步成功".equals(map.get("Prompt"))) {
                    logMapper.updateById(new Log(log.getId(), 1, result, costime));
                } else {
                    logMapper.updateById(new Log(log.getId(), 0, result, costime));
                }
            }
        }
    }

    private String send(List<Map<String, Object>> data, Integer index) {
        String result = "";
        try {
            result = kingDeeApi.synchronization(data);
        } catch (Exception e) {
            if (index != 0) {
                result = this.send(data, index - 1);
            } else {
                return "金蝶服务器地址异常";
            }
        }
        return result;
    }


}