package com.engine.msgcenter.dao;

import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.msgcenter.constant.HrmPracticalConstant;
import com.engine.msgcenter.constant.PageUidConstant;
import com.engine.msgcenter.entity.HrmType;
import com.engine.msgcenter.util.MsgECToEM;
import com.engine.msgcenter.util.MsgPushLogUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.DBUtil;
import weaver.conn.RecordSet;
import weaver.conn.constant.DBConstant;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * @ Date       ：Created in 2019/1/15 14:50 by mhw
 */
public class MsgTypeConfigDao {

    public WeaResultMsg contextConfig(Map<String, Object> params, User user) {

        WeaResultMsg resultMsg = new WeaResultMsg(false);
        RecordSet recordSet = new RecordSet();
        String guid = java.util.UUID.randomUUID().toString().replace("-", "");
        String date = MsgPushLogUtil.getNowDate();
        String time = MsgPushLogUtil.getNowTime();
        String flag = Util.null2String(params.get("flag"));
        //params
//        String id = Util.null2String(params.get("id"));
        String config_id = Util.null2String(params.get("config_id"));
        String contextType = Util.null2String(params.get("contextType"));
        String detailType = Util.null2String(params.get("detailType"));
        String contextPath = Util.null2String(params.get("contextPath"));
        try {
            if (StringUtils.equals(flag, "add")) {
                String sql = "insert into ecology_biz_mobile_context (id,config_id,contexttype,detailtype,contextpath,creater,createdate,createtime,modifydate,modifytime) values(?,?,?,?,? ,?,?,?,?,?)";
                recordSet.executeUpdate(sql, guid, config_id, contextType, detailType, contextPath, user.getUID(), date, time, date, time);
                return resultMsg.success();
            } else if (StringUtils.equals(flag, "update")) {
                if (StringUtils.isBlank(config_id))
                    return resultMsg.fail("id is empty");
                String sql = "update ecology_biz_mobile_context set contexttype=?,contextpath=?,detailtype=? where config_id=?";
                recordSet.executeUpdate(sql, contextType, contextPath, detailType, config_id);
                return resultMsg.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return resultMsg.fail(e.getMessage());
        }
        return resultMsg;
    }

    public boolean hasAgentid(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select agentid from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        if (org.apache.commons.lang.StringUtils.isNotBlank(recordSet.getString("agentid")))
            return true;
        return false;
    }

    public String getMsgTypeids(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select messagetypeid from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("messagetypeid");
    }

    public String getAgentid(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select agentid from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("agentid");
    }

    public static String getStatus(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select status from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("status");
    }

    public static String getEMStatus(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select em_status from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("em_status");
    }

    public static String getPC_Dialogurl(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select dialogurl from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("dialogurl");
    }

    public static String getAPP_Dialogurl(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select em_app_url from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("em_app_url");
    }

    public static String getAgentids(String ids) {
        RecordSet recordSet = new RecordSet();
        String sql = "select agentid from ecology_biz_mobile_config where id=?";
        String[] idString = Util.splitString(ids, ",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < idString.length; i++) {
            recordSet.executeQuery(sql, idString[i]);
            recordSet.next();
            if ("n".equals(recordSet.getString("isdefault")))
                sb.append(recordSet.getString("agentid")).append(",");
        }
        return sb.toString();
    }

    public void insertContextConfig(String config_id, String contextType, String detailType, String contextPath, String otherparam, String userid) {
        RecordSet recordSet = new RecordSet();
        String date = MsgPushLogUtil.getNowDate();
        String time = MsgPushLogUtil.getNowTime();
        String sql = "insert into ecology_biz_mobile_context " +
                "(id, config_id, contexttype, detailtype, contextpath, otherparam, creater, createdate, createtime, modifydate, modifytime) " +
                "values(?,?,?,?,? ,?,?,?,?,?, ?)";
        recordSet.executeUpdate(sql, config_id, config_id, contextType, detailType, contextPath, otherparam, userid, date, time, date, time);
        return;
    }

    public void updateCC(String config_id, String contextType, String contextPath, String detailType, String otherparam) {
        RecordSet recordSet = new RecordSet();
        String date = MsgPushLogUtil.getNowDate();
        String time = MsgPushLogUtil.getNowTime();
        String sql = "update ecology_biz_mobile_context set contexttype=?, contextpath=?, detailtype=?, otherparam=?, modifydate=?, modifytime=? where config_id=?";
        recordSet.executeUpdate(sql, contextType, contextPath, detailType, otherparam, date, time, config_id);
        return;
    }

    public String backfields() {
        RecordSet recordSet = new RecordSet();
        String fields = " t.em_status,t.id, t.name, t.isdefault,t.broadcaster,t.sendrange, t2.groupname, t3.name as gname, t.messagetypeid, t.moduleid, t.agentid, t.dialogurl, t.imgurl, t.enable, t.enableem, t.enablepc, t.sendmobile, t.config, t.description, concat(concat(t.createdate, ' '),t.createtime) as tcretime, concat(concat(t.modifydate, ' '),t.modifytime) as tmodtime";
        if (DBConstant.DB_TYPE_SQLSERVER.equalsIgnoreCase(recordSet.getDBType())) {
            fields = " t.em_status,t.id, t.name, t.isdefault,t.broadcaster,t.sendrange, t2.groupname, t3.name as gname, t.messagetypeid, t.moduleid, t.agentid, t.dialogurl, t.imgurl, t.enable, t.enableem, t.enablepc, t.sendmobile, t.config, t.description, t.createdate+' '+t.createtime as tcretime, t.modifydate+' '+t.modifytime as tmodtime";
        }
        return fields;
    }

    public String sqlForm(String radioType, Map<String, Object> params) {
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        String sql = "ecology_biz_mobile_config t left join ecology_message_group t2 on t.moduleid=t2.id left join ecology_biz_mobile_group t3 on t.groupid=cast(t3.id as varchar)";
        bb.writeLog("rs.getDBType():"+rs.getDBType());
		if ("mysql".equalsIgnoreCase(rs.getDBType())){
            sql = "ecology_biz_mobile_config t left join ecology_message_group t2 on t.moduleid=t2.id left join ecology_biz_mobile_group t3 on t.groupid=cast(t3.id as char)";
        } else if ("oracle".equalsIgnoreCase(rs.getDBType())) {
            sql = "ecology_biz_mobile_config t left join ecology_message_group t2 on t.moduleid= to_char(t2.id) left join ecology_biz_mobile_group t3 on t.groupid= to_char(t3.id) ";
        }
        bb.writeLog("sql:"+sql);
        if (HrmPracticalConstant.RADIO_TYPE.equals(radioType)) {
            String objectValue = Util.null2String(params.get("objectValue"));
            String objectType = Util.null2String(params.get("objectType"));
            if (StringUtils.isNotBlank(objectValue) || "6".equals(objectType))
                sql += " inner join ";
            else
                sql += " left join ";
            sql += " ( SELECT DISTINCT configid from ECOLOGY_HRMRESOURCE_PERMISSION t4 where 1 =1 ";

            if ("6".equals(objectType)){
                sql += " and t4.permissionType='broadCaster' and t4.objectType=" + objectType + "";

            }
            else if (org.apache.commons.lang.StringUtils.isNotBlank(objectType) && StringUtils.isNotBlank(objectValue)) {
                sql += " and t4.permissionType='broadCaster'";
                sql += " and t4.objectType=" + objectType + "";
                if (HrmType.EVERYONE != HrmType.getHrmType(objectType))
                    sql += " and t4.objectValue in ('" + objectValue.replaceAll(",", "','") + "')";
            }
            sql += ") t5 on t.id = t5.configid";
        }
        return sql;
    }

    public Map<String, Object> selectMapById(String id) {
        Map<String, Object> datas = new HashMap<>();
        if (org.apache.commons.lang.StringUtils.isBlank(id))
            return datas;
        RecordSet recordSet = new RecordSet();
        String sql = "select * from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        if (recordSet.next()) {
            datas.put("id", id);
            datas.put("name", Util.null2String(recordSet.getString("name")));
            datas.put("biztypeid", Util.null2String(recordSet.getString("biztypeid")));
            datas.put("groupid", Util.null2String(recordSet.getString("groupid")));
            datas.put("moduleid", Util.null2String(recordSet.getString("moduleid")));
            datas.put("messagetypeid", Util.null2String(recordSet.getString("messagetypeid")));
            datas.put("agentid", Util.null2String(recordSet.getString("agentid")));
            datas.put("dialogurl", Util.null2String(recordSet.getString("dialogurl")));
            datas.put("imgurl", Util.null2String(recordSet.getString("imgurl")));
            datas.put("enable", Util.null2String(recordSet.getString("enable")));
            datas.put("enableem", Util.null2String(recordSet.getString("enableem")));
            datas.put("enablepc", Util.null2String(recordSet.getString("enablepc")));
            datas.put("sendmobile", Util.null2String(recordSet.getString("sendmobile")));
            datas.put("desc", Util.null2String(recordSet.getString("description")));
            datas.put("status", Util.null2String(recordSet.getString("status")));
            datas.put("createrid", Util.null2String(recordSet.getString("createrid")));
            datas.put("createtime", Util.null2String(recordSet.getString("createdate")) + " " + Util.null2String(recordSet.getString("createtime")));
            datas.put("latest_modifytime", Util.null2String(recordSet.getString("modifydate")) + " " + Util.null2String(recordSet.getString("modifytime")));
        }
        sql = "select contexttype,contextpath,detailtype,otherparam from ecology_biz_mobile_context where config_id=?";
        recordSet.executeQuery(sql, id);
        if (recordSet.next()) {
            datas.put("contexttype", Util.null2String(recordSet.getString("contexttype")));
            datas.put("contextpath", Util.null2String(recordSet.getString("contextpath")));
            datas.put("detailtype", Util.null2String(recordSet.getString("detailtype")));
            datas.put("otherparam", Util.null2String(recordSet.getString("otherparam")));
        }
        return datas;
    }

