package com.engine.htsc.workflow.web;

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.BrowserInitUtil;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.engine.htsc.workflow.util.WorkflowUtil;
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.hrm.check.JobComInfo;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.interfaces.htsc.comInfo.PropBean;

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.*;

/**
 * Created by K1810006 on 2020/9/23.
 */
public class AssignProcessorAction {


    /**
     * 获取指定处理人配置表单字段
     * @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, Object>();
        String workflowid = request.getParameter("workflowid");

        ConditionFactory conditionFactory = new ConditionFactory(user);
        //流程对应的配置字段
        List<SearchConditionGroup> fieldGroup = new ArrayList<SearchConditionGroup>();
        List<SearchConditionItem> mainFieldItems = new ArrayList<SearchConditionItem>();
        List<SearchConditionItem> detailFieldItems = new ArrayList<SearchConditionItem>();

        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);


                }

                mainFieldItems.add(fieldItem);
            }


            //获取流程字段
            rs.executeQuery(" select * from uf_lctjzd where lc=? ",new Object[]{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"));

                SearchConditionItem  fieldItem = getFieldItem(conditionFactory,lczd,lczd,zdlx,zdymlx,zdzlx,lbid,3,1);
                fieldItem.setRules("required");
                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, Object>();
        String dataid = request.getParameter("dataid");


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

        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.setValue(mainDataMap.get(fieldname));
                fieldItem.setRules("required");
                if(fielddbtype.startsWith("browser")){
                    fielddbtype = fielddbtype.split("\\.")[1];
                }else{
                    fielddbtype = "";
                }
                Object fieldvalue = getItemDefaultValue(user,mainDataMap.get(fieldname),fielddbtype,fieldhtmltype,type,fieldid);
                BrowserInitUtil.setConditionItemDefaultValue(fieldItem, fieldvalue,3);
                mainFieldItems.add(fieldItem);
            }

            //查询明细表数据
            String detailSql = " select zd,z,b.* from uf_zdclrpz_dt1 a,workflow_billfield b " +
                    " where a.mainid=? and b.id=a.zd ";
            rs.executeQuery(detailSql,new Object[]{dataid});
            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 fieldlabel =  Util.null2String(rs.getString("fieldlabel"));
                SearchConditionItem  fieldItem = getFieldItem(conditionFactory,fieldid,fieldid,fielddbtype,fieldhtmltype,type,fieldlabel,3,1);
                fieldItem.setRules("required");
                // fieldItem.setValue(mainDataMap.get(fieldname));
                if(fielddbtype.startsWith("browser")){
                    fielddbtype = fielddbtype.split("\\.")[1];
                }else{
                    fielddbtype = "";
                }
                Object fieldvalue = getItemDefaultValue(user,fieldValue,fielddbtype,fieldhtmltype,type,fieldid);
                BrowserInitUtil.setConditionItemDefaultValue(fieldItem, fieldvalue,3);

                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
     */
    @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, Object>();
        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);
            int dqpzld = baseParamsJson.getIntValue("dqpzld");
            int cjbm = User.getUser(dqpzld,0).getUserDepartment();
            String gw = Util.null2String(baseParamsJson.getString("gw"));
            String lc = Util.null2String(baseParamsJson.getString("lc"));
            String cftj = Util.null2String(baseParamsJson.getString("cftj"));
            String zdclr = Util.null2String(baseParamsJson.getString("zdclr"));
            String uuid = UUID.randomUUID().toString();
            String currentdate = TimeUtil.getCurrentDateString();
            String currenttime = TimeUtil.getOnlyCurrentTimeString();
            //int formmodeid = Util.getIntValue(bb.getPropValue("HtscFormmode","uf_zdclrpz"),2004);

            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("AssignProcessorAction-formmodeid:"+formmodeid);

            int creater = user.getUID();
            String mainSql = " insert into uf_zdclrpz (dqpzld,gw,cjbm,lc,cftj,zdclr," +
                    "modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) " +
                    "values(?,?,?,?,?,?,?,?,?,?,?) ";
            boolean res = rts.executeUpdate(mainSql,new Object[]{dqpzld,gw,cjbm,lc,cftj,zdclr,creater,currentdate,currenttime,formmodeid,uuid});
            if(res){
                rts.executeQuery("select id from uf_zdclrpz where dqpzld=? and lc=? and zdclr=? ",
                        new Object[]{dqpzld,lc,zdclr});
                rts.next();
                int mainid = rts.getInt("id");
                //重构权限
                ModeRightInfo moderight = new ModeRightInfo();
                moderight.editModeDataShare(creater, formmodeid, mainid);
                //插入明细数据
                JSONObject settingParamsJson = JSONObject.parseObject(settingParams);
                Iterator iter = settingParamsJson.entrySet().iterator();
                while (iter.hasNext())
                {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String fieldname = (String)entry.getKey();
                    String fieldvalue = (String) entry.getValue();
                    rts.executeUpdate(" insert into uf_zdclrpz_dt1(mainid,zd,z) values(?,?,?) ", new Object[]{mainid,fieldname,fieldvalue});
                }
            }
            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);
        BaseBean bb = new BaseBean();
        Map<String, Object> apidatas = new HashMap<String, Object>();
        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 cftj = Util.null2String(baseParamsJson.getString("cftj"));
            String zdclr = Util.null2String(baseParamsJson.getString("zdclr"));
            String modifyDatetime = TimeUtil.getCurrentTimeString();
            int modifier = user.getUID();
            String mainSql = " update uf_zdclrpz set cftj=?,zdclr=?," +
                    " modedatamodifier=?,modedatamodifydatetime=? where id=? ";
            boolean res = rts.executeUpdate(mainSql,new Object[]{cftj,zdclr,modifier,modifyDatetime,dataid});
            if(res){
                //更新明细数据
                JSONObject settingParamsJson = JSONObject.parseObject(settingParams);
                Iterator iter = settingParamsJson.entrySet().iterator();
                while (iter.hasNext())
                {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String fieldname = (String)entry.getKey();
                    String fieldvalue = (String) entry.getValue();
                    rts.executeUpdate("  update uf_zdclrpz_dt1 set z=? where zd=? and mainid=? ", new Object[]{fieldvalue,fieldname,dataid});
                }
            }
            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
     */
    @GET
    @Path("/setting/getAssignUserList")
    @Produces({MediaType.TEXT_PLAIN})
    public String getAssignUserList(@Context HttpServletRequest request, @Context HttpServletResponse response){

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

        try {
            List<Map<String,Object>> userList = new ArrayList<>();
            //如果当前人员安全级别大于等于50 有配置权限
            if(Util.getIntValue(user.getSeclevel())>=50){
                Map<String,Object> userMap = getUserMap(user);
                userList.add(userMap);
            }

            RecordSet rs = new RecordSet();
            rs.executeQuery(" select bpzr from uf_pzrqxb where pzr=? ", new Object[]{user.getUID()});
            if(rs.next()){
                String bpzr = Util.null2String(rs.getString("bpzr"));
                String bpzrArr[] = bpzr.split(",");
                for(int i=0;i<bpzrArr.length;i++){
                    int id = Util.getIntValue(bpzrArr[i]);
                    User userItem = User.getUser(id,0);
                    Map userMap = getUserMap(userItem);
                    userList.add(userMap);
                }

            }
            apidatas.put("users",userList);
            apidatas.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("success", false);
        }
        return JSONObject.toJSONString(apidatas);
    }


    /**
     * 获取表单字段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){
        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);



        }

        if("3".equals(fieldhtmltype)){
            fieldItem = conditionFactory.createCondition(ConditionType.BROWSER,fieldlabel,fieldname,type);
            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;
    }



    /**
     * 获取表单字段condition
     * @param conditionFactory
     * @param fieldid  表单字段id
     * @param viewAttr 是否可编辑
     * @param colSpan 一行显示数
     * @return
     */
    public SearchConditionItem getFieldItem(ConditionFactory conditionFactory,String fieldid,int viewAttr,int colSpan){
        SearchConditionItem  fieldItem = null;
        RecordSet rs = new RecordSet();
        rs.executeQuery(" select * from workflow_billfield where id=? ",new Object[]{fieldid});
        if(rs.next()){
            String fieldname = Util.null2String(rs.getString("fieldname"));
            String fieldhtmltype =  Util.null2String(rs.getString("fieldhtmltype"));
            String fielddbtype =  Util.null2String(rs.getString("fielddbtype"));
            String type =  Util.null2String(rs.getString("type"));
            String fieldlabel =  Util.null2String(rs.getString("fieldlabel"));
            fieldItem = getFieldItem(conditionFactory,fieldid,fieldname,fielddbtype,fieldhtmltype,type,fieldlabel,viewAttr,colSpan);
        }
        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;
    }


    /**
     * user对象转为Map
     * @param user
     * @return
     */
    public Map<String,Object> getUserMap(User user){
        Map<String,Object> userMap = new HashMap<String,Object>();
        if(user!=null){
            userMap.put("uID",user.getUID());
            userMap.put("lastname",user.getLastname());
            userMap.put("seclevel",user.getSeclevel());
            userMap.put("sex",user.getSex());
            userMap.put("status",user.getStatus());
            userMap.put("account",user.getAccount());
            userMap.put("account_type",user.getAccount_type());
            userMap.put("userDepartment",user.getUserDepartment());
            userMap.put("userSubCompany1",user.getUserSubCompany1());
            userMap.put("loginid",user.getLoginid());
            userMap.put("email",user.getEmail());
            userMap.put("jobtitle",user.getJobtitle());


            try {
                JobComInfo jobComInfo = new JobComInfo();
                DepartmentComInfo deptComInfo = new DepartmentComInfo();
                String jobTitleName = jobComInfo.getJobName(user.getJobtitle());
                userMap.put("jobactivity",jobTitleName);
                String departmentName = deptComInfo.getDepartmentName(user.getUserDepartment()+"");
                userMap.put("departmentName",departmentName);

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return userMap;

    }




}
