package com.engine.htsc.contractmanagement.service.impl;

import com.engine.core.impl.Service;
import com.engine.cube.biz.CodeBuilder;
import com.engine.htsc.contractmanagement.cmd.*;
import com.engine.htsc.contractmanagement.service.ContractService;
import com.engine.htsc.contractmanagement.util.RecordChangeFieldLog;
import com.engine.htsc.contractmanagement.util.RecordChangeVersion;
import org.docx4j.wml.R;
import weaver.conn.RecordSet;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.text.SimpleDateFormat;
import java.util.*;

public class ContractServiceImpl extends Service implements ContractService {


    @Override
    public Map<String, Object> getChangeRecord(Map<String, Object> params) throws Exception {
        return commandExecutor.execute(new ChangeRecordCmd(params));
    }


    @Override
    public Map<String, Object> checkRepeatData(Map<String, Object> params) throws Exception {
        return commandExecutor.execute(new CheckRepeatDataCmd(params));
    }

    @Override
    public Map<String, Object> queryDataByCustId(Map<String, Object> params) throws Exception {
        RecordSet rs = new RecordSet();
        Map responseMap = new HashMap();
        responseMap.put("data",new ArrayList<>());
        String custId = (String) params.getOrDefault("custId","");
        String id = (String) params.getOrDefault("id","");
        if (custId.equals("") && id.equals("")){
            responseMap.put("code","500");
            responseMap.put("message","参数不能为空");
            return responseMap;
        }
        if (!"".equals(id)){
            return commandExecutor.execute(new QueryDataCmd(params));
        }else {
            rs.executeQuery("select id from uf_dsfgl where khwyid=? and scbs!=1 and fid is null",custId);
            if (rs.next()){
                Map<String,Object> paramMap = new HashMap();
                paramMap.put("id",rs.getString("id"));
                return commandExecutor.execute(new QueryDataCmd(paramMap));
            }
        }
        responseMap.put("code","400");
        responseMap.put("message","未查到数据");
        return responseMap;
    }

    @Override
    public Map<String, Object> queryDataByCertNo(Map<String, Object> params) throws Exception {
        RecordSet rs = new RecordSet();
        Map responseMap = new HashMap();
        List dataList = new ArrayList();
        responseMap.put("data",dataList);
        String certType = (String) params.getOrDefault("certType","");
        String certNo = (String) params.getOrDefault("certNo","");
        if (certType.equals("") || certNo.equals("")){
            responseMap.put("code","500");
            responseMap.put("message","参数不能为空");
            return responseMap;
        }
        rs.executeQuery("select a.* from uf_dsfgl_dt1 a left join uf_dsfgl b on a.mainid=b.id where a.zjlx=? and a.zjhm=? and b.fid is null",certType,certNo);
        if (rs.next()){
            List<Map<String,String>> detailList = new ArrayList();
            Map<String,String> detailMap = new HashMap<>();
            Map<String, Object> dataMap = new HashMap<>();
            String[] columns =  rs.getColumnName();
            for (String columnName :columns){
                detailMap.put(columnName.toLowerCase(),rs.getString(columnName));
            }
            detailList.add(detailMap);
            dataMap.put("detail1",detailList);
            dataList.add(dataMap);
            responseMap.put("code","0");
            return responseMap;
        }
        responseMap.put("code","400");
        responseMap.put("message","未查到数据");
        return responseMap;
    }

    @Override
    public Map<String, Object> addOrginfo(Map<String, Object> params) throws Exception {
        Map<String, Object> param = new HashMap<>();
        Map responseMap = new HashMap();
        Map map = new HashMap();
        for (Map.Entry<String, Object> entry:params.entrySet()){
            map.put(entry.getKey().toUpperCase(),entry.getValue());
        }
        params=map;

        responseMap.put("data",new ArrayList<>());
        if (params.get("KHWYID") == null || params.get("ZHTBSJ") == null){
            responseMap.put("code","400");
            responseMap.put("message","必填参数为空");
            return responseMap;
        }
        //添加默认值
        if (params.get("JGCRMSCLJ") == null){ //逻辑删除标记
            params.put("JGCRMSCLJ",1);
        }
        PropBean pb = new PropBean();
        String[] modeidAndFormid = pb.getPropName("counterpartyModeidAndFormid").split(",");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd&HH:mm:ss");
        String date = sdf2.format(new Date());
        params.put("MODEDATACREATEDATE",date.split("&")[0]);
        params.put("MODEDATACREATETIME",date.split("&")[1]);
        params.put("MODEDATACREATER","1");//默认创建者为系统管理员id
        params.put("MODEUUID",UUID.randomUUID().toString());
        params.put("MODEDATACREATERTYPE","0");
        params.put("FORMMODEID",modeidAndFormid[0]);
        params.put("DSFMC",params.get("ZWM"));
        params.put("DQBB","1");
        params.put("SCBS","0");
        params.put("DSFLX","1");
        params.put("ZT","5");//默认生效状态
        params.put("LY","1");

        param.put("uf_dsfgl",params);
        //添加数据
        Map<String, Object> resultMap = commandExecutor.execute(new AddContractDataCmd(param));
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_dsfgl where khwyid=?",params.get("KHWYID"));
        if (rs.next()){
            int id = rs.getInt("id");
            //添加对手方编号
            CodeBuilder codeBuilder = new CodeBuilder(Integer.valueOf(modeidAndFormid[0]));

            Map<String, Object> objectMap = codeBuilder.getModeCodeStr(-Integer.valueOf(modeidAndFormid[1].replace("-","").trim()),id);

            //记录变更记录日志
            recordChangeLog(id,"1","id","uf_dsfgl",params,"0");
            //记录变更快照
            RecordChangeVersion.recordChangeVersion(id,"uf_dsfgl");
        }


        return resultMap;
    }

