package com.engine.htsc.workflow.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.BrowserBean;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.hrm.biz.HrmFieldManager;
import com.engine.htsc.workflow.service.DesignatedProcessorSettingsService;
import com.engine.htsc.workflow.service.impl.DesignatedProcessorSettingsServiceImpl;
import com.engine.htsc.workflow.util.WorkflowUtil;
import com.engine.integration.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.wechat.util.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;
import java.util.stream.Collectors;

public class DesignatedProcessorSettingsAction {

    @GET
    @Path("/setting/designated/processor")
    @Produces({MediaType.TEXT_PLAIN})
    public String getDesignatedProcessors(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> responseData = new HashMap<>();
        Map<String, Object> requestParamMap = ParamUtil.request2Map(request);
        User user = HrmUserVarify.getUser(request, response);
        try {
            Map<String, Object> resultMap = getService().getDesignatedProcessor(requestParamMap);
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) resultMap.get("data");
            for (Map<String, Object> map : dataList) {
                List<Map<String, Object>> details = (List<Map<String, Object>>) map.get("details");
                for (Map<String, Object> detail : details) {
                    if (StringUtils.equals("3", Util.null2String(detail.get("fieldhtmltype")))) {
                        String fieldValue = Util.null2String(detail.get("fieldValue"));
                        Object realFieldValue;
                        if (StringUtils.equals("all", fieldValue) || StringUtils.equals("others", fieldValue)) {
                            realFieldValue = fieldValue;
                        } else {
                            String fielddbtype = Util.null2String(detail.get("fielddbtype"));
                            String fieldhtmltype = Util.null2String(detail.get("fieldhtmltype"));
                            String type = Util.null2String(detail.get("type"));
                            String fieldid = Util.null2String(detail.get("fieldid"));
                            List<Map<String, Object>> fieldValueList = (List<Map<String, Object>>) getItemDefaultValue(user, fieldValue, fielddbtype, fieldhtmltype, type, fieldid);
                            detail.put("realValue", fieldValueList);
                            realFieldValue = fieldValueList.stream()
                                    .map(e -> Utils.null2String(e.get("name"))).collect(Collectors.joining(","));
                        }
                        detail.put("value", realFieldValue);
                    }
                }
            }
            responseData.putAll(resultMap);
            responseData.put("api_status", true);
            responseData.put("api_errormsg", "");
        } catch (Exception e) {
            e.printStackTrace();
            responseData.put("api_status", false);
            responseData.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSON.toJSONString(responseData);
    }

