package com.api.customization.qc3189074.util;

import com.alibaba.fastjson.JSON;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.ArrayList;
import java.util.List;

public class dataBuildJob extends BaseCronJob {
    String requestId;

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    @Override
    public void execute() {
        String tableName = new BaseBean().getPropValue("qc3189074","tableName");
        String tableDetailName = new BaseBean().getPropValue("qc3189074","tableDetailName");
        new BaseBean().writeLog("---dataBuildBegin--");
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        List<List<Object>> lsParam = new ArrayList<>();

        String sql = "select a.pbyf,a.kqz,b.* from "+ tableName+" a join "+ tableDetailName+" b " +
                "on a.id = b.mainid and a.requestid ="+getRequestId();
        new BaseBean().writeLog("dataBuildSql:" + JSON.toJSONString(sql));
        rs.executeQuery(sql);
        while (rs.next()){
            String kqMonth = rs.getString("pbyf");
            String kqgroupId = rs.getString("kqz");
            String resourceId = rs.getString("yg");
            String requestId = getRequestId();
            //先把这个人当月的排班删除掉
            delete(resourceId,kqMonth);

            for (int i = 1; i <= 31 ; i++) {
                String scheduleDate = "";
                if (i<10){
                    scheduleDate = kqMonth+"-0"+i;
                }else {
                    scheduleDate = kqMonth+"-"+i;
                }
                String serialId = rs.getString("bc"+i);
                String insertSql = "insert into kq_shiftschedule(kqdate,serialid,resourceid,groupid,isdelete,wfid,wfidstatus)"
                +"values(?,?,?,?,0,?,3)";
                rs1.executeUpdate(insertSql,scheduleDate,serialId,resourceId,kqgroupId,requestId);
            }
        }
        new BaseBean().writeLog("---dataBuildEnd--");

    }

    /**
     * 确保一天只有一个班次
     * @param resourceId
     */
    public void delete(String resourceId,String kqMonth){
        RecordSet rs = new RecordSet();
        String monthBeginDate = DateUtil.getFirstDayOfMonth(kqMonth+"-01");
        String monthEndDate = DateUtil.getLastDayOfMonth(kqMonth+"-01");
        String delSql = "update kq_shiftschedule set isdelete = 1"+
                        "where resourceid="+resourceId+" and kqdate between '"+monthBeginDate+"' and '"+monthEndDate+"'";
        rs.executeUpdate(delSql);
    }
}
