package com.engine.attendance.attendanceanalysis.cmd;

import com.engine.attendance.enums.CheckBoxEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.DateUtil;
import com.engine.common.util.DbTools;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 出勤结果数据入库
 */
@Slf4j
public class RecordDataCmd extends AbstractCommonCommand<Map<String,Object>> {

    public RecordDataCmd(Map<String, Object> params){
        this.params=params;
    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        //
        String userId = Util.null2String(params.get("userId"));
        //分析日期
        String analysisDate = Util.null2String(params.get("analysisDate"));
        //项目数据集合
        List<Map<String, Object>> recordDataList = (List<Map<String, Object>>)params.get("recordData");
        //日期类型
        String rqlx = Util.null2String(params.get("rqlx"));
        //班次
        List<Map<String,Object>> classInfo = (List<Map<String,Object>>)params.get("classInfo");
        //进出时间
        Map<String,Object> recordDataTime = (Map<String,Object>)params.get("recordDataTime");
        //出勤时间
        String attendanceDuration = Util.null2String(params.get("attendanceDuration"));

        Map<String,String> formmodeIdMap = (Map<String,String>)params.get("formmodeIdMap");

        String formmodeid = formmodeIdMap.get("uf_jcl_kq_cqjg");
        //出勤状态
        String cqzt = Util.null2String(params.get("cqzt"));
        //是否休息
        String sfxx = Util.null2String(params.get("sfxx"));

        if ("".equals(sfxx)){
            sfxx= CheckBoxEnum.UNCHECKED.getKey();
        }

        String sql = "select ygid,rq from uf_jcl_kq_cqjg where ygid=? and rq=?";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,userId,analysisDate);
        if (dataList.size() >0){
            sql = "update uf_jcl_kq_cqjg set cqsc="+attendanceDuration+",cqzt="+cqzt+",fxrq='"+DateUtil.getCurrentTime()+"',rqlx="+rqlx+",sfxx="+sfxx;
            if (classInfo.size() == 0 || classInfo.get(0).get("bcxx") == null || "".equals(classInfo.get(0).get("bcxx"))){
                sql = sql + ",bc=NULL,bcbdxx=NULL,";
            }else {
                sql = sql + ",bc="+classInfo.get(0).get("bcxx")+",bcbdxx='"+classInfo.get(0).get("bcsdxx")+"',";
            }
            for (int i =0;i<recordDataList.size();i++){
                String item = Util.null2String(recordDataList.get(i).get("item"));
                String itemduration = Util.null2String(recordDataList.get(i).get("itemduration"));
                int index = i+1;
                sql = sql + "xm"+index+"="+item+",";
                if (!"".equals(itemduration)){
                    sql = sql + "sc"+index+"="+itemduration+",";
                }
            }
            for (int i=recordDataList.size()+1;i<9;i++){
                sql = sql +"xm"+i+"=NULL,sc"+i+"=NULL,";
            }
            if (recordDataTime != null && recordDataTime.size() >0){
                for (Map.Entry<String,Object> entry : recordDataTime.entrySet()){
                    if (entry.getValue() == null || "NULL".equals(entry.getValue()) || "null".equals(entry.getValue())
                    ||"".equals(entry.getValue())){
                        sql = sql + entry.getKey()+"="+entry.getValue()+",";
                    }else {
                        sql = sql + entry.getKey()+"='"+entry.getValue()+"',";
                    }
                }
            }else {
                for (int i=1;i<9;i++){
                    sql = sql + "j"+i+"=NULL,c"+i+"=NULL,";
                }
            }

            sql = sql.substring(0,sql.length()-1) +" where ygid=? and rq=?";
            log.info("update sql : {}",sql);
            DbTools.update(sql,userId,analysisDate);
        }else {
            sql = "select subcompanyid1,departmentid,jobtitle from hrmresource  where id=?";
            List<Map<String,Object>> userList = DbTools.getSqlToList(sql,userId);
            sql = "insert into uf_jcl_kq_cqjg (szjg,ygid,fbid,bm,zw,rq,bc,bcbdxx,cqzt,cqsc,sjzt,fxrq,formmodeid,modeuuid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,rqlx,sfxx,";
            String cloumns = "";
            String value = "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,";
            List<Object> insertDatas = Lists.newArrayList();
            insertDatas.add(userList.get(0).get("subcompanyid1"));
            insertDatas.add(userId);
            insertDatas.add(userList.get(0).get("subcompanyid1"));
            insertDatas.add(userList.get(0).get("departmentid"));
            insertDatas.add(userList.get(0).get("jobtitle"));
            insertDatas.add(analysisDate);
            insertDatas.add(classInfo.size()>0?classInfo.get(0).get("bcxx"):null);
            insertDatas.add(classInfo.size()>0?classInfo.get(0).get("bcsdxx"):null);
            insertDatas.add(cqzt);
            insertDatas.add(attendanceDuration);
            insertDatas.add(1);
            insertDatas.add(DateUtil.getCurrentTime());
            insertDatas.add(formmodeid);
            insertDatas.add(UUID.randomUUID().toString());
            insertDatas.add(1);
            insertDatas.add(0);
            insertDatas.add(DateUtil.getCurrentDate());
            insertDatas.add(DateUtil.getCurrentTime().split(" ")[1]);
            insertDatas.add(rqlx);
            insertDatas.add(sfxx);
            for (int i =0;i<recordDataList.size();i++){
                int index = i+1;
                String item = Util.null2String(recordDataList.get(i).get("item"));
                String itemduration = Util.null2String(recordDataList.get(i).get("itemduration"));

                cloumns = cloumns+"xm"+index+",";
                value = value +"?,";
                insertDatas.add(item);
                if (!"".equals(itemduration)){
                    cloumns = cloumns + "sc"+index+",";
                    value = value +"?,";
                    insertDatas.add(itemduration);
                }
            }
            if (recordDataTime != null && recordDataTime.size() >0){
                for (Map.Entry<String,Object> entry : recordDataTime.entrySet()){
                    if (!"NULL".equals(entry.getValue())){
                        cloumns = cloumns + entry.getKey()+",";
                        value = value + "?,";
                        insertDatas.add(entry.getValue());
                    }
                }
            }
            if (!"".equals(cloumns)){
                cloumns = cloumns.substring(0,cloumns.length()-1);
            }else {
                sql = sql.substring(0,sql.length()-1);
            }
            value = value.substring(0,value.length()-1);
            sql  = sql +cloumns +") values ("+value+")";
            log.info("insert sql : {}",sql);
            log.info("insert data : {}",insertDatas);
            DbTools.update(sql,insertDatas.toArray());

        }
        updateWorkOverTimeDate(userId,analysisDate);
        return null;
    }

    public void updateWorkOverTimeDate(String userId,String date){
        String sql = "select id from uf_jcl_kq_cqjg where ygid=? and rq=?";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,userId,date);
        if (dataList.size() > 0){
            String id = Util.null2String(dataList.get(0).get("id"));
            RecordSetTrans rst = new RecordSetTrans();
            rst.setAutoCommit(false);
            try {
                sql = "delete from uf_jcl_kq_jbjg where lyid=?";
                rst.executeUpdate(sql,id);
                sql = "delete from uf_jcl_kq_jqye where lyid=?";
                rst.executeUpdate(sql,id);
                sql = "update uf_jcl_kq_jbjg set lyid =? where lyid=?";
                rst.executeUpdate(sql,id,userId+"-"+DateUtil.getCurrentDate());
                sql = "update uf_jcl_kq_jqye set lyid =? where lyid=?";
                rst.executeUpdate(sql,id,userId+"-"+DateUtil.getCurrentDate());
                rst.commit();
            }catch (Exception e){
                rst.rollback();
                log.error("updateWorkOverTimeDate error :{}",e);
            }
        }
    }

}