    /**
     * 获取指定处理人配置表单字段,
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/setting/getAddFormfields")
    @Produces({MediaType.TEXT_PLAIN})
    public String getFormFields(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();
        String workflowid = request.getParameter("workflownum");
        System.out.println("workflowid*****" + workflowid);
        ConditionFactory conditionFactory = new ConditionFactory(user);
        //流程对应的配置字段
        List<SearchConditionGroup> fieldGroup = new ArrayList<>();
        List<SearchConditionItem> mainFieldItems = new ArrayList<>();
        List<SearchConditionItem> detailFieldItems = new ArrayList<>();

        try {
            //主表字段
            RecordSet rs = new RecordSet();
            String mainFieldsSql = " select b.* from workflow_bill a,workflow_billfield b " +
                    " where a.id=b.billid and a.tablename='uf_zdclrpz' and  detailtable is null order by b.dsporder ";
            rs.executeQuery(mainFieldsSql);
            while (rs.next()) {
                String fieldid = Util.null2String(rs.getString("id"));
                String fieldname = Util.null2String(rs.getString("fieldname"));
                String fielddbtype = Util.null2String(rs.getString("fielddbtype"));
                String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype"));
                String type = Util.null2String(rs.getString("type"));
                String fieldlabel = Util.null2String(rs.getString("fieldlabel"));
                SearchConditionItem fieldItem = getFieldItem(conditionFactory, fieldid, fieldname, fielddbtype, fieldhtmltype, type, fieldlabel, 3, 1);
                fieldItem.setRules("required");
                if (fieldname.equals("dqpzld") || fieldname.equals("gw")) {
                    fieldItem.setViewAttr(3);
                    String value = Util.null2String(request.getParameter(fieldname));
                    fieldItem.setValue(value);
                }
                System.out.println("基本信息*****" + JSONObject.toJSONString(fieldItem));
                mainFieldItems.add(fieldItem);
            }

            //获取流程字段
            rs.executeQuery(" select * from uf_lctjzd where lc=? ", workflowid);
            while (rs.next()) {
                String lczd = Util.null2String(rs.getString("lczd"));
                String zdlx = Util.null2String(rs.getString("zdlx"));
                String zdyw = Util.null2String(rs.getString("zdyw"));
                String lbid = Util.null2String(rs.getString("lbid"));
                String zdymlx = Util.null2String(rs.getString("zdymlx"));
                String zdzlx = Util.null2String(rs.getString("zdzlx"));
                //获取是不是多选
                String multipleSelect = Util.null2String(rs.getString("sfdx"));
                SearchConditionItem fieldItem = getFieldItem(conditionFactory, lczd, lczd, zdlx, zdymlx, zdzlx, lbid, 3, 1, StringUtils.equals("1", multipleSelect));
                fieldItem.setRules("required");
                System.out.println("基本信息*****" + JSONObject.toJSONString(fieldItem));
                detailFieldItems.add(fieldItem);
            }
            fieldGroup.add(new SearchConditionGroup("基本信息", true, mainFieldItems));
            fieldGroup.add(new SearchConditionGroup("指定条件配置", true, detailFieldItems));
            apidatas.put("fields", fieldGroup);
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * 获取指定处理人编辑表单字段
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/setting/getEditFormfields")
    @Produces({MediaType.TEXT_PLAIN})
    public String getEditFormFields(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();
        String dataid = request.getParameter("dataid");
        String designatedProcessorId = request.getParameter("designatedProcessorId");

        ConditionFactory conditionFactory = new ConditionFactory(user);
        List<SearchConditionGroup> fieldGroup = new ArrayList<>();
        List<SearchConditionItem> mainFieldItems = new ArrayList<>();
        List<SearchConditionItem> detailFieldItems = new ArrayList<>();

        try {
            RecordSet rs = new RecordSet();
            //查询当前编辑数据的主表数据
            Map<String, String> mainDataMap = new HashMap<>();
            rs.executeQuery(" select * from uf_zdclrpz where id=? ", new Object[]{dataid});
            if (rs.next()) {
                String columnNames[] = rs.getColumnName();
                for (int i = 0; i < columnNames.length; i++) {
                    String fieldName = columnNames[i].toLowerCase();
                    String fieldValue = Util.null2String(rs.getString(fieldName));
                    mainDataMap.put(fieldName, fieldValue);
                }
            }

            //主表字段
            String mainFieldsSql = " select b.* from workflow_bill a,workflow_billfield b " +
                    " where a.id=b.billid and a.tablename='uf_zdclrpz' and  detailtable is null order by b.dsporder ";
            rs.executeQuery(mainFieldsSql);
            while (rs.next()) {
                String fieldid = Util.null2String(rs.getString("id"));
                String fieldname = Util.null2String(rs.getString("fieldname"));
                String fielddbtype = Util.null2String(rs.getString("fielddbtype"));
                String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype"));
                String type = Util.null2String(rs.getString("type"));
                String fieldlabel = Util.null2String(rs.getString("fieldlabel"));
                SearchConditionItem fieldItem = getFieldItem(conditionFactory, fieldid, fieldname, fielddbtype, fieldhtmltype, type, fieldlabel, 3, 1);
                fieldItem.setRules("required");
                if (fielddbtype.startsWith("browser")) {
                    fielddbtype = fielddbtype.split("\\.")[1];
                } else {
                    fielddbtype = "";
                }
                Object fieldvalue = getItemDefaultValue(user, mainDataMap.get(fieldname), fielddbtype, fieldhtmltype, type, fieldid);
                setConditionItemDefaultValue(fieldItem, fieldvalue, 3);
                mainFieldItems.add(fieldItem);
            }

            //查询明细表数据
            String detailSql = "select zd,z,b.*,a.ZDCLR,c.LC from uf_zdclrpz_dt1 a join UF_ZDCLRPZ c on a.MAINID=c.ID join workflow_billfield b on b.ID = a.ZD\n" +
                    "where a.MAINID=? and dbms_lob.instr(ZDCLR,'%s')>0 order by zd desc";
            rs.executeQuery(String.format(detailSql, designatedProcessorId), dataid);
            Map<String, Boolean> cachedMap = new HashMap<>();
            String workflowid = "";
            Map<String,SearchConditionItem> searchConditionItemMap = new LinkedHashMap<>();
            while (rs.next()) {
                String fieldid = Util.null2String(rs.getString("zd"));
                String fieldValue = Util.null2String(rs.getString("z"));
                String fieldname = Util.null2String(rs.getString("fieldname"));
                String fielddbtype = Util.null2String(rs.getString("fielddbtype"));
                String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype"));
                String type = Util.null2String(rs.getString("type"));
                String lc = Util.null2String(rs.getString("lc"));
                workflowid = lc;
                String fieldlabel = Util.null2String(rs.getString("fieldlabel"));
                SearchConditionItem fieldItem = getFieldItem(conditionFactory, fieldid, fieldid, fielddbtype, fieldhtmltype, type, fieldlabel, 3, 1, isMulti(lc, fieldid, cachedMap));
                fieldItem.setRules("required");
                if (fielddbtype.startsWith("browser")) {
                    fielddbtype = fielddbtype.split("\\.")[1];
                } else {
                    fielddbtype = "";
                }
                Object fieldvalue = getItemDefaultValue(user, fieldValue, fielddbtype, fieldhtmltype, type, fieldid);
                setConditionItemDefaultValue(fieldItem, fieldvalue, 3);
                searchConditionItemMap.put(fieldid,fieldItem);
            }

            rs.executeQuery(" select * from uf_lctjzd where lc=? ", workflowid);
            while (rs.next()) {
                String lczd = Util.null2String(rs.getString("lczd"));
                detailFieldItems.add(searchConditionItemMap.get(lczd));
            }

            fieldGroup.add(new SearchConditionGroup("基本信息", true, mainFieldItems));
            fieldGroup.add(new SearchConditionGroup("指定条件配置", true, detailFieldItems));
            apidatas.put("fields", fieldGroup);
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }

    private boolean isMulti(String workflowid, String filedId, Map<String, Boolean> cacheMap) {
        Boolean cachedResult = cacheMap.get(filedId);
        if (cachedResult != null) {
            return cachedResult;
        }
        RecordSet rs = new RecordSet();
        //获取流程字段
        rs.executeQuery(" select * from uf_lctjzd where lc=? ", workflowid);
        while (rs.next()) {
            String lczd = Util.null2String(rs.getString("lczd"));
            String multipleSelect = Util.null2String(rs.getString("sfdx"));
            cacheMap.put(lczd, StringUtils.equals("1", multipleSelect));
        }
        cachedResult = cacheMap.get(filedId);
        return cachedResult != null && cachedResult;
    }

    /**
     * 删除指定处理人
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/setting/deleteFormFields")
    @Produces({MediaType.TEXT_PLAIN})
    public String deleteFormFields(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<>();
        String designatedProcessorId = request.getParameter("designatedProcessorId");
        String mainId = request.getParameter("mainId");
        RecordSet recordSet = new RecordSet();
        try {
            //更新主表数据
            String sqlTemplate = "delete from UF_ZDCLRPZ_DT1 where MAINID= ? and dbms_lob.instr(ZDCLR,'%s')>0";
            apidatas.put("success", recordSet.executeUpdate(String.format(sqlTemplate, designatedProcessorId), mainId));
            String sqlTemplateMain = "delete from UF_ZDCLRPZ where id= ? ";
            apidatas.put("success", recordSet.executeUpdate(sqlTemplateMain, mainId));
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * 保存指定处理人配置
     *
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/setting/saveFormfields")
    @Produces({MediaType.TEXT_PLAIN})
    public String saveFormfields(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        BaseBean bb = new BaseBean();
        Map<String, Object> apidatas = new HashMap<>();
        String baseParams = request.getParameter("baseparams");
        String settingParams = request.getParameter("settingparams");

        RecordSetTrans rts = new RecordSetTrans();
        rts.setAutoCommit(false);
        try {
            //更新主表数据
            JSONObject baseParamsJson = JSONObject.parseObject(baseParams);
            int dqpzld = baseParamsJson.getIntValue("dqpzld");
            String gw = Util.null2String(baseParamsJson.getString("gw"));
            String lc = Util.null2String(baseParamsJson.getString("lc"));
            String zdclr = Util.null2String(baseParamsJson.getString("zdclr"));
            String uuid = UUID.randomUUID().toString();
            String currentdate = TimeUtil.getCurrentDateString();
            String currenttime = TimeUtil.getOnlyCurrentTimeString();

            PropBean pb = new PropBean();
            String uf_zdclrpz_cubeuuid = pb.getPropName("UF_ZDCLRPZ_CUBEUUID");
            JSONObject jsonObject = pb.getModeInfoByUUID(uf_zdclrpz_cubeuuid);
            int formmodeid = Util.getIntValue(jsonObject.getString("modeid"));
            bb.writeLog("DesignatedProcessorSettingsAction-formmodeid:"+formmodeid);
            //int formmodeid = Util.getIntValue(bb.getPropValue("HtscFormmode", "uf_zdclrpz"), 2004);
            int creater = user.getUID();


            Integer mainId = null;
            //指定处理人可能出现同一个领导不同配置到同一个指定处理人的情况，因此将主表修改为每次插入新数据时同时插入主表
            //之前的逻辑是主表中，同一个当前配置领导只存在一条数据
            //2021-03-23 吴吉斌 013472
//            rts.executeQuery("select id from uf_zdclrpz where dqpzld=? and lc=? ", dqpzld, lc);
//            if (rts.next()) {
//                相同的
//                mainId = rts.getInt("id");
//
//            } else {
                String mainSql = " insert into uf_zdclrpz (dqpzld,gw,lc," +
                        "modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) " +
                        "values(?,?,?,?,?,?,?,?) ";
                boolean res = rts.executeUpdate(mainSql, dqpzld, gw, lc, creater, currentdate, currenttime, formmodeid, uuid);
                if (res) {
                    rts.executeQuery("select id from uf_zdclrpz where dqpzld=? and lc=? order by id desc", dqpzld, lc);
                    rts.next();
                    mainId = rts.getInt("id");
                }
//            }

            if (mainId != null) {
                //重构权限
                ModeRightInfo moderight = new ModeRightInfo();
                moderight.editModeDataShare(creater, formmodeid, mainId);
                //插入明细数据
                JSONObject settingParamsJson = JSONObject.parseObject(settingParams);
                Set<Map.Entry<String, Object>> entrySet = settingParamsJson.entrySet();
                for (java.util.Map.Entry<String, Object> entry : entrySet) {
                    String fieldname = entry.getKey();
                    if (!StringUtils.isNumeric(fieldname)) {
                        throw new RuntimeException("settingparams中Key数据格式不正确");
                    }
                    String fieldvalue = (String) entry.getValue();
                    rts.executeQuery(String.format("select * from uf_zdclrpz_dt1 where mainid=? and zd = ? and dbms_lob.instr(ZDCLR,'%s')>0", zdclr), mainId, fieldname);
                    if (rts.next()) {
                        String id = rts.getString("id");
                        rts.executeUpdate("update uf_zdclrpz_dt1 set z = ? where id = ?", fieldvalue, id);
                    } else {
                        rts.executeUpdate(" insert into uf_zdclrpz_dt1(mainid,zd,z,zdclr) values(?,?,?,?) ", mainId, fieldname, fieldvalue, zdclr);
                    }
                }
            }
            rts.commit();
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            rts.rollback();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }


    /**
     * 更新指定处理人配置
     *
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/setting/updateFormfields")
    @Produces({MediaType.TEXT_PLAIN})
    public String updateFormFields(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> apidatas = new HashMap<>();
        String dataid = request.getParameter("dataid");
        String baseParams = request.getParameter("baseparams");
        String settingParams = request.getParameter("settingparams");
        RecordSetTrans rts = new RecordSetTrans();
        rts.setAutoCommit(false);
        try {
            //更新主表数据，只更新修改时间
            JSONObject baseParamsJson = JSONObject.parseObject(baseParams);
            String zdclr = Util.null2String(baseParamsJson.getString("zdclr"));
            String modifyDatetime = TimeUtil.getCurrentTimeString();
            int modifier = user.getUID();
            String mainSql = " update uf_zdclrpz set  modedatamodifier=?,modedatamodifydatetime=? where id=? ";
            boolean res = rts.executeUpdate(mainSql, modifier, modifyDatetime, dataid);
            if (res) {
                JSONObject settingParamsJson = JSONObject.parseObject(settingParams);
                Set<Map.Entry<String, Object>> entrySet = settingParamsJson.entrySet();
                for (Map.Entry<String, Object> entry : entrySet) {
                    String fieldName = entry.getKey();
                    String fieldValue = (String) entry.getValue();
                    rts.executeUpdate("update uf_zdclrpz_dt1 set z=?,zdclr=? where zd=? and mainid=? ", fieldValue, zdclr, fieldName, dataid);
                }
            }
            rts.commit();
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            rts.rollback();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }


    public SearchConditionItem getFieldItem(ConditionFactory conditionFactory, String fieldid, String fieldname,
                                            String fielddbtype, String fieldhtmltype, String type, String fieldlabel, int viewAttr, int colSpan) {
        return getFieldItem(conditionFactory, fieldid, fieldname, fielddbtype, fieldhtmltype, type, fieldlabel, viewAttr, colSpan, false);
    }

    /**
     * 获取表单字段condition，
     *
     * @param conditionFactory
     * @param fieldid
     * @param fieldname
     * @param fieldhtmltype
     * @param type
     * @param fieldlabel
     * @param viewAttr
     * @param colSpan
     * @return
     */
    public SearchConditionItem getFieldItem(ConditionFactory conditionFactory, String fieldid, String fieldname,
                                            String fielddbtype, String fieldhtmltype, String type, String fieldlabel, int viewAttr, int colSpan, boolean isMutiple) {
        System.out.println("isMultiple*****" + isMutiple);
        SearchConditionItem fieldItem = null;
        if ("1".equals(fieldhtmltype)) {//输入框类型
            if ("1".equals(type)) { //文本
                fieldItem = conditionFactory.createCondition(ConditionType.INPUT, fieldlabel, fieldname);
            } else {//数值
                fieldItem = conditionFactory.createCondition(ConditionType.INPUTNUMBER, fieldlabel, fieldname);
            }
        }

        if ("2".equals(fieldhtmltype)) {//多行文本类型
            fieldItem = conditionFactory.createCondition(ConditionType.TEXTAREA, fieldlabel, fieldname);
        }

        if ("5".equals(fieldhtmltype)) {//下拉框类型
            fieldItem = conditionFactory.createCondition(ConditionType.SELECT, fieldlabel, fieldname);
            List<SearchConditionOption> selectOptions = WorkflowUtil.getSelectOptions(fieldid);
            fieldItem.setOptions(selectOptions);
            System.out.println("isMultiple*****" + isMutiple);
            fieldItem.setMultiple(isMutiple);
        }

        if ("3".equals(fieldhtmltype)) {
            if (isMutiple && "4".equals(type)) {
                fieldItem = conditionFactory.createCondition(ConditionType.BROWSER, fieldlabel, fieldname, "57");
            } else {
                fieldItem = conditionFactory.createCondition(ConditionType.BROWSER, fieldlabel, fieldname, type);
                fieldItem.setMultiple(isMutiple);
            }
            if ("161".equals(type)) {
                BrowserBean browserBean = fieldItem.getBrowserConditionParam();

                Map<String, Object> conditionParams = new HashMap<>();
                conditionParams.put("type", fielddbtype);
                browserBean.setConditionDataParams(conditionParams);

                Map<String, Object> completeParams = new HashMap<>();
                completeParams.put("type", type);
                completeParams.put("fielddbtype", fielddbtype);
                browserBean.setCompleteParams(completeParams);

                browserBean.getDestDataParams().put("type", fielddbtype);
                browserBean.getDataParams().put("type", fielddbtype);
                fieldItem.setBrowserConditionParam(browserBean);
            }
        }
        fieldItem.setColSpan(colSpan);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        fieldItem.setFieldcol(12);    //条件输入框所占宽度，默认值18
        fieldItem.setViewAttr(viewAttr);
        return fieldItem;
    }


