package com.sifang.modules.setting.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.entity.CrmEntryCashFlow;
import com.sifang.modules.customer.utils.MonitorTokenUtils;
import com.sifang.modules.setting.dao.CrmPlatformEmployeeRoleDao;
import com.sifang.modules.setting.dao.MemberDao;
import com.sifang.modules.setting.dao.MemberRoleDao;
import com.sifang.modules.setting.entity.CrmPlatformEmployeeRole;
import com.sifang.modules.setting.req.GrantTreeVO;
import com.sifang.modules.setting.req.GrantVO;
import com.sifang.modules.setting.req.TreeNode;
import com.sifang.modules.site.siteInfo.service.SiteEmployeeService;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.dao.SupplyOrderAuditDao;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.ZtreeNode;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

@Service
public class MemberService {

    @Autowired
    MemberDao memberDao;

    @Autowired
    MemberRoleDao memberRoleDao;
    @Autowired
    SfCacheService cacheService;
    @Autowired
    SiteEmployeeService siteEmployeeService;
    @Autowired
    SupplyOrderAuditDao supplyOrderAuditDao;


    @Autowired
    ProjectCompanyDao projectCompanyDao;

    public void test() {
        memberDao.saySth();
    }

    public void getMembers(Map<String, String> params, LayuiPage page) {
        List<Record> memberRds = memberDao.getMembers(params, page);
        List<Record> roleRds = memberDao.getMemberRoles();
        Map<String, String> roleMap = memberDao.transferRoleToMap(roleRds);
        for (Record rd : memberRds) {
            String roleIds = rd.getStr("role_ids");
            if (StrKit.notBlank(roleIds)) {
                String[] roleArr = roleIds.split(",");
                StringBuilder roleSb = new StringBuilder("");
                for (String roleId : roleArr) {
                    if (roleMap.containsKey(roleId)) {
                        roleSb.append(",").append(roleMap.get(roleId));
                    }
                }
                if (StrKit.notBlank(roleSb.toString())) {
                    rd.set("roles", roleSb.toString().substring(1));
                }
            }
        }
        page.setData(memberRds);
        page.setCount(memberDao.getMemberCount(params));
    }

    public List<Record> getMemberRoles() {
        return memberDao.getMemberRoles();
    }

    public String addMemberRole(String name) {
        boolean bo = memberDao.addMemberRole(name);
        return bo ? "ok" : "err";
    }

    public String saveMemberRoleMenus(String roleId, String roleName, String permission,String permissionsyw) {
        boolean bo = memberDao.saveMemberRoleMenus(roleId, roleName, permission);
      /*  if(StringUtil.isNotBlank(permissionsyw)){
            //获取token
            String token  = cacheService.get("monitorToken");
            if(StringUtil.isBlank(token)){
                token  = MonitorTokenUtils.findOauthToken();
                cacheService.setex("monitorToken",500,token);
            }
            GrantVO vo= new GrantVO();
            List<String> roleIds = Lists.newArrayList();
            roleIds.add(roleId);
            vo.setRoleIds(roleIds);
            List<String> menuIds = Lists.newArrayList();
            for(String meId :permissionsyw.split(",")){
                menuIds.add(meId);
            }
            vo.setMenuIds(menuIds);

            JSONObject obj = MonitorTokenUtils.clientPostYXMap(new Gson().toJson(vo),"blade-user/role/grant",token);

        }*/

        return bo ? "ok" : "err";
    }

    /**
     * 服务商保存修改的角色权限 ***
     */
    public String saveSiteMemberRoleMenus(String siteId, Integer role, String permission) {
        boolean bo = memberDao.saveSiteMemberRoleMenus(siteId, role, permission);
        return bo ? "ok" : "err";
    }

    public String saveMember(Map<String, String> params) {
        String id = params.get("id");
        String msg = "ok";
        String loginName = params.get("loginName").trim();
        if (StringUtil.isBlank(loginName)) {
            return "登录账号不能为空";
        }
        params.put("loginName", loginName);
        if (StrKit.isBlank(id)) {
            msg = memberDao.addMember(params);
        } else {
            msg = memberDao.updateMember(params);
        }
        return msg;
    }