    @Override
    public Map<String, Object> addCertificate(Map<String, Object> params) throws Exception {
        Map<String, Object> param = new HashMap<>();
        Map responseMap = new HashMap();
        Map map = new HashMap();
        for (Map.Entry<String, Object> entry:params.entrySet()){
            map.put(entry.getKey().toUpperCase(),entry.getValue());
        }
        params=map;
        responseMap.put("data",new ArrayList<>());
        String custId = (String) params.getOrDefault("GLKHWYID","");
        if (params.get("GLKHWYID") == null || params.get("ZJLX")==null ||params.get("ZJHM")==null ||
                params.get("ZHTBSJ")==null){
            responseMap.put("code","400");
            responseMap.put("message","必填参数为空");
            return responseMap;
        }
        //塞入默认值
        if (params.get("JGCRMSCLJ") == null){ //逻辑删除标记
            params.put("JGCRMSCLJ",1);
        }
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf2.format(new Date());
        params.put("CJSJ",date);
        params.put("ZJGXSJ",date);
        params.put("CJR","1");//默认创建者为系统管理员id
        params.put("GXR","1");

        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_dsfgl where khwyid=? and scbs!=1",custId);
        if (rs.next()){
            params.put("MAINID",rs.getString("id"));
            param.put("uf_dsfgl_dt1",params);
            //添加明细表1
            responseMap = commandExecutor.execute(new AddContractDataCmd(param));
            //记录变更记录日志
            recordChangeLog(rs.getInt("id"),"1","mainid","uf_dsfgl_dt1",params,"1");
            //记录变更快照
            RecordChangeVersion.recordChangeVersion(rs.getInt("id"),"uf_dsfgl");

            return responseMap;
        }
        responseMap.put("code","400");
        responseMap.put("message","该机构id的主表记录为空");
        return responseMap;
    }

    @Override
    public Map<String, Object> updateOrginfo(Map<String, Object> params) throws Exception {
        Map<String, Object> param = new HashMap<>();
        Map responseMap = new HashMap();
        Map map = new HashMap();
        for (Map.Entry<String, Object> entry:params.entrySet()){
            map.put(entry.getKey().toUpperCase(),entry.getValue());
        }
        params=map;
        if (params.get("KHWYID") == null || params.get("ID")==null ||params.get("ZHTBSJ")==null){
            responseMap.put("code","400");
            responseMap.put("message","必填参数为空");
            return responseMap;
        }
        //塞入默认值
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf2.format(new Date());
        params.put("MODEDATAMODIFYDATETIME",date);
        params.put("MODEDATAMODIFIER","1");
        if (params.get("ZWM") != null || !"".equals(params.get("ZWM"))){
            params.put("DSFMC",params.get("ZWM"));
        }


        //记录变更记录日志
        recordChangeLog(Integer.valueOf(params.get("ID").toString()),"2","id","uf_dsfgl",params,"0");
        //修改数据
        param.put("uf_dsfgl",params);
        responseMap = commandExecutor.execute(new UpdateContractDataCmd(param));
        //记录变更快照
        RecordChangeVersion.recordChangeVersion(Integer.valueOf(params.get("ID").toString()),"uf_dsfgl");

        return responseMap;
    }

    @Override
    public Map<String, Object> deleteOrginfo(Map<String, Object> params) throws Exception {
        params.put("JGCRMSCLJ","0");
        return updateOrginfo(params);
    }

    @Override
    public Map<String, Object> updateCertificate(Map<String, Object> params) throws Exception {
        Map<String, Object> param = new HashMap<>();
        Map responseMap = new HashMap();
        Map map = new HashMap();
        for (Map.Entry<String, Object> entry:params.entrySet()){
            map.put(entry.getKey().toUpperCase(),entry.getValue());
        }
        params=map;
        if (params.get("ID") == null || params.get("MAINID")==null ||params.get("ZHTBSJ")==null){
            responseMap.put("code","400");
            responseMap.put("message","必填参数为空");
            return responseMap;
        }
        //塞入默认值
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf2.format(new Date());
        params.put("ZJGXSJ",date);
        params.put("GXR","1");


        //记录变更记录日志
        recordChangeLog(Integer.valueOf(params.get("MAINID").toString()),"2","mainid","uf_dsfgl_dt1",params,"1");
        //修改数据
        param.put("uf_dsfgl_dt1",params);
        responseMap = commandExecutor.execute(new UpdateContractDataCmd(param));
        //记录变更快照
        RecordChangeVersion.recordChangeVersion(Integer.valueOf(params.get("MAINID").toString()),"uf_dsfgl");

        return responseMap;
    }

    @Override
    public Map<String, Object> deleteCertificate(Map<String, Object> params) throws Exception {
        params.put("JGCRMSCLJ","0");
        return updateCertificate(params);
    }


    public void recordChangeLog(int id,String operateType,String primaryName,String tableName,Map<String, Object> dataMap,String viewtype)throws Exception{
        PropBean pb = new PropBean();
        String[] modeidAndFormid = pb.getPropName("counterpartyModeidAndFormid").split(",");
        //记录变更记录日志
        Map<String, String> conditionMap = new HashMap<>();
        conditionMap.put("id",String.valueOf(id));
        conditionMap.put("modeId",modeidAndFormid[0]);
        conditionMap.put("formId",modeidAndFormid[1]);
        conditionMap.put("userId","1");
        conditionMap.put("primaryName",primaryName);
        conditionMap.put("operateType",operateType);
        conditionMap.put("viewtype",viewtype);
        RecordChangeFieldLog.recordChange(tableName,conditionMap,dataMap);
    }
}