    /**
     * 获取字段的默认值
     * 返回指定处理人表单以及默认值
     *
     * @param value
     * @param fieldhtmltype
     * @return
     */
    public Object getItemDefaultValue(User user, String value, String fiedlddbtype, String fieldhtmltype, String detailtype, String fieldid) {
        Object defaultValue = value;
        try {
            if ("3".equals(fieldhtmltype)) {
                List<Map<String, Object>> replaceDatas = new ArrayList<Map<String, Object>>();
                if (value.length() > 0) {
                    HrmFieldManager hrmFieldManager = new HrmFieldManager();
                    String fieldshowname = hrmFieldManager.getFieldvalue(user, fiedlddbtype, Util.getIntValue(fieldid), Util.getIntValue(fieldhtmltype), Util.getIntValue(detailtype), value, 0);
                    String[] fieldvalues = Util.splitString(value, ",");
                    String[] fieldshownames = Util.splitString(fieldshowname, ",");
                    if (detailtype.equals("257")) {
                        if (fieldshowname.endsWith("&nbsp")) {
                            fieldshowname = fieldshowname.substring(0, fieldshowname.length() - 5);
                        }
                        fieldshownames = Util.splitString(fieldshowname, "&nbsp");
                    }
                    for (int i = 0; fieldvalues != null && i < fieldvalues.length; i++) {
                        if (fieldvalues.length != fieldshownames.length) {
                            break;
                        }
                        if (Util.null2String(fieldshownames[i]).length() == 0) {
                            continue;
                        }
                        Map<String, Object> replaceData = new HashMap<String, Object>();
                        replaceData.put("id", fieldvalues[i]);
                        replaceData.put("name", fieldshownames[i]);
                        replaceDatas.add(replaceData);
                    }

                }
                return replaceDatas;
            }
        } catch (Exception e) {
            new BaseBean().writeLog(e);
        }

        return defaultValue;
    }