    public List<ZtreeNode> getMenus(String roleId) {
        User user = UserUtils.getUser();
        List<Record> rds = new ArrayList<>();
        if (StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_TRADER, UserConstants.TYPE_JXS_EMP)) {
            if ("1".equals(user.getTraderType())) {
                rds = memberRoleDao.getMenusByUserRole("4");
            } else if ("2".equals(user.getTraderType())) {
                rds = memberRoleDao.getMenusByUserRole("10");
            }
        } else {
            rds = memberRoleDao.getMenusByUserRole("1");
        }
        List<Record> selectedMenus = memberRoleDao.getMenusByMemberRoleId(roleId);  //获取角色所对应的权限
        Map<String, String> selectedMap = memberRoleDao.getMemberRoleMap(selectedMenus);
        List<ZtreeNode> nodes = Lists.newArrayList();
        for (Record rd : rds) {
            ZtreeNode zn = new ZtreeNode(rd);
            /*   zn.setName(zn.getName() + "_" + zn.getId());*/
            zn.setName(zn.getName());
            if (selectedMap.containsKey(zn.getId())) {
                zn.setChecked(true);
            }
            nodes.add(zn);
        }
        return nodes;
    }

    public List<ZtreeNode> getMenusYw(String roleId) {
        User user = UserUtils.getUser();
        List<TreeNode> rds = new ArrayList<>();
        List<ZtreeNode> nodes = Lists.newArrayList();
       /* if (StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_PLAT_EMP, UserConstants.TYPE_ADMIN)) {
            //获取token
             String token  = cacheService.get("monitorToken");
            if(StringUtil.isBlank(token)){
                token  = MonitorTokenUtils.findOauthToken();
                cacheService.setex("monitorToken",500,token);
            }

            Map<String,Object> map = Maps.newHashMap();
            map.put("roleIds",roleId);
            JSONObject roles =  MonitorTokenUtils.clientGetYX(map,"blade-system/menu/roleTreeKeysHy",token);
            if("200".equals(roles.getString("code"))) {
               // JSONObject data = roles.getJSONObject("data");
                Gson gson = new Gson();
                GrantTreeVO cashList=gson.fromJson(roles.getString("data"),new com.google.common.reflect.TypeToken<GrantTreeVO>(){}.getType());
                rds = cashList.getMenu();
                List<String> selectedMenus = cashList.getHydataScope();  //获取角色所对应的权限
                for (TreeNode rd : rds) {
                    ZtreeNode zn = new ZtreeNode();
                    zn.setName(rd.getTitle());
                    zn.setPid(rd.getParentId().toString());
                    zn.setId(rd.getId().toString());
                    if (selectedMenus.contains(zn.getId())) {
                        zn.setChecked(true);
                    }
                    nodes.add(zn);
                }
                ZtreeNode zn = new ZtreeNode();
                zn.setName("监控运维系统");
                zn.setPid("a");
                zn.setId("0");
                zn.setChecked(true);
                nodes.add(zn);
            }
        }*/
        return nodes;
    }

    /***
     *获取服务商端所有菜单 ***
     */
    public List<ZtreeNode> getSiteMenus(String siteId, Integer role) {
        List<Record> rds = memberRoleDao.getMenusByUserRole("3");
        Record record = memberRoleDao.getSitMemberRoleMenus(siteId, role);
        Map<String, String> selectedMap = new TreeMap<>();
        if (record != null) {
            String permission = record.getStr("permission");
            if (StrKit.notBlank(permission)) {
                String[] perArr = permission.split(",");
                for (String per : perArr) {
                    if (!selectedMap.containsKey(per)) {
                        selectedMap.put(per, "1");
                    }
                }
            }
        }
        List<ZtreeNode> nodes = Lists.newArrayList();
        for (Record rd : rds) {
            ZtreeNode zn = new ZtreeNode(rd);
            zn.setName(zn.getName() + "_" + zn.getId());
            if (selectedMap.containsKey(zn.getId())) {
                zn.setChecked(true);
            }
            nodes.add(zn);
        }
        return nodes;
    }

    public String getMemberPermissionsByUserId(String userId) {
        List<Record> roles = memberRoleDao.getMemberRoleMenus(userId);
        Map<String, String> map = Maps.newHashMap();
        StringBuilder sb = new StringBuilder("-1");
        for (Record rd : roles) {
            String permission = rd.getStr("permission");
            if (StrKit.notBlank(permission)) {
                String[] perArr = permission.split(",");
                for (String per : perArr) {
                    if (!map.containsKey(per)) {
                        sb.append(",").append(per);
                    }
                }
            }
        }
        return sb.toString();
    }

    public String delMember(Map<String, String> params) {
        String id = params.get("id");
        boolean bo = memberDao.delMember(id);
        return bo ? "ok" : "err";
    }

    public Record getMemberById(String id) {
        Record rd = new Record();
        if (StrKit.isBlank(id)) {
            return rd;
        } else {
            rd = memberDao.getMembersById(id);
            return rd;
        }
    }

    public String delRole(String id) {
        boolean canDel = true;
        try {
            if (canDel) {
                Db.update("update crm_platform_employee_role set status = '1' where id = ? ", id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "err";
        }
        return "ok";
    }

    public String beforeSave(Map<String, String> params) {
        String id = params.get("id");
        String ret = "0";   //正常
        String loginName = params.get("loginName").trim();
        if (StringUtil.isBlank(loginName)) {
            return "2";
        }
        Record rd = memberDao.getExistsLoginName(id, loginName);
        if (rd != null && StrKit.notBlank(rd.getStr("id"))) {
            ret = "1";
        }
        return ret;
    }

    //获取平台角色列表
    public List<Record> getRoleList(LayuiPage page) {
        User user = UserUtils.getUser();
        StringBuffer sf = new StringBuffer();
        if (StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_TRADER, UserConstants.TYPE_JXS_EMP)) {  // 代理商角色
            String traderId = user.getTraderId();
            sf.append(" SELECT r.*,(SELECT COUNT(id) FROM crm_trader_employe e WHERE e.role_id=r.id AND e.status='0' )AS number    ");
            sf.append(" FROM `crm_platform_employee_role` r WHERE r.`status`='0'  and r.trader_id= '" + traderId + "'");
            sf.append(" ORDER BY sort ASC ");
        } else {
            sf.append(" SELECT r.*,(");
            sf.append(" SELECT COUNT(1) FROM `crm_platform_employee_role_rel` rel LEFT JOIN `crm_platform_employee` e ON rel.`employee_id`=e.id WHERE rel.`role_ids` LIKE CONCAT('%',r.id,'%') AND e.`status` ='0'");
            sf.append(" )AS number");
            sf.append("  FROM `crm_platform_employee_role` r WHERE r.`status`='0' and r.trader_id='1' ORDER BY sort ASC");
        }
        sf.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        return Db.find(sf.toString());
    }

    public long getCount() {
        User user = UserUtils.getUser();
        StringBuffer sf = new StringBuffer();
        String traderId = "1";
        if (StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_TRADER, UserConstants.TYPE_JXS_EMP)) {  // 代理商角色
            traderId = user.getTraderId();
        }
        sf.append(" SELECT count(r.id) from  `crm_platform_employee_role` r WHERE r.`status`='0' and r.trader_id='" + traderId + "' ");

        return Db.queryLong(sf.toString());
    }

    @Autowired
    private CrmPlatformEmployeeRoleDao crmPlatformEmployeeRoleDao;


    //平台修改角色数据权限
    public String saveEditRoleRights(String id, String province, String city, String project, String traderIds) {
        try {
            StringBuilder sb = new StringBuilder("");
            sb.append(" update crm_platform_employee a ");
            sb.append(" set a.provices = ?, a.city = ?,a.project_number=?,trader_id=? ");
            sb.append(" where  a.id = ? ");
            Db.update(sb.toString(), province, city, project, traderIds, id);
            cacheService.del("findEmployeeByUserId");
            return "200";
        } catch (Exception e) {
            return "202";
        }

    }


    //添加平台角色
    @Transactional(rollbackFor = Exception.class)
    public String addPlateformRole(String jsonData) {
        List listData = new Gson().fromJson(jsonData, List.class);
        List<CrmPlatformEmployeeRole> list = Lists.newArrayList();
        if (listData.size() == 0) {
            return "402";
        }
        User user = UserUtils.getUser();
        String traderId = user.getTraderId();
        if (StringUtil.isBlank(traderId)) {
            traderId = "1";
        }
        List<Map<String,String>> lists = Lists.newArrayList();
        for (int i = 0; i < listData.size(); i++) {
            Map<String, String> map1 = (Map<String, String>) listData.get(i);
            String name = map1.get("name");
            // String sort=map1.get("sort");
            Long count = getCheck(name, null, traderId);
            if (count > 0) {
                return "205"; //角色名称已存在
            }
            CrmPlatformEmployeeRole crmPlatformEmployeeRole = new CrmPlatformEmployeeRole();
            crmPlatformEmployeeRole.setName(name);
            crmPlatformEmployeeRole.setPermission("");
            //  crmPlatformEmployeeRole.setSort(99);
            crmPlatformEmployeeRole.setStatus("0");
            crmPlatformEmployeeRole.setType("3");
            crmPlatformEmployeeRole.setId(IdGen.uuid());
            crmPlatformEmployeeRole.setTraderId(traderId);
            list.add(crmPlatformEmployeeRole);
            map1.put("roleName",name);
            map1.put("roleAlias",name);
            map1.put("tenantId","000000");
            map1.put("householdRoleId", crmPlatformEmployeeRole.getId());
            lists.add(map1);
        }
        //获取token
    /*    String token  = cacheService.get("monitorToken");
        if(StringUtil.isBlank(token)){
            token  = MonitorTokenUtils.findOauthToken();
            cacheService.setex("monitorToken",500,token);
        }*/
        crmPlatformEmployeeRoleDao.save(list);
       // JSONObject obj = MonitorTokenUtils.clientPostYXMap(new Gson().toJson(lists),"blade-user/role/batchSubmit",token);
       // return obj.getString("code");
        return "200";
    }

    //平台修改角色
    public String saveEditPlatformRole(String roleId, String name, String sort) {
        User user = UserUtils.getUser();
        String traderId = user.getTraderId();
        if (StringUtil.isBlank(traderId)) {
            traderId = "1";
        }
        //首先验证名字
        Long count = getCheck(name, roleId, traderId);
        if (count > 0) {
            return "205"; //角色名称已存在
        }
        Map<String, String> map1 = Maps.newHashMap();
        try {
            CrmPlatformEmployeeRole crmPlatformEmployeeRole = crmPlatformEmployeeRoleDao.get(roleId);
            // crmPlatformEmployeeRole.setSort(Integer.valueOf(sort));
            crmPlatformEmployeeRole.setName(name);
            map1.put("roleName",name);
            map1.put("householdRoleId", crmPlatformEmployeeRole.getId());
            crmPlatformEmployeeRoleDao.save(crmPlatformEmployeeRole);
            //获取token
         /*   String token  = cacheService.get("monitorToken");
            if(StringUtil.isNotBlank(token)){
                token  = MonitorTokenUtils.findOauthToken();
                cacheService.setex("monitorToken",500,token);
            }*/
           // JSONObject obj = MonitorTokenUtils.clientPostYXMap(new Gson().toJson(map1),"blade-user/role/updateRole",token);
            return "200";
        } catch (Exception e) {
            return "202";
        }

    }

    //验证改角色是否存在
    public long getCheck(String name, String id, String traderId) {
        StringBuffer sb = new StringBuffer();
        Long count = null;
        sb.append(" SELECT COUNT(id) FROM `crm_platform_employee_role` WHERE NAME=? AND STATUS='0' and  trader_id= ? ");
        if (StringUtil.isNotBlank(id)) {
            sb.append(" AND id !=?");
            count = Db.queryLong(sb.toString(), name, traderId, id);
        } else {
            count = Db.queryLong(sb.toString(), name, traderId);
        }
        return count;
    }

    /**
     * 获取项目
     */
    public List<Record> getProjectLists() {

        String sql = "SELECT * FROM crm_project_setting WHERE status='0'";
        String pojects = cacheService.get("projectList");
        List<Record> list;
        pojects = null;
        if (StringUtil.isNotBlank(pojects)) {
            list = new Gson().fromJson(pojects, new TypeToken<List<Record>>() {
            }.getType());
        } else {
            List<Record> li = Db.find(sql);
            list = li;
            cacheService.set("projectList", new Gson().toJson(list));
        }
        return list;
    }


    public List<Record> getProjectListsByTraderId(String traderId) {
        SqlBuilder sql = new SqlBuilder()
                .line("SELECT * FROM crm_trader_pcd  where trader_id = ?", traderId);
        List<Record> tpcdList = Db.find(sql.build(), sql.params());
        SqlBuilder projectSql = new SqlBuilder()
                .line("SELECT *  FROM crm_project_setting ps WHERE ps.status='0' ");
        int i = 0;
        if (tpcdList.size() > 0) {
            projectSql.line(" and  ps.id in ( SELECT project_id FROM crm_project_pcd pp WHERE (");
            for (Record record : tpcdList) {
                if (i++ != 0) {
                    projectSql.line(" OR");
                }
                projectSql.line(" (pp.province = ? AND (pp.city= '' OR pp.city IS NULL)  AND (pp.area = '' OR pp.area IS NULL)) ", record.getStr("province"));
                projectSql.line(" OR (pp.province = ?", record.getStr("province"));
                if (record.getStr("city") != null && !Objects.equals(record.getStr("city"), "")) {
                    projectSql.line(" and pp.city = ?", record.getStr("city"));
                    if (record.getStr("area") != null && !Objects.equals(record.getStr("area"), "")) {
                        projectSql.line(" and pp.area = ?)", record.getStr("area"));
                    } else {
                        projectSql.line(" )");
                    }
                    projectSql.line(" OR (pp.province = ? AND pp.city = ? AND (pp.area = '' OR pp.area IS NULL)) ", record.getStr("province"), record.getStr("city"));
                } else {
                    projectSql.line(" )");
                }
                if (record.getStr("area") != null && !Objects.equals(record.getStr("area"), "")) {
                    projectSql.line(" OR (pp.province = ? AND pp.city = ? AND pp.area = ? )", record.getStr("province"), record.getStr("city"), record.getStr("area"));
                }
            }
            projectSql.line(")) GROUP BY ps.id");
        }
        return Db.find(projectSql.build(), projectSql.params());
    }


    public List<Record> getProjectAndLineLists() {

        SqlBuilder sql = new SqlBuilder()
                .line("SELECT s.*,l.attribute,l.name as productLineName FROM crm_project_setting s ")
                .line("left join crm_product_line_set l on l.id=s.product_line_id ")
                .line(" WHERE status='0' ");

        List<Record> list = Db.find(sql.build(), sql.params());
        return list;
    }

    public List<Record> getProjectByTraderLists(String traderId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,pc.name AS companyName,pl.name AS lineName,pl.attribute");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN `crm_trader_project` t ON t.project_id=p.id ");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line("WHERE p.status='0' AND t.trader_id=?", traderId);
        builder.line(" GROUP BY p.id");
        String pojects = "";
        List<Record> list;
        if (StringUtil.isNotBlank(pojects)) {
            list = new Gson().fromJson(pojects, new TypeToken<List<Record>>() {
            }.getType());
        } else {
            List<Record> li = Db.find(builder.build(), builder.params());
            list = li;
            cacheService.set(traderId + "projectList", new Gson().toJson(list));
        }
        return list;
    }

    public List<Record> getProjectByTraderListAndFilingType(String traderId, String filing_type) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,pc.name AS companyName,pl.name AS lineName,pl.attribute");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN `crm_trader_project` t ON t.project_id=p.id ");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line("WHERE p.status='0' AND t.trader_id=?", traderId);
