package com.engine.jucailinkq.attendance.workflow.action;

import com.engine.common.util.ServiceUtil;
import com.engine.jucailinkq.attendance.component.AttendanceCycle.service.AttendanceCycleService;
import com.engine.jucailinkq.attendance.component.AttendanceCycle.service.impl.AttendanceCycleServiceImpl;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: sy
 * @Description: 津贴确认流程，批准节点action
 * @Date: 2024/7/25
 **/
@Slf4j
public class AllowanceConfirmApproveAction implements Action {

    private AttendanceCycleService getAttendanceCycleService = ServiceUtil.getService(AttendanceCycleServiceImpl.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        log.info("AllowanceConfirmApproveAction,do action on request:" + requestInfo.getRequestid());
        String requestid = requestInfo.getRequestid();
        try {

            // 流程表单主表数据
            HashMap<String, String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
            String qrr = mainTableData.get("xjr");
            List<String> jtIdList = new ArrayList<>();
            List<String> ztUpdateList = new ArrayList<>();

            // 流程表单明细表数据
            List<Map<String, String>> detailTableData = CommonUtil.getDetailTableInfo(requestInfo,0);
            log.info("detailTableData:" + detailTableData);
            //收集明细表中津贴数据id
            jtIdList = detailTableData.stream().map(e->Util.null2String(e.get("jtid"))).collect(Collectors.toList());
            if (jtIdList.size() > 0) {
                //遍历比较哪些津贴数据的状态改变了，并将状态发生改变的津贴数据认定为要更新出勤结果数据状态的津贴数据
                String jtSql = "select id, zt from uf_jcl_kq_cqjt where id in (" + String.join(",", jtIdList) + ")";
                List<Map<String, Object>> jtDataList = DbTools.getSqlToList(jtSql);
                Map<String, String> jtStatusMap = jtDataList.stream().collect(Collectors.toMap(e->Util.null2String(e.get("id")), e->Util.null2String(e.get("zt"))));
                detailTableData.forEach(f -> {
                    if (StringUtils.isNotBlank(f.get("jtid"))) {
                        //收集需要更改出勤结果数据状态的人员、日期信息
                        if (!jtStatusMap.getOrDefault(f.get("jtid"), "").equals(Util.null2String(f.get("zt")))) {
                            ztUpdateList.add(f.get("jtid"));
                        }
                    }
                });
            }
            log.info("ztUpdateList_size:" + ztUpdateList.size());
            if (ztUpdateList.size() > 0) {
                /**
                 * 考勤周期检查
                 */
                Map<String, Object> params = Maps.newHashMap();
                params.put("userId",qrr);
                params.put("submitDate", DateUtil.getCurrentDate());
                params.put("submitStr","rq");
                //筛选出津贴状态发生变化的明细数据
                detailTableData = detailTableData.stream().filter(e -> ztUpdateList.contains(e.get("jtid"))).collect(Collectors.toList());
                params.put("submitDataList",detailTableData);
                log.info("params:" + params);
                Map<String,Object> dataMap = getAttendanceCycleService.getKqCycleCheckoutInfoCmd(params);
                log.info("dataMap:" + dataMap);
                List<Map<String,Object>> checkoutList = (List<Map<String,Object>>)dataMap.get("checkoutList");
                List<String> nocycleList = (List<String>)dataMap.get("nocycleList");

                boolean status = (boolean)dataMap.get("status");
                if (!status){
                    log.error("该人员没有考勤周期");
                    requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                    requestInfo.getRequestManager().setMessagecontent("该人员没有考勤周期！");
                    return Action.FAILURE_AND_CONTINUE;
                }
                if (checkoutList.size() > 0 || nocycleList.size() > 0){
                    String message = "";
                    if (nocycleList.size() > 0){
                        message = message +String.join(",",nocycleList)+"未找对对应的考勤周期；";
                    }
                    if (checkoutList.size() > 0){
                        List<String> list = checkoutList.stream().map(e->e.get("rq").toString()).collect(Collectors.toList());
                        message = message +String.join(",",list)+"对应的考勤周期的考勤周期已结账";
                    }
                    requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                    requestInfo.getRequestManager().setMessagecontent(message);
                    log.info(message);
                    return Action.FAILURE_AND_CONTINUE;
                }
            }

        } catch (Exception e) {
            log.debug("流程数据报错:AllowanceConfirmApproveAction:");
            StringWriter errorsWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(errorsWriter));
            log.debug(errorsWriter.toString());
            requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222");
            requestInfo.getRequestManager().setMessagecontent("【津贴确认批准action】报错，请联系管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
}
