package com.engine.kq.cmd.reportfielddefine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQReportFieldComInfo;
import com.engine.kq.biz.KQReportFieldGroupComInfo;
import weaver.conn.DBUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.util.*;

public class SaveGroupCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;
    SimpleBizLogger.SubLogInfo subLogInfo;
    public SaveGroupCmd(Map<String, Object> params, User user) {
        this.user = user;
        this.params = params;

        this.logger = new SimpleBizLogger();
        BizLogContext logContext = new BizLogContext();
        logContext.setDateObject(new Date());
        logContext.setLogType(BizLogType.HRM_ENGINE);
        logContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQREPORT_DEFINED);
        logContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQREPORT_DEFINED);
        logContext.setParams(params);
        logger.setUser(user);//当前操作人

        String cmd = Util.null2String(params.get("cmd"));
        String mainSql = "";
        if(cmd.equals("save")){
            String id = Util.null2String(params.get("id"));
            if(id.length()==0)id="-1";
            mainSql = " select * from kq_report_field_group where id= " + id;
        }else{
            mainSql = " select * from kq_report_field_group";
        }
        logger.setMainSql(mainSql);//主表sql
        logger.setMainPrimarykey("id");//主日志表唯一key
        logger.setMainTargetNameColumn("groupname");

        subLogInfo = logger.getNewSubLogInfo();
        String subSql = " select * from kq_report_field";
        subLogInfo.setSubSql(subSql);
        subLogInfo.setSubPrimarykey("id");
        subLogInfo.setSubTargetNameMethod("com.engine.kq.util.KQTransMethod.getLabelName");
        subLogInfo.setSubMethodOtherParams("column:fieldlabel+" + user.getLanguage());
        subLogInfo.setGroupId("1");  //所属分组， 按照groupid排序显示在详情中， 不设置默认按照add的顺序。
        subLogInfo.setSubGroupNameLabel(33943); //在详情中显示的分组名称，不设置默认显示明细x
        logger.addSubLogInfo(subLogInfo);

        logger.before(logContext);

    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> retmap = new HashMap<String, Object>();
        String sql = "";
        RecordSetTrans rst = new RecordSetTrans();
        try {
            if (!HrmUserVarify.checkUserRight("KQReportFieldDefine:Add", user)) {
                retmap.put("status", "-1");
                retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
                return retmap;
            }

            String cmd = Util.null2String(params.get("cmd"));
            if(cmd.equals("save")){
                String id = Util.null2String(params.get("id"));
                if(id.length()>0) {
                    sql = " update kq_report_field_group set groupname=? where id=?";
                    rst.executeUpdate(sql,id);
                }else{
                    String groupname = Util.null2String(params.get("groupname"));
                    String isshow = "1";
                    sql = "insert into kq_report_field_group (groupname, isshow) values (?,?)";
                    rst.executeUpdate(sql,groupname, isshow);

                    rst.executeQuery("select max(id) from kq_report_field_group");
                    if (rst.next()) {
                        id = rst.getString(1);
                    }
                    sql = " update kq_report_field_group set showorder=id where id = ? ";
                    rst.executeUpdate(sql,id);
                }
                String mainSql = " select * from kq_report_field_group where id= " + id;
                logger.setMainSql(mainSql);//主表sql
                retmap.put("id", id);
            }else if(cmd.equals("savebatch")){
                List<String> lsDelGroupId = new ArrayList<String>();
                sql = " select id from kq_report_field_group ";
                rst.executeQuery(sql);
                while(rst.next()){
                    lsDelGroupId.add(rst.getString("id"));
                }
                String datas = Util.null2String(params.get("datas"));
                JSONArray jArray = JSON.parseArray(datas);
                if(jArray != null){
                    for(int i=0;i<jArray.size();i++){
                        JSONObject jObject = (JSONObject) jArray.get(i);
                        String id = Util.null2String(jObject.get("id"));
                        String groupname = Util.null2String(jObject.get("groupname"));
                        String isshow = Util.null2String(jObject.get("isshow"));
                        String showorder = Util.null2String(jObject.get("showorder"));
                        if(id.length()>0) {
                                lsDelGroupId.remove(id);
                            sql = "update kq_report_field_group set groupname=?,isshow=?,showorder=? where id = ?";
                            rst.executeUpdate(sql,groupname, isshow, showorder,id);
                        }else{
                            sql = "insert into kq_report_field_group (groupname, isshow, showorder) values (?,?,?)";
                            rst.executeUpdate(sql,groupname, isshow, showorder);
                        }
                    }
                }
                String delGroupIds = "";
                for(int i=0;i<lsDelGroupId.size();i++){
                    if(delGroupIds.length()>0){
                        delGroupIds+=",";
                    }
                    delGroupIds+=lsDelGroupId.get(i);
                }
                if(delGroupIds.length()>0){
                    List sqlParams = new ArrayList();
                    Object[] objects= DBUtil.transListIn(delGroupIds,sqlParams);

                    sql = " update kq_report_field set groupid=null where groupid in ("+objects[0]+")";
                    rst.executeUpdate(sql, sqlParams);

                    sql = "delete from kq_report_field_group where id in("+objects[0]+") ";
                    rst.executeUpdate(sql, sqlParams);
                }
            }

            boolean duplicate = false;
            List<String> lsGroupname = new ArrayList<>();
            sql = "  SELECT groupname from kq_report_field_group";
            rst.executeQuery(sql);
            while(rst.next()){
                String groupname = Util.formatMultiLang(rst.getString("groupname"),""+user.getLanguage());
                if(lsGroupname.contains(groupname)){
                    duplicate = true;
                    break;
                }
                lsGroupname.add(groupname);
            }

            if(duplicate){
                retmap.put("status", "-1");
                retmap.put("message",  SystemEnv.getHtmlLabelName(10000835,weaver.general.Util.getIntValue(user.getLanguage()))+"("+rst.getString("groupname")+")");
                rst.rollback();
            }else{
                rst.commit();
                new KQReportFieldComInfo().removeCache();
                new KQReportFieldGroupComInfo().removeCache();
                retmap.put("status", "1");
            }
        } catch (Exception e) {
            rst.rollback();
            this.writeLog(e);
            retmap.put("status", "-1");
            retmap.put("message", SystemEnv.getHtmlLabelName(382661, this.user.getLanguage()));
        }
        return retmap;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public List<BizLogContext> getLogContexts() {
        return logger.getBizLogContexts();
    }
}