//        builder.line(" and p.filing_type = ?", filing_type);
        if (filing_type.equals("2")) {
            builder.line(" and p.filing_type = ?", filing_type);
        }
        builder.line(" GROUP BY p.id");
        String pojects = "";
        List<Record> list;
        if (StringUtil.isNotBlank(pojects)) {
            list = new Gson().fromJson(pojects, new TypeToken<List<Record>>() {
            }.getType());
        } else {
            List<Record> li = Db.find(builder.build(), builder.params());
            list = li;
            cacheService.set(traderId + "projectList", new Gson().toJson(list));
        }
        return list;
    }


    public List<Record> getProjectByTraderLists2(String traderId, String filingType, String management) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,pc.name AS companyName,pl.name AS lineName,pl.attribute,p.project_company_id");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN `crm_trader_project` t ON t.project_id=p.id ");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line("WHERE p.status='0' AND t.trader_id=?  and p.management =  ?", traderId, management);
        builder.line(" and p.filing_type = ?", filingType);
        String pojects = "";
        List<Record> list;
        if (StringUtil.isNotBlank(pojects)) {
            list = new Gson().fromJson(pojects, new TypeToken<List<Record>>() {
            }.getType());
        } else {
            List<Record> li = Db.find(builder.build(), builder.params());
            list = li;
            cacheService.set(traderId + "projectList", new Gson().toJson(list));
        }
        return list;
    }

    /**
     * 根据省市区 备案类型 资方 获取产品信息
     */
    public List<Record> getProjectByTraderLists3(String traderId, String filingType, String management,String province,String city,String area) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,pc.name AS companyName,pl.name AS lineName,pl.attribute,p.project_company_id,p.assembly_specs");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN `crm_trader_project` t ON t.project_id=p.id ");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        builder.line(" left join crm_project_pcd d on d.project_id  = p.id ");
        builder.line("WHERE p.status='0' AND t.trader_id=?  and p.management =  ?", traderId, management);
        builder.line(" and d.status = '0' and  p.filing_type = ?", filingType);
        builder.line(" and ( (d.province = ? and d.city is null )" ,province);
        builder.line(" or (d.province = ? and d.city = ? and d.area is null)",province ,city);
        builder.line(" or (d.province = ? and d.city = ? and d.area = ? ))" ,province ,city,area);
        String pojects = "";
        List<Record> list;
        if (StringUtil.isNotBlank(pojects)) {
            list = new Gson().fromJson(pojects, new TypeToken<List<Record>>() {
            }.getType());
        } else {
            List<Record> li = Db.find(builder.build(), builder.params());
            list = li;
            cacheService.set(traderId + "projectList", new Gson().toJson(list));
        }
        return list;
    }

    public List<Record> getBTProject(String traderId, String management, String tenantType,
                                     String filType, String filingType, String projectId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,pc.name AS companyName,pl.name AS lineName,pl.attribute,p.management,p.assembly_specs");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN `crm_trader_project` t ON t.project_id=p.id ");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        if (StringUtil.isNotBlank(projectId)) {
            builder.line(" left join crm_partner as c on p.management = c.id  ");
        }
        builder.line("WHERE p.status='0'  AND t.trader_id=?", traderId);
        if (StringUtil.isNotBlank(filType)) {
            if ("2".equals(filType)) {
                builder.line("AND p.filing_type = ?", filType);
            }
        }
        if (StringUtil.isNotBlank(filingType)) {
            builder.line("AND p.filing_type = ?", filingType);
        }
        if (StringUtil.isNotBlank(management)) {
            builder.line("AND p.management = ?", management);
        }
        if (StringUtil.isNotBlank(projectId)) {
            builder.line("  and c.id=? ", projectId);
        }
        if (StringUtil.isNotBlank(tenantType)
                && Objects.equals(CustomerEntryConstants.TENANT_TYPE_COMPANY, tenantType)) {
            builder.line("AND p.filing_type = '2'");
        }

        builder.line(" order by p.name asc");
        return Db.find(builder.build(), builder.params());
    }

    public List<Record> getProjectWithOutBT(User user, String traderId, String management, String filType, String filingType, String projectId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT p.id,p.code,p.name,p.pay_cycle,p.filing_type,pc.name AS companyName,pl.name AS lineName,pl.attribute,p.management,p.assembly_specs");
        builder.line("FROM crm_project_setting p");
        builder.line("LEFT JOIN `crm_trader_project` t ON t.project_id=p.id ");
        builder.line("LEFT JOIN crm_project_company_settings pc ON pc.id = p.project_company_id");
        builder.line("LEFT JOIN crm_product_line_set pl ON pl.id = p.product_line_id");
        if (StringUtil.isNotBlank(projectId)) {
            builder.line(" left join crm_partner as c on p.management = c.id  ");
        }
        builder.line("WHERE p.status='0' AND pl.attribute <> '1' ");
        if (StringUtil.isNotBlank(traderId)) {
            builder.line("AND t.trader_id=?", traderId);
        } else {
            List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(user.getId());
            List<String> traderList = supplyOrderAuditDao.appendColumns(employeeRole, "trader_id");
            if (!traderList.isEmpty()) {
                builder.inst("AND t.trader_id in ", traderList);
            }
        }
        if (StringUtil.isNotBlank(filType)) {
            if ("2".equals(filType)) {
                builder.line("AND p.filing_type = ?", filType);
            }
        }
        if (StringUtil.isNotBlank(filingType)) {
            builder.line("AND p.filing_type = ?", filingType);
        }

        if (StringUtil.isNotBlank(management)) {
            builder.line(" AND p.management = ?", management);
        }
        if (StringUtil.isNotBlank(projectId)) {
            builder.line("  and c.id=? ", projectId);
        }
        builder.line(" order by p.assembly_specs asc ");
        return Db.find(builder.build(), builder.params());
    }


    public Record getPlatFormEmployeById(String id) {

        return Db.findFirst("SELECT * FROM `crm_platform_employee` WHERE id=? ", id);
    }

    public List<Record> getProjectListByIds(String ids) {

        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT * FROM crm_project_setting WHERE status='0'");
        if (StrKit.notBlank(ids)) {
            builder.inst("and id in", Arrays.asList(ids.split(",")));
        }
        return Db.find(builder.toString());
    }

}
