package com.sifang.modules.sys.util;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.utils.util.IsInteger;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

public class CrmUtils {

    public static String getUserXM(User user) {

        if ("1".equals(user.getUserType())) { // 平台管理员
            Record r = Db.findFirst("select name from crm_platform where user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("4".equals(user.getUserType())) { // 平台人员
            Record r = Db.findFirst("select name from crm_platform_employee where user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("3".equals(user.getUserType())) { // 服务商
            Record r = Db.findFirst("select name from crm_site where user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("5".equals(user.getUserType())) {  //服务商人员
            Record r = Db.findFirst("SELECT name FROM `crm_site_employee` WHERE user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("6".equals(user.getUserType())) {  //代理商
            Record r = Db.findFirst("SELECT name FROM `crm_trader` WHERE user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("7".equals(user.getUserType())) {  //代理商
            Record r = Db.findFirst("SELECT name FROM `crm_trader_employe` WHERE user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("8".equals(user.getUserType())) {  //供应商
            Record r = Db.findFirst("SELECT name FROM `crm_supply_supplier` WHERE user_id=?", user.getId());
            return r.getStr("name");
        }
        if ("9".equals(user.getUserType())) {
            Record r = Db.findFirst("select name from `crm_partner` where user_id = ?", user.getId());
            return r.getStr("name");
        }
        if ("a".equals(user.getUserType())) {
            Record r = Db.findFirst("select name from `crm_partner_staff` where user_id = ?", user.getId());
            return r.getStr("name");
        } else if ("0".equals(user.getUserType())) {
            return "admin";
        } else if ("2".equals(user.getUserType())) {
            return "guanliyuan";
        } else {
            throw new RuntimeException("user " + user + "is null ");
        }

    }

    public static String getUserXM(String userId) {
        UserDao userDao = SpringUtils.getBean(UserDao.class);
        User user = userDao.get(userId);
        return getUserXM(user);
    }

    public static String getUserRelId(User user) {

        if ("1".equals(user.getUserType())) { // 平台管理员

            Record r = Db.findFirst("select id from crm_platform where user_id=?", user.getId());
            return r.getStr("id");
        }
        if ("4".equals(user.getUserType())) { // 平台人员
            Record r = Db.findFirst("select id from crm_platform_employee where user_id=?", user.getId());
            return r.getStr("id");
        }
        if ("3".equals(user.getUserType())) { // 服务商
            Record r = Db.findFirst("select id from crm_site where user_id=?", user.getId());
            return r.getStr("id");
        }
        if ("5".equals(user.getUserType())) {//服务商人员
            Record r = Db.findFirst("select site_id from crm_site_employee where user_id=?", user.getId());
            return r.getStr("site_id");
        }
        if ("6".equals(user.getUserType())) {//代理商
            Record r = Db.findFirst("select id from crm_trader where user_id=?", user.getId());
            return r.getStr("id");
        }
        if ("7".equals(user.getUserType())) {//代理商人员
            Record r = Db.findFirst("select trader_id from crm_trader_employe where user_id=?", user.getId());
            return r.getStr("trader_id");
        } else {
            throw new RuntimeException("user " + user + "is null ");
        }

    }

    public static Record getUserTrader(String userType, String userId) {
        if (User.USER_TYPE_KJ.equals(userType)) {//代理商
            Record r = Db.findFirst("select t.id,t.type,t.parent_id,t.name,t.mobile from crm_trader t where t.user_id=?", userId);
            return r;
        } else if (User.USER_TYPE_ADVISOR.equals(userType)) {//代理商人员
            Record r = Db.findFirst(" SELECT t.id,t.type,t.parent_id,t.name,t.mobile,e.`data_authority` FROM `crm_trader` t LEFT JOIN crm_trader_employe e ON e.trader_id=t.`id` WHERE e.user_id=? ", userId);
            return r;
        } else {
            throw new RuntimeException("user " + userId + "is null ");
        }
    }

    public static String getPartnerId(String userId) {
        Record r = Db.findFirst("select partner_id from crm_partner_staff where user_id=?", userId);
        return r.getStr("partner_id");
    }

    /**
     * 获取服务商id
     *
     * @param user
     * @return
     */
    public static String getSiteId(User user) {
        String siteId;
        if (User.USER_TYPE_HUI.equals(user.getUserType())) {  //服务商人员
            siteId = Db.queryStr("SELECT a.site_id FROM crm_site_employee a WHERE a.user_id=? ", user.getId());
        } else if (User.USER_TYPE_FWS.equals(user.getUserType())) {  //服务商
            siteId = Db.queryStr("select s.id from crm_site s where s.status IN('0','2','4') and s.user_id =? ", user.getId());
        } else {
            return "";
        }
        return siteId;
    }

    /***
     * 获取服务商人员的siteId ***
     */
    public static String getSite(String userId) {
        Record r = Db.findFirst("select site_id from crm_site_employee where user_id=?", userId);
        return r.getStr("site_id");
    }

    public static String getCurrentTraderId(User user) {
        if (!StringUtils.endsWithAny(user.getUserType(), "6", "7")) {
            throw new IllegalArgumentException("该用户非代理商");
        }
        if ("6".equals(user.getUserType())) {
            return getTraderIdByUserId(user.getId());
        }
        return getTraderId(user.getId());
    }

    public static String getCurrentTraderId(String userId) {
        UserDao userDao = SpringUtils.getBean(UserDao.class);
        User user = userDao.get(userId);
        return getCurrentTraderId(user);
    }

    /***
     * 获取代理商人员的traderId ***
     */
    public static String getTraderId(String userId) {
        Record r = Db.findFirst("select trader_id from crm_trader_employe where user_id=?", userId);
        return r.getStr("trader_id");
    }

    public static String getparentId(String userId) {
        Record r = Db.findFirst("select parent_id from crm_trader_employe where user_id=?", userId);
        return r.getStr("parent_id");
    }

    public static String getParentIdByUserId(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("select s.parent_id from crm_trader s where s.status ='0' and s.user_id = ? ");
        return Db.queryStr(sf.toString(), userId);
    }

    public static String getTraderIdByUserId(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("select s.id from crm_trader s where s.status ='0' and s.user_id = ? ");
        return Db.queryStr(sf.toString(), userId);
    }

    public static String getTraderNameById(String id) {
        StringBuffer sf = new StringBuffer();
        sf.append("select s.name from crm_trader s where s.status ='0' and s.id = ? ");
        return Db.queryStr(sf.toString(), id);
    }

    /**
     * 获取供应商id
     */
    public static String getSupplierId(String userId) {
        return Db.queryStr(" SELECT s.id FROM `crm_supply_supplier` s WHERE s.status ='0' AND s.user_id = ? ", userId);
    }

    /**
     * 获取平台人员信息
     */
    public static Record getByUserId(User user) {
        return getByUserId(user.getUserType(), user.getId());
    }

    /**
     * 获取平台人员信息
     */
    public static Record getByUserId(String userType, String userId) {
        Record rec;
        if (User.DEL_FLAG_DELETE.equals(userType)) {
            rec = Db.findFirst("select * from crm_platform where user_id=?", userId);

        } else if (User.USER_TYPE_WXG.equals(userType)) {
            rec = Db.findFirst("select * from crm_platform_employee where user_id=?", userId);

        } else if (User.USER_TYPE_ADVISOR.equals(userType)) {
            rec = Db.findFirst("select * from crm_trader_employe where user_id=?", userId);
        } else if (User.USER_TYPE_KJ.equals(userType)) {
            rec = Db.findFirst("select *,id as trader_id from crm_trader where user_id=?", userId);
        } else {
            throw new RuntimeException("user type with " + userType + " cannot feedback");
        }
        return rec;
    }


    public static List<Map<String, Object>> returnListMap(List<Record> list) {
        List<Map<String, Object>> listMap = new ArrayList<>();
        if (list.size() > 0) {
            for (Record rd : list) {
                Map<String, Object> map1 = rd.getColumns();
                listMap.add(map1);
            }
        }
        return listMap;
    }


    public static String no() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Random r = new Random();
        return sdf.format(new Date()) + String.valueOf(r.nextLong()).substring(0, 4);
    }

    /**
     * 获取工程师的id
     *
     * @param userId
     */
    public static Record getEmployeId(String userId) {
        String sql = "SELECT * FROM `crm_site_employee` WHERE user_id=? and role='2' and status='0' ";
        return Db.findFirst(sql, userId);
    }

    /**
     * 获取平台元的角色
     */
    public static String getPlatEmployeRole(String userId) {
        StringBuilder sf = new StringBuilder();
        sf.append("SELECT r.type FROM crm_platform_employee_role r ");
        sf.append("LEFT JOIN crm_platform_employee_role_rel q ON q.role_ids=r.id ");
        sf.append("LEFT JOIN crm_platform_employee e ON e.id=q.employee_id ");
        sf.append("WHERE e.user_id=? and e.status <> '1'");
        return Db.queryStr(sf.toString(), userId);

    }

    public static long listMessageDataCount(String userId, String objType) {

        SqlBuilder sb = new SqlBuilder()
                .line("select count(*) from crm_platform_announcement as c")
                .line("LEFT JOIN `crm_announcement_readinfo` AS b ")
                .line("ON c.`id`=b.platform_announcement_id AND b.read_id=? ")
                .line("where c.status='0' AND b.id IS NULL ")
                .line("and c.`obj_type`=?");
        return Db.queryLong(sb.toString(), userId, objType);
    }


    //区分当前用户是供应链、供应商还是代理商的方法
    public static String getCurrentUserType(User user) {
        String userType = user.getUserType();
        if (User.USER_TYPE_YYS.equals(userType) || User.USER_TYPE_PTYG.equals(userType)) {
            return "1";    //供应链
        } else if (User.USER_TYPE_GYS.equals(userType)) {
            return "2";  // 供应商
        } else if (User.USER_TYPE_KJ.equals(userType) || User.USER_TYPE_ADVISOR.equals(userType)) {
            return "3";  // 代理商
        } else {
            throw new RuntimeException("user type with " + userType + " cannot feedback");
        }

    }

    public boolean isSupplyChain() {
        User user = UserUtils.getUser();
        return User.USER_TYPE_YYS.equals(user.getUserType()) || User.USER_TYPE_PTYG.equals(user.getUserType());
    }

    /**
     * 获取当前用户的归属id
     *
     * @return 供应链 返回 a，供应商返回供应商id和名称，代理商返回代理商id和名称
     */
    public static Ascription getAscription() {
        User user = UserUtils.getUser();
        return getAscription(user);
    }

    public static Ascription getAscription(User user) {
        String userType = user.getUserType();
        if (User.USER_TYPE_YYS.equals(userType) || User.USER_TYPE_PTYG.equals(userType)) {
            return new Ascription("a", "供应链");    //供应链
        } else if (User.USER_TYPE_GYS.equals(userType)) {
            Record supplier = Db.findFirst("select * from crm_supply_supplier where user_id=? and status='0'", user.getId());
            return new Ascription(supplier.getStr("id"), supplier.getStr("name"));  // 供应商
        } else if (User.USER_TYPE_KJ.equals(userType)) {
            Record trader = Db.findFirst("select * from crm_trader where user_id=? and status='0'", user.getId());
            return new Ascription(trader.getStr("id"), trader.getStr("name"));  // 代理商
        } else if (User.USER_TYPE_ADVISOR.equals(userType)) {
            Record trader = Db.findFirst("select t.* from crm_trader_employe e inner join crm_trader t on e.trader_id=t.id and e.user_id=? and e.status='0'", user.getId());
            return new Ascription(trader.getStr("id"), trader.getStr("name"));  // 代理商
        } else if ("9".equals(user.getUserType())) {
            Record partner = Db.findFirst("select * from crm_partner where user_id=? and status='0'", user.getId());
            return new Ascription(partner.getStr("id"), partner.getStr("name"));
        } else if ("a".equals(user.getUserType())) {
            Record partner = Db.findFirst("select t.* from crm_partner_staff e inner join crm_partner t on e.partner_id=t.id and e.user_id=? and e.status='0'", user.getId());

            return new Ascription(partner.getStr("id"), partner.getStr("name"));
        } else {
            throw new RuntimeException("user type with " + userType + " cannot feedback");
        }
    }

    //获取人员部门
    public static Record getEmpDepart(User user) {
        if ("4".equals(user.getUserType())) { // 平台人员
            Record r = Db.findFirst("SELECT e.department_id,d.name as depart_name FROM crm_platform_employee e LEFT JOIN `crm_department` d ON d.id=e.department_id WHERE user_id=? ", user.getId());
            return r;
        }
        return null;
    }

    //获取人员部门
    public static String getEmpDepartName(String userId) {
        String departName = Db.queryStr("SELECT d.name FROM crm_platform_employee e LEFT JOIN `crm_department` d ON d.id=e.department_id WHERE user_id=? ", userId);
        return departName == null ? "" : departName;
    }

    public static List<Map<String, Object>> turnRecordListToMapList(List<Record> records) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Record record : records) {
            list.add(record.getColumns());
        }
        return list;
    }

    public static List<Record> findAllTrader() {
        return Db.find("select id,name,user_id from crm_trader where status='0' order by create_time desc");
    }

    //通过电站编码判断电站是否存在
    public static boolean checkEntryByCode(String powerStationCode) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(e.id)")
                .line(" from crm_customer_entry e")
                .line(" where e.power_station_code=? ", powerStationCode);
        Long cnt = Db.queryLong(builder.build(), builder.params());
        if (cnt > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static String getEntryIdByCode(String powerStationCode) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id")
                .line("from crm_customer_entry e")
                .line("where e.power_station_code=? ", powerStationCode);
        return Db.queryStr(builder.build(), builder.params());
    }

    public static String getCompanySetName(String code) {
        return Db.queryStr(" SELECT name from crm_project_company_settings WHERE company_code=? and `status`='0'", code);
    }

    public static Operator getOperatorByTwo(String userId) {
        User user = getUserBy(userId);
        if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){  //代理商人员
            Record r= Db.findFirst("SELECT name,role_name FROM `crm_trader_employe` WHERE user_id=?",user.getId());
            return Operator.of(user.getId(), r.getStr("name"), user.getUserType(),r.getStr("role_name"));
        }
        if (User.USER_TYPE_WXG.equals(user.getUserType())){  //平台人员
            Record emp = Db.findFirst("SELECT name, id FROM `crm_platform_employee` WHERE user_id=?",user.getId());
            String roleName = Db.queryStr(
                    "SELECT GROUP_CONCAT(er.name) as role_name " +
                            " FROM crm_platform_employee_role er, crm_platform_employee_role_rel r" +
                            " WHERE r.`employee_id` = ? AND FIND_IN_SET(er.id, r.role_ids)", emp.getStr("id"));
            return Operator.of(user.getId(), emp.getStr("name"), user.getUserType(), roleName);
        }
        return Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType(),"");
    }


    public static User getUserBy(String userId) {
        UserDao userDao = SpringUtils.getBean(UserDao.class);
        if (StrKit.isBlank(userId)) {
            throw new BusinessException("userId不能为空");
        }
        User user = userDao.get(userId);
        if (user == null) {
            user = userDao.getById(userId);
        }
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (!"0".equals(user.getStatus())) {
            throw new BusinessException("当前账号已禁用或已删除，不可操作！");
        }
        return user;
    }


    /**
     * 校验是否有处在流程中的申请单
     * @param status 电站状态
     * @param entryId 电站id
     * @return
     */
    public static String checkExistApply(String status ,String entryId){
        //物料信息变更
        if(status.equals(CustomerEntryConstants.ENTRY_STATUS_DAZ) || status.equals(CustomerEntryConstants.ENTRY_STATUS_DAZYS) ||
                status.equals(CustomerEntryConstants.ENTRY_STATUS_AZYSTH) || status.equals(CustomerEntryConstants.ENTRY_STATUS_DBW) ||
                status.equals(CustomerEntryConstants.ENTRY_STATUS_YSBH) || status.equals(CustomerEntryConstants.ENTRY_STATUS_AZZS)
        ){
            boolean wlbgFlag = Db.queryLong("SELECT COUNT(1) FROM crm_material_information_change_apply WHERE entry_id = ? AND unique_key = '1'", entryId) > 0;
            if (wlbgFlag){
                return "当前电站存在未完成的物料信息变更申请单！";
            }
        }
        //客户信息变更
        boolean khxxbg=Db.queryLong("SELECT COUNT(1) FROM crm_customer_entry_tenant_change_record WHERE entry_id = ? AND status = '2'", entryId) > 0;
        if (khxxbg){
            return "当前电站存在未完成的客户信息变更申请单！";
        }
        //设计信息变更
        boolean sjbg=Db.queryLong("SELECT COUNT(1) FROM crm_customer_entry_change_design WHERE entry_id = ? AND status = '0' ", entryId) > 0;
        if (sjbg){
            return "当前电站存在未完成的设计信息变更申请单！";
        }
        //勘测信息变更
        boolean kcxxbg=Db.queryLong("SELECT COUNT(1) FROM crm_customer_entry_survey_change_record WHERE entry_id = ? AND status = '0' ", entryId) > 0;
        if (kcxxbg){
            return "当前电站存在未完成的勘测信息变更申请单！";
        }
        //完工信息变更
        boolean wgxxbg=Db.queryLong("SELECT COUNT(1) FROM crm_customer_entry_completion_change_record WHERE entry_id = ? AND status = '0' ", entryId) > 0;
        if (wgxxbg){
            return "当前电站存在未完成的完工信息变更申请单！";
        }

        //并网信息变更
        boolean bwxxbg=Db.queryLong("SELECT COUNT(1) FROM crm_customer_entry_supplement WHERE entry_id = ? AND status = '2' ", entryId) > 0;
        if (bwxxbg){
            return "当前电站存在未完成的并网信息变更申请单！";
        }
        return null;
    }

    public static boolean containsCommonString(List<List<String>> lists) {
        boolean found = false;
        for (List<String> list1 : lists) {
            for (String str1 : list1) {
                for (List<String> list2 : lists) {
                    if (list2 != list1 ) {
                        if (list2.contains(str1)){
                            found = true;
                        }else {
                            found = false;
                            break;
                        }
                    }
                }
                if (found){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取流程标题名称
     *
     * @return
     */
    public static String getStationName(CustomerEntry entry){
        String stationName = entry.getProvince()+entry.getArea()+entry.getTenantName();
        IsInteger str = new IsInteger();
        if(str.isInteger(entry.getStatus())&& StringUtil.equalsAny(entry.getStatus(),"0", "1", "2", "3","4") ){
            stationName = stationName +
                    (new BigDecimal(entry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }else{
            stationName= stationName +
                    (entry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }
        stationName = stationName + "KW光伏电站";
        return stationName;
    }

}
