package com.api.customization.qc3189074.util;

import com.alibaba.fastjson.JSON;
import com.engine.kq.log.KQLog;
import com.wbi.util.Util;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *排班流程归档操作
 */
public class ScheduleAction implements Action   {
     KQLog log = new KQLog();
    @Override
    public String execute(RequestInfo requestInfo)  {
        try {
            log.info("==ScheduleActionBegin==");

            String tableName = new BaseBean().getPropValue("qc3189074","tableName");
            String tableDetailName = new BaseBean().getPropValue("qc3189074","tableDetailName");
            RecordSet rs = new RecordSet();
            CustomScheduleUtil customScheduleUtil = new CustomScheduleUtil();
            String requestid = requestInfo.getRequestid();
            Map<String,Map<String,Object>> scheduleMap = new HashMap<>();

            //获取当前日期和时间
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            String operateDate = now.format(dateFormatter); // 日期字符串
            String operateTime = now.format(timeFormatter); // 时间字符串
            //获取主表数据
            Map<String, String> mainDatas = new HashMap<>();
            Property[] properties = requestInfo.getMainTableInfo().getProperty();
            for (Property propertie : properties) {
                mainDatas.put(propertie.getName(), propertie.getValue());
            }
            //获取一些主表上的数据
            String kqMonth = Util.null2String(mainDatas.get("pbyf"));//排班月份
            String groupid = Util.null2String(mainDatas.get("kqz"));//排班考勤组
            String operateUser = Util.null2String(mainDatas.get("cjr"));//流程提交人
            String monthBeginDate = DateUtil.getFirstDayOfMonth(kqMonth+"-01");
            String monthEndDate = DateUtil.getLastDayOfMonth(kqMonth+"-01");
            String resourceIds = Util.null2String(mainDatas.get("pbmd"));
            Map<String, String> validateMap = customScheduleUtil.getValidateMap(resourceIds, groupid);//获取排班人员考勤组有效期范围

            //根据人员的有效开始日期和结束日期获取班次
            String sql = "select a.pbyf,a.kqz,b.* from "+ tableName+" a join "+ tableDetailName+" b " +
                    "on a.id = b.mainid and a.requestid ="+requestid;
            rs.executeQuery(sql);
            while (rs.next()){
                Map<String, Object> scheduleData = new HashMap<>();
                String resourceid = Util.null2String(rs.getString("yg"));//人员id
                String validatefrom = validateMap.get(resourceid + "|validatefrom");//人员开始生效日期
                String validateto = validateMap.get(resourceid + "|validateto");//人员开始结束日期
                if (validatefrom.compareTo(monthBeginDate) < 0){
                    validatefrom = monthBeginDate;
                }
                if (validateto.compareTo(monthEndDate) > 0){
                    validateto = monthEndDate;
                }


                LocalDate startDate = LocalDate.parse(validatefrom, dateFormatter);
                LocalDate endDate = LocalDate.parse(validateto, dateFormatter);
                scheduleData.put("validatefrom",validatefrom);
                scheduleData.put("validateto",validateto);
                scheduleData.put("groupid",groupid);

                // 遍历一下该人员生效范围内班次
                List<List<String>> params = new ArrayList<>();
                for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                    List<String> param = new ArrayList<>();
                    String scheduleDate = date.format(dateFormatter);//排班日期
                    int dayOfMonth = date.getDayOfMonth();
                    String columnName = "bc" + dayOfMonth;
                    String serialId = rs.getString(columnName);//班次id
                    //没有排班就不装了
                    if (serialId.length() <= 0)continue;
                    //封装下排班所需参数
                    param.add(resourceid);
                    param.add(scheduleDate);
                    param.add(serialId);
                    param.add(groupid);
                    param.add(requestid);
                    param.add("3");
                    //2025-03-27 加上操作日期和时间
                    param.add(operateDate);
                    param.add(operateTime);
                    params.add(param);
                }
                scheduleData.put("datas",params);
                scheduleMap.put(resourceid,scheduleData);
            }
            //开始插入数据吧
            for (Map.Entry<String, Map<String,Object>> entry : scheduleMap.entrySet()) {
                String key = entry.getKey();
                Map<String,Object> shceduleData = entry.getValue();
                //先把人员排班范围内的班次删了
                String validatefrom = Util.null2String(shceduleData.get("validatefrom"));
                String validateto = Util.null2String(shceduleData.get("validateto"));
                List<List> params =(List<List>) shceduleData.get("datas");
                //直接做删除吧
                String delSql = "delete from kq_shiftschedule where resourceid=? and kqdate between ? and ?";
                rs.executeUpdate(delSql,key,validatefrom,validateto);

                //2025-04-02 换个方式吧
                for (int i = 0; i < params.size(); i++) {
                    List dataList = params.get(i);
                    String resourceid_temp = Util.null2String(dataList.get(0));
                    String scheduleDate_temp = Util.null2String(dataList.get(1));
                    String serialId_temp = Util.null2String(dataList.get(2));
                    String groupid_temp = Util.null2String(dataList.get(3));
                    String requestid_temp = Util.null2String(dataList.get(4));
                    String status_temp = Util.null2String(dataList.get(5));
                    String operateDate_temp = Util.null2String(dataList.get(6));
                    String operateTime_temp = Util.null2String(dataList.get(7));

                    //再把班次插入进去吧
                    if ("2025-03-25".equals(scheduleDate_temp)){
                        log.info("==参数=="+resourceid_temp+" ｜ "+scheduleDate_temp+" ｜ "+serialId_temp+" ｜ "+groupid_temp+" ｜ "+" ｜ "+requestid_temp);
                    }
                    String inserSql = "insert into kq_shiftschedule(resourceid,kqdate,serialid,groupid,isdelete,wfid,wfidstatus,operateDate,operateTime,operateUser)"+
                            "values(?,?,?,?,0,?,?,?,?,?)";
                    boolean isInsert = rs.executeUpdate(inserSql, resourceid_temp, scheduleDate_temp, serialId_temp, groupid_temp, requestid_temp, status_temp, operateDate_temp, operateTime_temp, operateUser);
                    log.info("==isInsert=="+isInsert);
                }

            }
            //然后更改下状态
            String updateSql =  "update kq_flow_shiftschedule set wfidstatus=3,operateDate=?,operateTime=? where wfid=?";
            boolean isUpdate = rs.executeUpdate(updateSql,operateDate,operateTime,requestid);
            log.info("==isUpdate=="+isUpdate);

            //先用线程吧
            ThreadUtil threadUtil = new ThreadUtil(scheduleMap);
            Thread thread = new Thread(threadUtil);
            thread.start();
            log.info("==排班流程归档数据111=="+JSON.toJSONString(scheduleMap));
        } catch (Exception e) {
            new BaseBean().writeLog("执行报错:" + JSON.toJSONString(e));
        }
        return SUCCESS;
    }
}