    private String SQL_TEMPLATE = "select h.LABELNAME as field_name, wb.FIELDHTMLTYPE as html_type,ud.ZD as fieldd_id,ud.ZD, ud.ZDCLR as" +
            "    designated_processor, wb.*,wb.ID as field_id,ud.Z as field_value,ud.WORKFLOWNAME as workflow_name,ud.DQPZLD,ud.LC,ud.main_id from" +
            "   (select uzd.*,wb.WORKFLOWNAME,uz.DQPZLD,uz.LC,uzd.MAINID as main_id  from UF_ZDCLRPZ_DT1 uzd join UF_ZDCLRPZ uz on uzd.MAINID=uz.ID JOIN WORKFLOW_BASE wb" +
            "       on uz.LC=wb.UNNUMBER %s)" +
            "       ud join WORKFLOW_BILLFIELD wb on ud.ZD = wb.ID join" +
            "        HTMLLABELINFO h on wb.FIELDLABEL = h.INDEXID and LANGUAGEID = 7";

    @GET
    @Path("/setting/designated/processorList")
    @Produces({MediaType.TEXT_PLAIN})
    public String getDesignatedProcessorsList(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> responseData = new HashMap<>();
        Map<String, Object> requestParamMap = ParamUtil.request2Map(request);
        String workflowId = Utils.null2String(requestParamMap.get("lc"));
        String workflowProcessorId = Utils.null2String(requestParamMap.get("dqpzld"));
        String workflowDesignatedProcessorId = Utils.null2String(requestParamMap.get("zdclr"));
        String conditions = buildConditions(workflowId, workflowProcessorId, workflowDesignatedProcessorId);
        String sql = String.format(SQL_TEMPLATE, conditions);

        try {
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql);
            List<Map<String, Object>> dataList = new ArrayList<>();
            String spanTemplate = "<a href=javaScript:openhrm(%s) onclick=pointerXY(event)>%s</a>&nbsp;";
            String lcSpanTemplate = "<span title='%s'>%s</span>&nbsp;";
            while (recordSet.next()) {
                Map<String, Object> data = new HashMap<>();
                String designatedProcessor = Utils.null2String(recordSet.getString("designated_processor"));
                String workflowName = recordSet.getString("workflow_name");
                String processorId = recordSet.getString("dqpzld");
                String mainId = recordSet.getString("main_id");
                String lc = recordSet.getString("lc");
                data.put("lc", lc);
                data.put("id", mainId);
                data.put("idspan", mainId);
                data.put("randomFieldId", mainId);
                data.put("randomFieldIdspan", "");
                data.put("lcspan", String.format(lcSpanTemplate, workflowName, workflowName));
                data.put("zdclr", designatedProcessor);
                data.put("dqpzld", processorId);
                dataList.add(data);
            }
            Map<String, Map<String, Object>> tempDataMap = new HashMap<>(dataList.size());
            Set<String> userIdSet = new HashSet<>();
            for (Map<String, Object> data : dataList) {
                tempDataMap.put(Utils.null2String(data.get("zdclr")), data);
                userIdSet.add(Utils.null2String(data.get("dqpzld")));
            }
            userIdSet.addAll(tempDataMap.keySet());
            Map<String, String> nameMap = queryProcessors(userIdSet);
            List<Map<String, Object>> resultDataList = tempDataMap.values().stream().map(map -> {
                String processorId = Utils.null2String(map.get("dqpzld"));
                map.put("dqpzldspan", String.format(spanTemplate, processorId, nameMap.get(processorId)));
                map.put("zdclr", nameMap.get(Utils.null2String(map.get("zdclr"))));
                return map;
            }).collect(Collectors.toList());
            responseData.put("data", resultDataList);
            responseData.put("api_status", true);
            responseData.put("api_errormsg", "");
        } catch (Exception e) {
            e.printStackTrace();
            responseData.put("api_status", false);
            responseData.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSON.toJSONString(responseData);
    }