    public String mtcAddSql() {
        StringBuffer sb = new StringBuffer();
        String opType = "insert into ecology_biz_mobile_config ";
        String backfields = "(id, name, moduleid, groupid, messagetypeid, agentid, dialogurl, belongid, imgurl, config, enable, enablepc, enableem, sendmobile, isdefault, isShow, status, createrid, createdate, createtime, modifydate, modifytime)";
        String values = "(?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?)";
        String sql = sb.append(opType).append(backfields).append("values").append(values).toString();
        return sql;
    }

    public String mtcUpdateSql() {
        StringBuffer sb = new StringBuffer();
        String opType = "update ecology_biz_mobile_config set ";
        String backfields = "agentid=?, name=?, groupid=?, moduleid=?, messagetypeid=?, imgurl=?, picture_url=?, enable=?, enablepc=?, enableem=?, sendmobile=?, modifydate=?, modifytime=?,em_status = ?,pc_url = ? ,dialogurl = ? ,em_app_url = ? ";
        String sqlWhere = "id=?";
        String sql = sb.append(opType).append(backfields).append("where ").append(sqlWhere).toString();
        return sql;
    }

    /**
     * @description ：路径类型ids=>路径ids
     */
    public String getWfpath(String typeids) {
        StringBuffer sb = new StringBuffer();
        sb.append(",");
        RecordSet recordSet = new RecordSet();
        List<String> params = new ArrayList<>();
        Object[] objects = DBUtil.transListIn(typeids, params);
        String sql = "select distinct a.id,a.workflowname as name from workflow_base a where a.workflowtype in (" + objects[0] + ")";
        recordSet.executeQuery(sql, params);
        while (recordSet.next()) {
            sb.append(recordSet.getInt("id")).append(",");
        }
        return sb.toString();
    }

