package weaver.interfaces.workflow.action;

import cn.hutool.core.date.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * use:铭锋项目 入职申请单归档同步建模表信息到个人卡片
 * author：liuhao
 */
public class MingfengToPersonCardAction extends BaseBean implements Action{
    private final Logger log = LoggerFactory.getLogger(MingfengToPersonCardAction.class);
    private static Map<String,String> ybrgx = new HashMap<>();
    static {
        ybrgx.put("0","配偶");
        ybrgx.put("1","儿子");
        ybrgx.put("2","女儿");
        ybrgx.put("3","父亲");
        ybrgx.put("4","母亲");
        ybrgx.put("5","其他");
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        Map<String, String> mainTableDatas = new HashMap<>();
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for (Property property : properties) {
            mainTableDatas.put(property.getName(), property.getValue());
            log.error("howec:::::::key:"+property.getName());
            log.error("howec:::::::value:"+property.getValue());
        }
        //紧急联系人数据库表名
        String jjlxrbm = getPropValue("mingfengtopersoncard", "mf.jjlxrbm");
        //紧急联系人建模id
        String jjlixjmid = getPropValue("mingfengtopersoncard", "mf.jjlixjmid");
        //身份证地址
        String sfzdz = getPropValue("mingfengtopersoncard","mf.sfjdz");
        //教育经历建模id
        String jyjljmid = getPropValue("mingfengtopersoncard", "mf.jyjljmid");
        //社会工作记录建模id
        String shgzjljmid  =getPropValue("mingfengtopersoncard", "mf.shgzjljmid");
        //子女信息建模id
        String znxxjmid  =getPropValue("mingfengtopersoncard", "mf.znxxjmid");
        //入职资料建模id
        String rzzljmid  =getPropValue("mingfengtopersoncard", "mf.rzzljmid");
        //性别
        String xbid  =getPropValue("mingfengtopersoncard", "mf.xb");
        //户口类型
        String hklxid = getPropValue("mingfengtopersoncard", "mf.hklx");

//        //工龄证明附件id（工作信息自定义）
//        String glzmfjid  =getPropValue("mingfengtopersoncard", "mf.glzmfjid");
//        //身份证附件id（个人信息自定义）
//        String sfzfjid  =getPropValue("mingfengtopersoncard", "mf.sfzfjid");
        //applyid
        String applyid = mainTableDatas.get("applyid");
        if(applyid==null || applyid.length()==0) {
            log.error("-1 applyid不能为空！");
            return "-1 applyid不能为空！";
        }
        String xmsql = mainTableDatas.get("xmsql");
        if(xmsql==null || xmsql.length()==0) {
            log.error("-1 姓名SQL不能为空！");
            return "-1 姓名SQL不能为空！";
        }
        String sfzhm = mainTableDatas.get("sfzhm");
        if(sfzhm==null || sfzhm.length()==0) {
            log.error("-1 身份证号码不能为空！");
            return "-1 身份证号码不能为空！";
        }
        RecordSet recordSet11 = new RecordSet();
        String sql61 = "select count(id) as nums from uf_rzygxxb where zjhm = '"+sfzhm+"'";
        log.error("howec::::::::::::2.4:"+sql61);
        recordSet11.executeQuery(sql61);
        recordSet11.next();
        int nums = recordSet11.getInt("nums");
        if(nums == 0) {
            log.error("-1 请检查当前员工身份证号，和入职员工信息表无法匹配！");
            return "-1 请检查当前员工身份证号，和入职员工信息表无法匹配！";
        }
        log.error("howec::::::1---applyid:"+applyid+",xmsql:"+xmsql+",sfzhm:"+sfzhm);
        //紧急联系人
        //员工简历信息表-明细1（uf_ygjlxxb_dt1）
        RecordSet recordSet1 = new RecordSet();
        RecordSet recordSet2 = new RecordSet();
        RecordSet recordSet200 = new RecordSet();
        RecordSet recordSet201 = new RecordSet();
        //入职申请单
        String sql = "select a.applyid,b.xm,b.gx2,b.lxfs from uf_ygjlxxb_dt1 b inner join uf_ygjlxxb a on a.id = b.mainid where a.applyid = "+applyid;
        log.error("howec::::::::::::0.1:"+sql);
        recordSet1.executeQuery(sql);
        while (recordSet1.next()) {
            String xm = recordSet1.getString("xm");//姓名
            String gx = recordSet1.getString("gx2");//关系
            String lxfs = recordSet1.getString("lxfs");//联系电话
            log.error("howec::::::::::::0.2:xm:"+xm+",gx:"+gx+",lxfs:"+lxfs);

            String sql2 = "insert into uf_jtcyjl(ygxm,jtcyxm,ybrgx,lxfs,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values (?,?,?,?,?,?,?,?,?)";
            log.error("howec::::::::::::0.3:"+sql2);
            try {
                boolean flag = recordSet200.executeUpdate(sql2,xmsql,xm,gx,lxfs,jjlixjmid,"1","0", DateUtil.today(),DateUtil.formatTime(new Date()));
                log.error("howec::::::::::xxxx:"+flag);
                if (flag) {
                    String idSql = "SELECT max(id) as mid from uf_jtcyjl";
                    log.error("howec:::::::idsql:"+idSql);
                    recordSet201.execute(idSql);
                    recordSet201.next();
                    String id = recordSet201.getString("mid");
                    log.error("howec:::::::idsql1:"+id);
                    // 权限重构
                    permissionReconstruction(Util.getIntValue(id),Integer.parseInt(jjlixjmid));
                }

            } catch (Exception e) {
                writeLog("howec:::::::::::error:001");
                return "-1 紧急联系人同步失败，"+e.getMessage();
            }
        }


        String sqlzb = "select sjhm,xzz,hyqk,sfzdz,xb from uf_ygjlxxb where applyid = "+applyid;
        log.error("howec::::::::::::0.4:"+sqlzb);
        recordSet1.executeQuery(sqlzb);
        recordSet1.next();
        String sjhm = recordSet1.getString("sjhm");//手机号码
        String xzz = recordSet1.getString("xzz");//现住址
        String hyqk = recordSet1.getString("hyqk");// 婚姻状况
        String sfzdz1 = recordSet1.getString("sfzdz");//身份证地址
        String xb = recordSet1.getString("xb");//性别0男1女
        log.error("howec::::::::::::0.5::sjhm:"+sjhm+",xzz:"+xzz+",hyqk:"+hyqk+",sfzdz1:"+sfzdz1);
        //手机号码，婚育情况，现住址
        //更新手机号
        String sql3 = "update HrmResource set mobile = '"+sjhm+"',residentplace = '"+xzz+"',maritalstatus = '"+hyqk+"'  where id = "+xmsql;
        log.error("howec::::::::::::0.6:"+sql3);
        recordSet2.executeUpdate(sql3);
        //个人信息1身份证地址【自定义】
        String sq4 = "select count(id) as nums from cus_fielddata where scopeid = 1 and scope = 'HrmCustomFieldByInfoType' and id = "+xmsql;
        recordSet1.executeQuery(sq4);
        recordSet1.next();
        nums = recordSet1.getInt("nums");
        //身份证地址和性别
        if(nums == 0) {
            String sql5 = "insert into cus_fielddata("+sfzdz+","+xbid+",scopeid,scope,id) values (?,?,?,?,?)";
            recordSet1.executeUpdate(sql5,sfzdz1,xb,1,"HrmCustomFieldByInfoType",xmsql);
        }else {
            String sql5 = "update cus_fielddata set "+sfzdz+" = '"+sfzdz1+"',"+xbid+" = '"+xb+"' where id = "+xmsql+" and scopeid = 1 and scope = 'HrmCustomFieldByInfoType'";
            recordSet1.executeUpdate(sql5);
        }

        //教育经历
        String sql6 = "select a.applyid,b.xx,b.zy,b.rxsj,b.bysj,b.xl from uf_ygjlxxb_dt2 b inner join uf_ygjlxxb a on a.id = b.mainid where a.applyid = "+applyid;
        log.error("howec::::::::::::0.7:"+sql6);
        recordSet1.executeQuery(sql6);
        while (recordSet1.next()) {
            String xx = recordSet1.getString("xx");//学校
            String zy = recordSet1.getString("zy");//专业
            String rxsj = recordSet1.getString("rxsj");//入学时间
            String bysj = recordSet1.getString("bysj");//毕业时间
            String xl = recordSet1.getString("xl");//学历
            log.error("howec::::::::::::0.8:"+xx+","+zy+","+rxsj+","+bysj+","+xl);
            String sql2 = "insert into uf_jypxjl(ygxm,byxx,zy,rxsj,bysj,xl,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values (?,?,?,?,?,?,?,?,?,?,?)";
            log.error("howec::::::::::::0.9:"+sql2);
            try {
                boolean flag = recordSet200.executeUpdate(sql2,xmsql,xx,zy,rxsj,bysj,getEdu(xl),jyjljmid,"1","0", DateUtil.today(),DateUtil.formatTime(new Date()));
                writeLog(flag);
                if (flag) {
                    String idSql = "SELECT max(id) as mid from uf_jypxjl";
                    recordSet201.execute(idSql);
                    recordSet201.next();
                    String id = recordSet201.getString("mid");
                    // 权限重构
                    permissionReconstruction(Util.getIntValue(id),Integer.parseInt(jyjljmid));
                }

            } catch (Exception e) {
                writeLog("howec:::::::::::error:002");
                return "-1 教育经历同步失败，"+e.getMessage();
            }
        }
        //工作履历
        sql6 = "select a.applyid,b.gzdw,b.gzkssj,b.gzjssj,b.zw from uf_ygjlxxb_dt3 b inner join uf_ygjlxxb a on a.id = b.mainid where a.applyid = "+applyid;
        log.error("howec::::::::::::1.0:"+sql6);
        recordSet1.executeQuery(sql6);
        while (recordSet1.next()) {
            String gzdw = recordSet1.getString("gzdw");//单位
            String gzkssj = recordSet1.getString("gzkssj");//工作开始时间
            String gzjssj = recordSet1.getString("gzjssj");//工作结束时间
            String zw = recordSet1.getString("zw");//职位
            log.error("howec::::::::::::1.1:"+gzdw+","+gzkssj+","+gzjssj+","+zw+",");
            String sql2 = "insert into uf_shgzjl(ygxm,kssj,jssj,dwmc,zw,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values (?,?,?,?,?,?,?,?,?,?)";
            try {
                boolean flag = recordSet200.executeUpdate(sql2,xmsql,gzkssj,gzjssj,gzdw,zw,shgzjljmid,"1","0", DateUtil.today(),DateUtil.formatTime(new Date()));
                writeLog(flag);
                if (flag) {
                    String idSql = "SELECT max(id) as mid from uf_shgzjl";
                    recordSet201.execute(idSql);
                    recordSet201.next();
                    String id = recordSet201.getString("mid");
                    // 权限重构
                    permissionReconstruction(Util.getIntValue(id),Integer.parseInt(shgzjljmid));
                }

            } catch (Exception e) {
                writeLog("howec:::::::::::error:002");
                return "-1 工作履历同步失败，"+e.getMessage();
            }
        }
        //子女信息（卡片表单：uf_znqk）
        sql6 = "select b.znxm,b.zncsnyr from uf_rzygxxb_dt1 b inner join uf_rzygxxb a on a.id = b.mainid where a.zjhm = '"+sfzhm+"'";
        log.error("howec::::::::::::1.2:"+sql6);
        recordSet1.executeQuery(sql6);
        while (recordSet1.next()) {
            String znxm = recordSet1.getString("znxm");//子女姓名
            String zncsnyr = recordSet1.getString("zncsnyr");//子女出生年月日
            log.error("howec::::::::::::1.3:"+znxm+","+zncsnyr);
            String sql2 = "insert into uf_znqk(ygxm,znxm,zncsnyr,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values (?,?,?,?,?,?,?,?)";
            try {
                boolean flag = recordSet200.executeUpdate(sql2,xmsql,znxm,zncsnyr,znxxjmid,"1","0", DateUtil.today(),DateUtil.formatTime(new Date()));
                writeLog(flag);
                if (flag) {
                    String idSql = "SELECT max(id) as mid from uf_znqk";
                    recordSet201.execute(idSql);
                    recordSet201.next();
                    String id = recordSet201.getString("mid");
                    // 权限重构
                    permissionReconstruction(Util.getIntValue(id),Integer.parseInt(znxxjmid));
                }

            } catch (Exception e) {
                writeLog("howec:::::::::::error:002");
                return "-1 工作履历同步失败，"+e.getMessage();
            }
        }

        //主表同步
        sql6 = "select sfzsmj,xsxwzsmj,byzsmj,tjbg,lzzm,jtyxk,glzm,dzzjz,hklx2 from uf_rzygxxb where zjhm = '"+sfzhm+"'";
        log.error("howec::::::::::::1.4:"+sql6);
        recordSet1.executeQuery(sql6);
        recordSet1.next();
        String sfzsmj = recordSet1.getString("sfzsmj");//身份证
        String xsxwzsmj = recordSet1.getString("xsxwzsmj");//学士学位
        String byzsmj = recordSet1.getString("byzsmj");//毕业证
        String tjbg = recordSet1.getString("tjbg");//体检报告
        String lzzm = recordSet1.getString("lzzm");//离职证明
        String jtyxk = recordSet1.getString("jtyxk");//交通银行卡照片
        String glzm = recordSet1.getString("glzm");//工领证明
        String dzzjz = recordSet1.getString("dzzjz");//电子证件照
        String hklx2 = recordSet1.getString("hklx2");//户口类型

        //个人信息1 户口类型【自定义】
        sq4 = "select count(id) as nums from cus_fielddata where scopeid = 1 and scope = 'HrmCustomFieldByInfoType' and id = "+xmsql;
        recordSet1.executeQuery(sq4);
        recordSet1.next();
        nums = recordSet1.getInt("nums");
        if(nums == 0) {
            String sql5 = "insert into cus_fielddata("+hklxid+",scopeid,scope,id) values (?,?,?,?)";
            recordSet1.executeUpdate(sql5,hklx2,1,"HrmCustomFieldByInfoType",xmsql);
        }else {
            String sql5 = "update cus_fielddata set "+hklxid+" = '"+hklx2+"' where id = "+xmsql+" and scopeid = 1 and scope = 'HrmCustomFieldByInfoType'";
            recordSet1.executeUpdate(sql5);
        }

        log.error("howec::::::::::::1.5:"+sfzsmj+","+xsxwzsmj+","+byzsmj+","+tjbg+","+lzzm+","+jtyxk+","+glzm+","+dzzjz);
        String sql2 = "insert into uf_rzzl(yg,xsxw,byz,jtyxkzp,tjbg,lzzm,dzzjz,sfzfj,glzm,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            boolean flag = recordSet200.executeUpdate(sql2,xmsql,xsxwzsmj,byzsmj,jtyxk,tjbg,lzzm,dzzjz,sfzsmj,glzm,rzzljmid,"1","0", DateUtil.today(),DateUtil.formatTime(new Date()));
            if (flag) {
                String idSql = "SELECT max(id) as mid from uf_rzzl";
                recordSet201.execute(idSql);
                recordSet201.next();
                String id = recordSet201.getString("mid");
                // 权限重构
                permissionReconstruction(Util.getIntValue(id),Integer.parseInt(rzzljmid));
            }

        } catch (Exception e) {
            log.error("howec:::::::::::error:002");
            return "-1 工作履历同步失败，"+e.getMessage();
        }
//        //身份证附件：field42 个人信息1
//        sq4 = "select count(id) as nums from cus_fielddata where scopeid = 1 and scope = 'HrmCustomFieldByInfoType' and id = "+xmsql;
//        log.error("howec::::::::x1:::"+sq4);
//        recordSet1.executeQuery(sq4);
//        recordSet1.next();
//        nums = recordSet1.getInt("nums");
//        if(nums == 0) {
//            String sql5 = "insert into cus_fielddata("+sfzfjid+",scopeid,scope,id) values (?,?,?,?)";
//            recordSet1.executeUpdate(sql5,sfzsmj,1,"HrmCustomFieldByInfoType",xmsql);
//        }else {
//            String sql5 = "update cus_fielddata set "+sfzfjid+" = '"+sfzsmj+"' where id = "+xmsql+" and scopeid = 1 and scope = 'HrmCustomFieldByInfoType'";
//            recordSet1.executeUpdate(sql5);
//        }
//        //工龄证明:field42 工作信息3
//        sq4 = "select count(id) as nums from cus_fielddata where scopeid = 3 and scope = 'HrmCustomFieldByInfoType' and id = "+xmsql;
//        log.error("howec::::::::x1:::"+sq4);
//        recordSet1.executeQuery(sq4);
//        recordSet1.next();
//        nums = recordSet1.getInt("nums");
//        if(nums == 0) {
//            String sql5 = "insert into cus_fielddata("+glzmfjid+",scopeid,scope,id) values (?,?,?,?)";
//            recordSet1.executeUpdate(sql5,glzm,3,"HrmCustomFieldByInfoType",xmsql);
//        }else {
//            String sql5 = "update cus_fielddata set "+glzmfjid+" = '"+glzm+"' where id = "+xmsql+" and scopeid = 3 and scope = 'HrmCustomFieldByInfoType'";
//            recordSet1.executeUpdate(sql5);
//        }
        return "1";
    }

    /**
     * 权限重构
     * @param billId
     */
    private void permissionReconstruction(int billId,int modelid) {
        log.error("howec:::::::ffffffffffffx:"+billId);
        log.error("howec:::::::ffffffffffffb:"+modelid);
        ModeRightInfo ModeRightInfo = new ModeRightInfo();
        ModeRightInfo.setNewRight(true);
        ModeRightInfo.editModeDataShare(1,Util.getIntValue(modelid),billId);
        log.error("howec:::::::ffffffffffffbx:"+modelid);
    }


    private String getGxbr(String gx) {
        String keyresult = "";
        int flag = 0;
        for (Map.Entry<String, String> entry : ybrgx.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if(gx.equals(value)) {
                flag = 1;
                keyresult = key;
                break;
            }
        }
        if(flag == 0) {
            return "5";
        }
        return keyresult;
    }

    private String getEdu(String xl) {
        String rs = "";
        if("0".equals(xl)) {//初中及以下
            rs = "2";
        }else if("1".equals(xl)) {//中专
            rs = "5";
        }else if("2".equals(xl)) {//高中
            rs = "3";
        }else if("3".equals(xl)) {//大专
            rs = "6";
        }else if("4".equals(xl)) {//本科
            rs = "7";
        }else if("5".equals(xl)) {//硕士研究生
            rs = "8";
        }else if("6".equals(xl)) {//技校/职高
            rs = "4";
        }else if("7".equals(xl)) {//博士研究生
            rs = "9";
        }else {
            rs = "1";
        }
        return rs;
    }
}
