package com.sifang.modules.flowable.utils;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class FormUtils {

    private static Logger logger = LoggerFactory.getLogger(FormUtils.class);

    public static final String AGENT_ADMISSION_APPLICATION= "01";        //代理商准入申请

    public static final String SUPPLIER_ADMISSION_APPLICATION= "02";     //供应商准入申请

    public static final String MARGIN_ADJUSTMENT_APPLICATION = "03";    //保证金调整申请

    public static final String DISTRIBUTION_ADJUSTMENT_APPLICATION = "04";    //授信额调整申请

    public static final String WITHDRAWAL_WARRANTY_APPLICATION = "05";      //质保金调整申请

    public static final String SUBCONTRACTING_STANDARD_PRICE_APPLICATION = "06";        //分包标准价申请

    public static final String SETTLE_AMOUNT_ADJUST_APPLICATION = "07";   //结算额调整申请

    public static final String INVEBNTORY_ORDER_APPLICATION = "10";   //盘点单申请Inventory

    public static final String TRANSFER_ORDER_APPLICATION = "11";   //调拨单申请

    public static final String SUPPLY_ORDER_APPLICATION = "08";   //订单申请

    public static final String PURCHASE_ORDER_APPLICATION = "09";   //采购申请

    public static final String CASH_OUT_APPLY = "12";   //请款申请


    public static final String PRICE_COEFFICIENT_APPLY = "14";   //零售价系数申请

    public static final String WAREHOUSE_APPLY = "13";   //仓库申请

    public static final String STOCK_UP_APPLY = "15";    //备货申请

    public static final String  BOND_LIMIT_APPLY="18";    // 保证金额度申请

    public static final String BRACKET_ACCOUNT_APPLY = "16";    //支架账户申请

    public static final String BRACKET_ORDER_APPLY = "17";    //现金下单申请

    public static final String ENTRY_STATUS_SJSH="91";  //设计审核
    public static final String ENTRY_STATUS_DASH="92";  //档案审核
    public static final String ENTRY_STATUS_AZYS="93";  //安装验收
    public static final String ENTRY_STATUS_BWYS="94";  //并网验收

    /**
     * 所有的变更审核 要走待办事项审批流程，默认审批人为原审核人员。
     * 以设计审核为例，查询电站最近一次的设计审核/设计变更审核人，然后本次设计变更审核人设置为查询结果。
     *
     * 设计变更审核 查询的是设计审核/设计变更审核人；
     * 客户信息变更审核 查询的是档案审核/客户信息变更审核人；
     * 勘测信息变更审核 查询的是设计审核/勘测信息变更审核人；
     * 完工信息变更审核 查询的是安装验收/完工信息变更审核人；
     * 物料信息变更审核 查询的是安装验收/物料信息变更审核人。
     */
    public static final String ENTRY_CHANGE_KCBG="95";  //勘测变更
    public static final String ENTRY_CHANGE_WGBG="96";  //完工变更
    public static final String ENTRY_CHANGE_SJBG="97";  //设计变更
    public static final String ENTRY_CHANGE_KHXXBG="98";  //客户信息变更
    public static final String ENTRY_CHANGE_WLXXBG="99";  //物料变更
    public static final String ENTRY_CHANGE_BWXXBG="100";  //并网信息变更



    /**
     * 获取流程设置信息
     * @param formId  b表单id
     *
     *
     */
    public static Record getdefLatest(String formId){
        String sql =" SELECT d.id,d.name,d.form_id,s.role_name FROM `crm_process_def_latest` l LEFT JOIN `crm_process_def` d ON d.id=l.process_def_id  " +
                "  LEFT JOIN `crm_process_def_submit_step` s ON s.proc_def_id=d.id " +
                " WHERE d.form_id=? and d.status ='0' ";
        return Db.findFirst(sql,formId);
    }

    public static String getSubmitRoleByDef(String defId){
        return Db.queryStr(" SELECT role_name FROM `crm_process_def_submit_step` s WHERE proc_def_id=? ",defId);
    }


    //获取表单提交节点的角色id
    public static Record submitRoleId(String formId){
        String sql=" SELECT s.role_id,s.submit_type,s.emp_user_id FROM `crm_process_def_latest` l LEFT JOIN `crm_process_def` d ON d.id=l.process_def_id " +
                " LEFT JOIN `crm_process_def_submit_step` s ON s.proc_def_id=d.id " +
                " WHERE d.form_id=? AND d.status ='0' ";
        return Db.findFirst(sql,formId);
    }

    //获取表单某个节点的审批设置
    public static Record getAuditRole(String formId,String name){
        String sql=" SELECT s.role_id,trans_department FROM `crm_process_def_latest` l LEFT JOIN `crm_process_def` d ON d.id=l.process_def_id " +
                "LEFT JOIN `crm_process_def_audit_step` s ON s.proc_def_id=d.id " +
                " WHERE d.form_id=? AND d.status ='0' AND s.name=? ";
        return Db.findFirst(sql,formId,name);
    }

    public static Integer getProcessSort(String processId,String taskName){
        return Db.queryInt("SELECT s.sort FROM `crm_process_def_audit_step` s WHERE s.proc_def_id=? AND s.name=? ",processId,taskName);
    }

    //获取部门的上级部门
    public static String getTopDepart(String deptId){
        String sql=" SELECT d.front_department FROM `crm_department` d WHERE id=? ";
        return Db.queryStr(sql,deptId);
    }

    //获取表单所有设置过得流程步骤
    public static Map<String,Record> getAllProcessByForm(String fromId){
        String sql="   SELECT CONCAT(s.proc_def_id,'_',s.`step_name`) AS sname,s.`role_id`,s.`trans_department` FROM `crm_process_def_audit_step` s " +
                "  LEFT JOIN `crm_process_def` d ON s.proc_def_id=d.`id` " +
                "  WHERE d.form_id=? ";
        List<Record> list=Db.find(sql,fromId);
        Map<String,Record> map=new HashMap<>();
        for(Record r:list){
            map.put(r.getStr("sname"),r);
        }
        return map;
    }

    //根据表单获取所有设置过的提交步骤
    public static Map<String,String> getAllProcessSubmitByForm(String fromId){
        String sql="   SELECT s.proc_def_id,s.`role_id` FROM `crm_process_def_submit_step` s " +
                "  LEFT JOIN `crm_process_def` d ON s.proc_def_id=d.`id` " +
                "  WHERE d.form_id=? ";
        List<Record> list=Db.find(sql,fromId);
        Map<String,String> map=new HashMap<>();
        for(Record r:list){
            map.put(r.getStr("proc_def_id"),r.getStr("role_id"));
        }
        return map;
    }

    //根据角色id 获取平台角色名称
    public static String getPlatformRoleName(String roleId){
        String sql=" SELECT r.name FROM `crm_platform_employee_role` r WHERE r.id=? ";
        return Db.queryStr(sql,roleId);
    }

    public static List<Record> getPlatformRoleNameByIds(String roleIds){
        String sql=" SELECT r.name FROM `crm_platform_employee_role` r WHERE r.id in("+ StringUtil.joinInSql(roleIds.split(","))+") ";
        return Db.find(sql);
    }



    //根据用户id, 获取代理商端的角色名称
    public static String getTraderRoleId(String userId){
        String sql=" SELECT  e.role_id FROM `crm_trader_employe` e WHERE e.user_id=? AND e.status='0' ";
        return Db.queryStr(sql, userId);
    }

    //根据proDefId 和  流程名称 获取目前是几级审批
    public static Integer getSortByDefIdName(String proDefId,String taskName){
        return Db.queryInt(" SELECT sort FROM `crm_process_def_audit_step` s WHERE s.proc_def_id=? AND s.name=?  ",proDefId,taskName);
    }
    //根据proDefId获取是否是最后一级审批
    public static Integer getMaxSortByProDefId(String proDefId){
        return Db.queryFirst("  SELECT sort FROM `crm_process_def_audit_step` s WHERE s.proc_def_id=? ORDER BY sort desc", proDefId);
    }

    public static List<Record> getDefAuditItems(String defId){
        return Db.find(" select role_id,role_name,audit_type,emp_user_id,audit_method,cc_user_id,s.sort, s.item_name from crm_process_def_audit_step s where s.proc_def_id=? order by s.sort asc",defId);
    }

    //根据角色 获取所有员工
    public static List<String> getPlateEmpUserIdByRoleId(String roleId,String province,String city,String traderId){
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT user_id FROM crm_platform_employee e LEFT JOIN crm_platform_employee_role_rel r ON e.id=r.employee_id ");
        sb.append(" WHERE e.status='0' AND FIND_IN_SET(?,r.role_ids) ");
        if(StringUtil.isNotBlank(province)){
            sb.append(" AND (e.provices='' OR FIND_IN_SET('"+province+"',e.provices)) ");
        }
        if(StringUtil.isNotBlank(city)){
            sb.append(" AND (e.city='' OR FIND_IN_SET('"+city+"',e.city) ) ");
        }
        if(StringUtil.isNotBlank(traderId)){
            sb.append(" AND (e.trader_id IS NULL OR e.trader_id='' OR FIND_IN_SET('"+traderId+"',e.trader_id))  ");
        }
        sb.append("  ORDER BY e.department_id DESC ");
        return Db.query(sb.toString(),roleId);
    }

    public static List<String> getFitUserEmpId(String empUserId,String province,String city,String traderId){
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT user_id FROM crm_platform_employee e  WHERE e.status='0' ");
        sb.append(" AND e.user_id IN("+ StringUtil.joinInSql(empUserId.split(","))+")");
        if(StringUtil.isNotBlank(province)){
            sb.append(" AND (e.provices='' OR FIND_IN_SET('"+province+"',e.provices)) ");
        }
        if(StringUtil.isNotBlank(city)){
            sb.append(" AND (e.city='' OR FIND_IN_SET('"+city+"',e.city) ) ");
        }
        if(StringUtil.isNotBlank(traderId)){
            sb.append(" AND (e.trader_id IS NULL OR e.trader_id='' OR FIND_IN_SET('"+traderId+"',e.trader_id))  ");
        }
        sb.append(" ORDER BY e.department_id DESC ");
        return Db.query(sb.toString());
    }

    public static String getOneStepTaskName(String defId){
        return Db.queryStr(" select item_name from crm_process_def_audit_step WHERE proc_def_id=? and sort=1 limit 1",defId);
    }

    public static String getLastAuditStep(String defId){
        return Db.queryStr(" select cc_user_id from crm_process_def_audit_step WHERE proc_def_id=? order by sort desc limit 1",defId);
    }

    /**
     * 审批流相关的 form keys
     */
    public static List<String> getProcessFormKeys() {
        List<String> keys = new ArrayList<>();
        for (int i = 1; i <= 18; i++) {
            keys.add(String.format("%02d", i));
        }
        return keys;
    }

    public static List<String> getProjectFormKeys() {
        List<String> keys = new ArrayList<>();
        keys.add("91");
        keys.add("92");
        keys.add("93");
        keys.add("94");
        keys.add("95");
        keys.add("96");
        keys.add("97");
        keys.add("98");
        keys.add("99");
        keys.add("100");
        return keys;
    }

}