    public String deleteGroupSql(Object obj) {
        return "delete from ecology_biz_mobile_group where status='n' and id in (" + obj + ")";
    }

    public String batchCs(String flat, Object obj) {
        return "update ecology_biz_mobile_config set modifydate=?,modifytime=?,enable='" + flat + "' where id in (" + obj + ")";
    }

    public String getBelongid(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select belongid from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        if (recordSet.next())
            return recordSet.getString("belongid");
        return "";
    }

    public int getShowNum() {
        RecordSet recordSet = new RecordSet();
        String sql = "select max(shownum) as shownum from ecology_biz_mobile_group";
        recordSet.executeQuery(sql);
        recordSet.next();
        int shownum = recordSet.getInt("shownum");
        return ++shownum;
    }

    public String getTab(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select istab from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        recordSet.next();
        return recordSet.getString("istab");
    }

    public void updateEnableAndAgentid(String id, String agentid) {
        RecordSet recordSet = new RecordSet();
        String sql = "update ecology_biz_mobile_config set enable='y',agentid=? where id=?";
        recordSet.executeUpdate(sql, agentid, id);
        return;
    }

    public void updateAgentid(String id, String agentid) {
        RecordSet recordSet = new RecordSet();
        String sql = "update ecology_biz_mobile_config set agentid=? where id=?";
        recordSet.executeUpdate(sql, agentid, id);
        return;
    }

    public void updateEnable(String id, String enable) {
        RecordSet recordSet = new RecordSet();
        String sql = "update ecology_biz_mobile_config set enable=?,modifydate=?,modifytime=? where id=?";
        recordSet.executeUpdate(sql, PageUidConstant.ABLE_EM.equals(enable) ? PageUidConstant.DISABLE_EM : PageUidConstant.ABLE_EM, MsgPushLogUtil.getNowDate(), MsgPushLogUtil.getNowTime(), id);
        return;
    }

    public boolean checkMTCApp(String id) {
        RecordSet recordSet = new RecordSet();
        String sql = "select agentid,istab,imgurl,dialogurl,em_app_url,name,sendmobile from ecology_biz_mobile_config where id=?";
        recordSet.executeQuery(sql, id);
        String agentid = recordSet.getString("agentid");
        String istab = recordSet.getString("istab");
        String imgurl = recordSet.getString("imgurl");
        String name = recordSet.getString("istab");
        String sendmobile = recordSet.getString("sendmobile");
//        String dialogurl = MsgECToEM.getDialog_Url(id, istab);
        String app_Dialogurl = recordSet.getString("em_app_url");
        String pc_Dialogurl = recordSet.getString("dialogurl");
        if (StringUtils.isBlank(agentid)) {
            //创建em应用
            try {
                MsgECToEM msgECToEM = new MsgECToEM();
                agentid = msgECToEM.CreateMsgTypeApp(imgurl, name, null, app_Dialogurl, pc_Dialogurl, sendmobile);
                if (StringUtils.isNotBlank(agentid)) {
                    updateAgentid(id, agentid);
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return true;
        }
        return false;
    }

    public void updateMsgConfigStatus(String id, String config) throws Exception {
        if (StringUtils.isBlank(id))
            throw new Exception("invalid params");
        if ("y".equals(config) || "n".equals(config)) {
        } else
            throw new Exception("invalid params");
        RecordSet rs = new RecordSet();
        String sql = "update ecology_biz_mobile_config set config = ? where id = ?";
        rs.executeUpdate(sql, config, id);
    }

}
