package weaver.interfaces.mingfeng.job;

import cn.hutool.core.date.DateUtil;
import com.engine.kq.biz.KQFormatData;
import com.engine.kq.timer.KQQueue;
import com.engine.kq.timer.KQTaskBean;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.LocalDateTime;
import java.util.*;

public class SyncKqDatasJob extends BaseCronJob {

    BaseBean basebean = new BaseBean();

    @Override
    public void execute() {
        basebean.writeLog("---------------SyncKqDatasJob Start---------------");

        RecordSet rs = new RecordSet();
        RecordSet rsF = new RecordSet();

        List<List> params = new ArrayList<>();
        List<String> resIds = new ArrayList<>();
        List<List> formParams = new ArrayList<>();

        // 获取当前日期前一天的日期
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(1);
        String yesterday = DateUtil.format(localDateTime,"yyyy-MM-dd");
        basebean.writeLog("----yesterday: "+yesterday);

        String acqKqDatasSql = "select 申请人, 日报日期, 开始时间, 结束时间, 日报类型, 创建日期 FROM ZDYVW_考勤打卡数据_销售日报 where 创建日期 = '" + yesterday + "'";
        basebean.writeLog("----acqKqDatasSql: "+acqKqDatasSql);

        String addFormDataSql = "insert into uf_reportsyncdata (resourceId, kqDate, startTime, endTime, reportType, " +
                "formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, MODEUUID) values (?,?,?,?,?,?,?,?,?,?,?)";
        String reportSyncModeId = basebean.getPropValue("syn_othersys_mfkj", "reportSyncModeId");
        Integer modedatacreater = 1;
        Integer modedatacreatertype = 0;
        String modedatacreatedate = DateUtil.format(new Date(), "yyyy-MM-dd");
        String modedatacreatetime = DateUtil.format(new Date(), "HH:mm:ss");

        rs.executeQuery(acqKqDatasSql);
        while (rs.next()) {
            String petitioner = Util.null2String(rs.getString("申请人"));
            String paperDate = Util.null2String(rs.getString("日报日期"));
            String startTime = Util.null2String(rs.getString("开始时间"));
            String endTime = Util.null2String(rs.getString("结束时间"));
            String reportType = Util.null2String(rs.getString("日报类型"));
            String createDate = Util.null2String(rs.getString("创建日期"));

            if ( StringUtils.isNotBlank(petitioner) && StringUtils.isNotBlank(paperDate) && StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime) ) {
                resIds.add(petitioner + "|" + paperDate);
                List<Object> paramIn = new ArrayList<>();
                paramIn.add(petitioner);
                paramIn.add("1");//内部人员
                paramIn.add("1");//签到
                paramIn.add(paperDate);//考勤日期
                paramIn.add(startTime);//考勤时间 -- 签到
                paramIn.add("1");//是否是有效考勤打卡 -- 1/有效
                paramIn.add("OutDataSourceSyn");//考勤来源 -- OutDataSourceSyn：外部考勤数据同步
                paramIn.add("GMT+8");//多时区所在时区
                paramIn.add(paperDate);//belongdate
                params.add(paramIn);
                List<Object> paramOut = new ArrayList<>();
                paramOut.add(petitioner);
                paramOut.add("1");//内部人员
                paramOut.add("2");//签退
                paramOut.add(paperDate);//考勤日期
                paramOut.add(endTime);//考勤时间 -- 签退
                paramOut.add("1");//是否是有效考勤打卡 -- 1/有效
                paramOut.add("OutDataSourceSyn");//考勤来源 -- OutDataSourceSyn：外部考勤数据同步
                paramOut.add("GMT+8");//多时区所在时区
                paramOut.add(paperDate);//belongdate
                params.add(paramOut);

                basebean.writeLog("---------------SyncKqDatasJob Start To insert formdata---------------");
                //需求变更：将数据转存建模，考勤报表需要根据建模表中是否存在同步的数据判断日报转出差的字段是否计数
                String uuid = UUID.randomUUID().toString();
                boolean addFlag = rsF.executeUpdate(addFormDataSql, petitioner, paperDate, startTime, endTime, reportType,
                        reportSyncModeId, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, uuid );
                if (addFlag) {
                    String billid = "-1";
                    String acqModeIdSql = "select id from uf_reportsyncdata where MODEUUID = ?";
                    rsF.executeQuery(acqModeIdSql, uuid);
                    while (rsF.next()) {
                        billid = Util.null2String(rsF.getString("id"));
                    }
                    modePerRecon(modedatacreater, reportSyncModeId, billid);
                }
            }

        }
        basebean.writeLog("----params: "+params);
        basebean.writeLog("----resIds: "+resIds);

        basebean.writeLog("---------------SyncKqDatasJob Start To InsertDatas---------------");

        //插入考勤数据
        String addDataSql = "insert into hrmschedulesign (userId,userType,signType,signDate,signTime,isInCom,signFrom,timeZone,belongdate)" +
                " values (?,?,?,?,?,?,?,?,?)";
        rs.executeBatchSql(addDataSql, params);

        basebean.writeLog("---------------SyncKqDatasJob Start To KqFormat---------------");
        //执行考勤格式化
        Map<String, List<String>> overtimeMap = Maps.newHashMap();
        KQFormatData kqFormatData = new KQFormatData();
        for (String res:resIds) {
            List<String> overtimeList = Lists.newArrayList();
            String[] split = res.split("\\|");
            String resid = split[0];
            String kqdate = split[1];
            overtimeList.add(kqdate);
            overtimeMap.put(resid,overtimeList);
            Map<String, Object> formatKqDataMap = kqFormatData.formatKqDate(resid, kqdate);
            basebean.writeLog("formatKqDataResult------- resource: " + resid + " formatKqDataMap: " + formatKqDataMap );
        }

        basebean.writeLog("---------------SyncKqDatasJob Start To FormatOverTimeDatas---------------");
        //处理加班生成
        List<KQTaskBean> tasks = new ArrayList<>();
        for(Map.Entry<String, List<String>> mme: overtimeMap.entrySet()){
            String resid = mme.getKey();
            List<String> overList = mme.getValue();
            for(String date : overList){
                SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks);
            }
        }
        if(!tasks.isEmpty()){
            KQQueue.writeTasks(tasks);
        }

        basebean.writeLog("---------------SyncKqDatasJob End---------------");

    }

    /**
     * 建模权限重构
     * @param userId
     * @param jobGroupDesModeId
     * @param billid
     */
    public void modePerRecon(Integer userId, String jobGroupDesModeId, String billid) {
        ModeRightInfo ModeRightInfo = new ModeRightInfo();
        ModeRightInfo.setNewRight(true);
        ModeRightInfo.editModeDataShare( userId, Integer.parseInt(jobGroupDesModeId), Integer.parseInt(billid));
    }
}
