package cn.com.countrygarden.bi.main.service.advise.util;

import cn.com.countrygarden.bi.main.dao.advise.AfAdviseConfigMapper;
import cn.com.countrygarden.bi.main.dao.advise.AfAdviseFeedbackMapper;
import cn.com.countrygarden.bi.main.dao.advise.AfAdviseProcessMapper;
import cn.com.countrygarden.bi.main.dto.advise.AdviseProcessDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.advise.AfAdviseConfig;
import cn.com.countrygarden.bi.main.model.advise.AfAdviseProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Condition;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 木木子
 * @Description: 建言工具类
 * @email 944528607@qq.com
 * @date 2019/5/9 17:31
 */
@Component
public class AdviseUtil {
    @Autowired
    private AfAdviseProcessMapper afAdviseProcessMapper;

    @Autowired
    private AfAdviseConfigMapper afAdviseConfigMapper;
    @Autowired
    private AfAdviseFeedbackMapper afAdviseFeedbackMapper;

    /**
     * 建言是否超时及处理定时处理器
     */
    public int timeOutAdviseProcess() {
        int count = 0;
        Condition condition = new Condition(AfAdviseConfig.class);
        condition.selectProperties("configKey", "configValue", "branchTypeCode").isDistinct();
        condition.createCriteria().andEqualTo("enable", 1).andEqualTo("configKey", "timeOut");
        List<AfAdviseConfig> afAdviseConfigs = afAdviseConfigMapper.selectByCondition(condition);
        if (null == afAdviseConfigs || afAdviseConfigs.isEmpty()) {
            return count;
        }
        for (AfAdviseConfig adviseConfig : afAdviseConfigs) {
            List<AdviseProcessDTO> adviseProcessDTOList = afAdviseProcessMapper.selectAllAfAdviseProcess(adviseConfig.getBranchTypeCode());
            if (null == adviseProcessDTOList || adviseProcessDTOList.isEmpty()) {
                return count;
            }
            DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (null != adviseConfig && null != adviseConfig.getConfigValue()) {
                List<AfAdviseProcess> addProcessesList = new ArrayList<>();
                List<Integer> adviseFeedbackIds = new ArrayList<>();
                String[] timeoutParameterArray = adviseConfig.getConfigValue().split("-");
                if(timeoutParameterArray.length!=3){
                    throw  new ServiceException("建言超时时间解析有误，请检查");
                }
                for (AdviseProcessDTO processDTO : adviseProcessDTOList) {
                    List<Long> answerTimeDifferenceList = getDistanceTime(dFormat.format(new Date()), dFormat.format(processDTO.getAnswerTime()), "yyyy-MM-dd HH:mm:ss");
                    //只对区域做超时时间处理
                    if (0 != processDTO.getProcessType()) {
                        continue;
                    }
                    for (int i = 0; i < 3; i++) {
                        //超时时间的设置参数：1-12-11（日-时-分）
                        long answerDate = answerTimeDifferenceList.get(i);
                        //当前时间与上一个建言节点处理的时间差（返回值为：xx天xx小时xx分xx秒）
                        long timeoutDate = Long.parseLong(timeoutParameterArray[i]);

                        //当前时间与上一个建言节点处理的时间差与超时时间比较
                        if (answerDate > timeoutDate) {
                            AfAdviseProcess adviseProcess = new AfAdviseProcess();
                            adviseProcess.setAdviseFeedbackId(processDTO.getAdviseFeedbackId());
                            adviseProcess.setAnswerTime(new Date());
                            adviseProcess.setProcessType(processDTO.getProcessType() + 1);
                            adviseProcess.setContent("建言处理超时，自动跳过至下一个节点处理");
                            adviseProcess.setUserName("超时系统自动处理");
                            adviseProcess.setBranchTypeCode(adviseConfig.getBranchTypeCode());
                            adviseProcess.setState(1);
                            adviseProcess.setEnable(1);
                            adviseProcess.setCreateTime(new Date());
                            adviseProcess.setIsTimeout(1);
                            adviseProcess.setBranchTypeCode(adviseProcess.getBranchTypeCode());
                            addProcessesList.add(adviseProcess);
                            adviseFeedbackIds.add(adviseProcess.getAdviseFeedbackId());
                            break;
                        } else if (answerDate < timeoutDate) {
                            break;
                        }
                    }
                }
                if (null != addProcessesList && !addProcessesList.isEmpty()) {
                    afAdviseProcessMapper.insertList(addProcessesList);
                    count = afAdviseFeedbackMapper.batchUpdateAfAdviseFeedback(adviseFeedbackIds);
                }
            }
        }
        return count;

    }
    /**
     * 处理两个时间差处理工具
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1    时间参数 1 格式：2016-06-22 18:21:20
     * @param str2    时间参数 2 格式：2016-06-22 17:21:20
     * @param pattern 日期格式 yyyy-MM-dd HH:mm:ss    毫秒(yyyy-MM-dd HH:mm:ss.SSS)
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static List<Long> getDistanceTime(String str1, String str2, String pattern) {
        DateFormat df = new SimpleDateFormat(pattern);
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            //当前时间
            long time1 = one.getTime();
            //回复时间
            long time2 = two.getTime();
            long diff;
            if (time1 > time2) {
                diff = time1 - time2;
            } else {
                return null;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Long> timeList = new LinkedList<Long>();
        timeList.add(day);
        timeList.add(hour);
        timeList.add(min);
        return timeList;
    }
}