    private Map<String, String> queryProcessors(Set<String> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return new HashMap<>();
        }
        String userIdListString = String.join(",", userIds);
        String sql = "select LASTNAME as last_name,ID as work_code from HRMRESOURCE where ID in (%s)";
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(String.format(sql, userIdListString));
        Map<String, String> processorsMap = new HashMap<>();
        while (recordSet.next()) {
            processorsMap.put(Utils.null2String(recordSet.getString("work_code")), Utils.null2String(recordSet.getString("last_name")));
        }
        return processorsMap;
    }

    public String buildConditions(String workflowId, String workflowProcessorId, String workflowDesignatedProceeorId) {
        StringBuilder stringBuilder = new StringBuilder();
        if (isNotEmpty(workflowId) || isNotEmpty(workflowProcessorId) || isNotEmpty(workflowDesignatedProceeorId)) {
            //where  uz.LC = 24 AND uz.DQPZLD = 5924 AND dbms_lob.instr(uzd.ZDCLR,'9569')>0
            stringBuilder.append(" WHERE ");
            if (isNotEmpty(workflowId)) {
                stringBuilder.append("uz.LC=");
                stringBuilder.append(workflowId);
                stringBuilder.append(" and ");
            }

            if (isNotEmpty(workflowProcessorId)) {
                stringBuilder.append("uz.DQPZLD=");
                stringBuilder.append(workflowProcessorId);
                stringBuilder.append(" and ");
            }

            if (isNotEmpty(workflowDesignatedProceeorId)) {
                stringBuilder.append("dbms_lob.instr(uzd.ZDCLR,'");
                stringBuilder.append(workflowDesignatedProceeorId);
                stringBuilder.append("')>0");
                stringBuilder.append(" and ");
            }
            stringBuilder.delete(stringBuilder.lastIndexOf(" and "), stringBuilder.length());
            return stringBuilder.toString();
        }
        return "";
    }

    private boolean isNotEmpty(String str) {
        return !StringUtils.isEmpty(str);
    }

    private void setConditionItemDefaultValue(SearchConditionItem var0, Object var1, int var2) {
        if (var0.getConditionType() == ConditionType.BROWSER) {
            var0.getBrowserConditionParam().setViewAttr(var2);
        } else {
            var0.setViewAttr(var2);
        }

        if (var1 != null) {
            Map var10;
            switch (var0.getConditionType()) {
                case INPUT:
                case DATEPICKER:
                case RESOURCEIMG:
                case CHECKBOX:
                case SWITCH:
                case TEXTAREA:
                case TIMEPICKER:
                    var0.setValue(var1);
                    break;
                case INPUTNUMBER:
                    var0.setValue(var1);
                    break;
                case SELECT:
                    List<SearchConditionOption> var3 = var0.getOptions();
                    String var4 = Util.null2String(var1);
                    if (!"".equals(var4)) {
                        Iterator<SearchConditionOption> var11 = var3.iterator();
                        while (var11.hasNext()) {
                            SearchConditionOption var12 = (SearchConditionOption) var11.next();
                            String[] selectedValues = var4.split(",");
                            boolean selected = false;
                            for (String selectedValue : selectedValues) {
                                selected = selectedValue.equals(var12.getKey());
                                if (selected) {
                                    break;
                                }
                            }
                            var12.setSelected(selected);
                        }
                    }
                    break;
                case DATE:
                    if (var1 != null) {
                        var10 = (Map) var1;
                        String var6 = Util.null2String((String) var10.get(var0.getDomkey()[0]));
                        if (!"".equals(var6)) {
                            List var7 = var0.getOptions();
                            Iterator var8 = var7.iterator();

                            while (var8.hasNext()) {
                                SearchConditionOption var9 = (SearchConditionOption) var8.next();
                                var9.setSelected(var6.equals(var9.getKey()));
                            }
                        }
                    }

                    var0.setValue(var1);
                    break;
                case SCOPE:
                    if (var1 != null) {
                        var10 = (Map) var1;
                        var0.setStartValue((String) var10.get("startValue"));
                        var0.setEndValue((String) var10.get("endValue"));
                    }
                    break;
                case BROWSER:
                    BrowserBean var5 = var0.getBrowserConditionParam();
                    if (var1 != null) {
                        var5.setReplaceDatas((List) var1);
                    }

                    var5.setViewAttr(var2);
                default:
                    var0.setValue(var1);

            }
        }
    }

    DesignatedProcessorSettingsService getService() {
        return ServiceUtil.getService(DesignatedProcessorSettingsServiceImpl.class);
    }

    DesignatedProcessorSettingsService getService(User user) {
        return ServiceUtil.getService(DesignatedProcessorSettingsServiceImpl.class, user);
    }

    @GET
    @Path("/setting/designated/table/data")
    @Produces({MediaType.TEXT_PLAIN})
    public String getTable(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<>();
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);
            apidatas.putAll(getService(user).getTable(ParamUtil.request2Map(request)));
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }

    @GET
    @Path("/setting/designated/table/condition")
    @Produces({MediaType.TEXT_PLAIN})
    public String getTableConditions(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<>();
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);
            apidatas.putAll(getService(user).getTableConditions(ParamUtil.request2Map(request)));
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }


}
