package com.sifang.modules.sunshine.SystemSetting.service;

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.account.dao.TraderAccountDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.constant.TraderConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.flowpath.entity.BondApply;
import com.sifang.modules.flowpath.entity.TraderApply;
import com.sifang.modules.flowpath.service.BondApplyService;
import com.sifang.modules.kingdee.service.KingDeeTraderService;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.sunshine.SystemSetting.dao.*;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.form.AddSecondTraderVo;
import com.sifang.modules.sunshine.SystemSetting.form.AddTrader;
import com.sifang.modules.sunshine.SystemSetting.utils.*;
import com.sifang.modules.sunshine.handler.TraderExcelImportHandler;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hongzq
 */
@Service
public class TraderService extends BaseService {

    @Autowired
    private TraderDao traderDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SiteInformationDao siteInformationDao;

/*    @Autowired
    private KingDeeTraderService kingDeeTraderService;*/

    @Autowired
    private SfCacheService cacheService;
    @Autowired
    private SiteInformationService siteInformationService;

    @Autowired
    private TraderWarehouseRelDao traderWarehouseRelDao;

    @Autowired
    private TraderEmployeDao traderEmployeDao;

    @Autowired
    private TraderAccountDao accountDao;

    @Autowired
    private CrmSupplyWarehouseSettingService warehouseSettingService;

    @Autowired
    private BondApplyService bondApplyService;

    public CrmTrader getById(String traderId) {
        return traderDao.get(traderId);
    }

    public CrmTrader getTraderBuserId(String userId){
        return traderDao.getTraderBuserId(userId);
    }

    public void listTrader(LayuiPage<Record> page, Map<String, String> map) {
        User user=UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){  //平台员工
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }
        List<Record> recordList = listTraderRecords(page, map);
        Long count = countTraderRecords(map);
        page.setData(recordList);
        page.setCount(count);
    }

    public void listTrader2(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> recordList = listTraderRecords(page, map);
        Long count = countTraderRecords(map);
        page.setData(recordList);
        page.setCount(count);
    }

    public List<Record> getTraderList(Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("  select t.id as traderId , t.name ")
                .line(" from crm_trader t  LEFT JOIN sys_user u on t.user_id = u.id ");
        if (StringUtil.isNotBlank(map.get("partner"))) {
            builder.line(" LEFT JOIN crm_trader_partner p on p.trader_id = t.id ");
        }
        builder.line("where 1=1 and type = '1' ");
        appendCondition(builder, map);
        return Db.find(builder.build(), builder.params());
    }


    public List<Record> listTraderRecords(LayuiPage<Record> page, Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select t.*,CONCAT_WS('',t.province,t.city,t.area,t.address) AS traderAddressfrom,  u.login_name,u.status as userStatus ")
                .line(",CONCAT_WS('',t.take_delivery_province,t.take_delivery_city,t.take_delivery_area,t.take_delivery_address) AS takeAddress, t.qq_company_code as qqCode")
                .line("from crm_trader t")
                .line("LEFT JOIN sys_user u on t.user_id = u.id");
          builder.line("where 1=1");
        appendCondition(builder, map);
        builder.line("order by t.create_time desc");
        if (page != null) {
            builder.limit(page.getPage(), page.getLimit());
            return Db.find(builder.build(), builder.params());
        }else{
            List<Record> list;
            String listTraderRecords = cacheService.get("listTraderRecords");
            listTraderRecords="";
            if(StringUtil.isNotBlank(listTraderRecords)){
                list =  new Gson().fromJson(listTraderRecords, new TypeToken< List<Record>>() {
                }.getType());
            }else{
                list=  Db.find(builder.build(), builder.params());
                cacheService.set("listTraderRecords",new Gson().toJson(list));
            }

            return list;
        }
    }

    public Long countTraderRecords(Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1) ")
                .line("from crm_trader t")
                .line("LEFT JOIN sys_user u on t.user_id = u.id")
                .line("where 1=1");
        appendCondition(builder, map);
        return Db.queryLong(builder.build(), builder.params());
    }


    public List<Record> findTraderRecordsList(Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select t.*,CONCAT_WS('',t.province,t.city,t.area,t.address) AS traderAddressfrom,  u.login_name ")
                .line(",CONCAT_WS('',t.take_delivery_province,t.take_delivery_city,t.take_delivery_area,t.take_delivery_address) AS takeAddress")
                .line("from crm_trader t")
                .line("LEFT JOIN sys_user u on t.user_id = u.id")
                .line("where 1=1");
        appendCondition(builder, map);
        builder.line("order by t.create_time desc");
        return Db.find(builder.build(), builder.params());
    }
    private void appendCondition(SqlBuilder builder, Map<String, String> map) {
        User user = UserUtils.getUser();
        if (Objects.equals("1", user.getTraderType())) {
            builder.line("and t.parent_id = ?", user.getTraderId());
        }
        if (StringUtil.checkParamsValid(map.get("type"))) {
            builder.line("and t.type = ?", map.get("type").trim());
            if(!StringUtil.checkParamsValid(map.get("ifNotCheckStatus"))){
                if (Objects.equals("1", map.get("type").trim())) {
                    builder.line("and t.status='0'");
                }
            }
            if(Objects.equals("1", map.get("type").trim())){
                builder.line("AND u.status <>1");
            }
        } else {
            builder.line("and t.status='0'");
        }
        if (StringUtil.isNotBlank(map.get("partner"))) {
            builder.line("and p.partner_id = ?", map.get("partner"));
        }
        if (StringUtil.checkParamsValid(map.get("status"))) {
            builder.line("and t.status = ?", map.get("status").trim());
        }
        if (StringUtil.checkParamsValid(map.get("name"))) {
            builder.line("and t.name like concat('%', ?, '%')", map.get("name").trim());
        }
        if (StringUtil.checkParamsValid(map.get("contacts"))) {
            builder.line("and t.contacts like concat('%', ?, '%')", map.get("contacts").trim());
        }
        if (StringUtil.checkParamsValid(map.get("mobile"))) {
            builder.line("and t.mobile like concat('%', ?, '%')", map.get("mobile").trim());
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMin"))) {
            builder.line("and t.create_time >= ?", map.get("createTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("createTimeMax"))) {
            builder.line("and t.create_time <= ?", map.get("createTimeMax"));
        }
        if (StringUtil.checkParamsValid(map.get("province"))) {
            builder.line("and concat(t.province,t.city,t.area,t.address) like concat('%', ?, '%')", map.get("province").trim());
        }
        if (StringUtil.isNotBlank(map.get("ids"))) {
            builder.inst("and t.id not in ", map.get("ids").split(","));
        }
        if (StringUtil.isNotBlank(map.get("traderIds"))) {
            builder.inst("and t.id  in ", map.get("traderIds").split(","));
        }
           //检索一级代理商列表
            if (StringUtil.checkParamsValid(map.get("type")) && map.get("type").equals("1")) {
                if(StringUtil.isNotBlank(map.get("provinceE"))){
                    builder.inst("  and (  t.province in ",map.get("provinceE").split(","));
                    builder.line(" or t.is_national_trader = '1' ) ");
                }
                if(StringUtil.isNotBlank(map.get("cityE"))){
                    builder.inst("  and ( t.city in  ",map.get("cityE").split(","));
                    builder.line(" or t.is_national_trader = '1' ) ");
                }
                if(StringUtil.isNotBlank(map.get("traderIdsE"))){
                    builder.inst(" and t.id in ",map.get("traderIdsE").split(","));
                }
            }else {
                //检索二级代理商列表
                if(StringUtil.isNotBlank(map.get("traderIdsE"))){
                    builder.inst(" and t.parent_id in ",map.get("traderIdsE").split(","));
                }
                //根据代理商地址 检索一级代理商traderId
                if(StringUtil.isNotBlank(map.get("provinceE"))){
                    builder.inst(" and t.parent_id in (SELECT id from crm_trader where ( province in ",map.get("provinceE").split(","));
                    builder.line(" or is_national_trader = '1' ) ");
                    if(StringUtil.isNotBlank(map.get("cityE"))){
                        builder.inst(" and  ( city in ",map.get("cityE").split(","));
                        builder.line(" or is_national_trader = '1' )");
                    }
                    builder.line(" )");
                }
            }

    }

    @Transactional(rollbackFor = Exception.class)
    public void addOrEditTrader(AddTrader req) {
        CrmTrader trader = getById(req.getId());
        if (trader != null) {
            editTrader(trader, req);
        } else {
            addTrader(req);
        }
        cacheService.del("listTraderRecords");
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteTrader(String ids){
        for (String id : ids.split(",")) {
            CrmTrader trader = getById(id);
            trader.setStatus(UserConstants.USER_STATUS_DELETE);
            if (trader.getUserId() != null) {
                traderDao.save(trader);
                User user = userDao.getById(trader.getUserId());
                user.setStatus(UserConstants.USER_STATUS_DELETE);
                user.setUpdateTime(new Date());
                userDao.save(user);
            }
        }
        cacheService.del("listTraderRecords");
    }
    private CrmTrader createNewTrader(TraderApply req, String userId,CrmTrader trader){

        trader.setUserId(userId);
        trader.setType("1");
        //trader.setStatus(UserConstants.USER_STATUS_NORMAL);
        trader.setCreateBy(req.getCreator());
        trader.setCreator(req.getCreator());

        trader.setName(req.getName());
        trader.setContacts(req.getContacts());
        trader.setProvince(req.getProvince());
        trader.setCity(req.getCity());
        trader.setArea(req.getArea());
        trader.setAddress(req.getAddress());
        trader.setMobile(req.getMobile());
        trader.setActualContacts(req.getActualContacts());
        trader.setTelephone(req.getTelephone());
        trader.setBond(req.getBond());
        trader.setActualIdCode(req.getActualIdCode());
        trader.setBankName(req.getBankName());
        trader.setBankCode(req.getBankCode());
        trader.setTaxNumber(req.getTaxNumber());
        trader.setLicenseImg(req.getLicenseImg());
        trader.setIdFrontImg(req.getIdFrontImg());
        trader.setIdOppositeImg(req.getIdOppositeImg());
        trader.setRemarks(req.getRemarks());
        trader.setTakeDeliveryProvince(req.getTakeDeliveryProvince());
        trader.setTakeDeliveryCity(req.getTakeDeliveryCity());
        trader.setTakeDeliveryArea(req.getTakeDeliveryArea());
        trader.setTakeDeliveryAddress(req.getTakeDeliveryAddress());
        trader.setDepartmentId(req.getDepartmentId());
        trader.setDepartmentName(req.getDepartmentName());
        trader.setQqjyglwtsImg(req.getQqjyglwtsImg());
        trader.setBzjdkpzImg(req.getBzjdkpzImg());
        trader.setSfzzmfyjImg(req.getSfzzmfyjImg());
        trader.setSfzfmfyjImg(req.getSfzfmfyjImg());
        trader.setDlszrsqbImg(req.getDlszrsqbImg());
        trader.setQqProjectCode(req.getQqProjectCode());
        trader.setQqProjectName(req.getQqProjectName());
        trader.setContractSigning("1");
        return trader;
    }

    private User createNewUser(AddTrader req){
        User user = new User();
        user.setCreateBy(UserUtils.getUser().getId());
        user.setStatus(UserConstants.USER_STATUS_NORMAL);
        user.setUserType(UserConstants.TYPE_TRADER);
        user.setCreateType(1);
        user.setMobile(req.getTelephone());
        user.setCreateDate(new Date());
        user.setLoginName(req.getLoginName());
        user.setPassword(RandomUtil.entryptPassword(req.getPassword()));
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addTrader(AddTrader req) {
        if (siteInformationDao.getExistsLoginName(req.getLoginName())) {
            throw new BusinessException("登录账号已存在");
        }
        if (!traderDao.checkNameExists(req.getTraderName(), "")) {
            throw new BusinessException("代理商名称已存在");
        }
        if (!traderDao.checkMobileExists(req.getTelephone(),"")) {
            throw new BusinessException("该手机号已存在");
        }
       // User user = createNewUser(req);
       // userDao.save(user);
       // CrmTrader trader = createNewTrader(req, user.getId());
       // traderDao.save(trader);
    }

    @Transactional(rollbackFor = Exception.class)
    public String addTraderByApply(TraderApply apply){
        String userId;
        CrmTrader trader ;
        boolean csReset = false;
        boolean jdFg=false;
        boolean ifNew=false;
        if(StringUtil.isBlank(apply.getTraderId())){
            ifNew=true;
            User user = new User();
            user.setCreateBy(apply.getCreateBy());
//            user.setStatus(UserConstants.USER_STATUS_DISABLE);//禁用状态(等代理商合同签署后，才能启用)TODO
            user.setStatus(UserConstants.USER_STATUS_NORMAL);
            user.setUserType(UserConstants.TYPE_TRADER);
            user.setCreateType(1);
            user.setMobile(apply.getTelephone());
            user.setCreateDate(new Date());
            user.setLoginName(apply.getLoginName());
            user.setPassword(RandomUtil.entryptPassword(apply.getPassword()));
            userDao.save(user);
            userId= user.getId();
            trader = new CrmTrader();
            trader.setCreateTime(new Date());
            trader.setApplyTime(apply.getCreateTime());
            trader.setContractSigning("0");
           // trader.setStatus(TraderConstants.STATUS_JY); //等代理商合同签署后，才能启用
            trader.setStatus(TraderConstants.STATUS_QY);
        }else {
            trader = traderDao.get(apply.getTraderId());
            userId = trader.getUserId();
            //修改供应商名称 重置合同签署
            if (!Objects.equals(trader.getName(),apply.getName())) {
                trader.setContractSigning("0");
                csReset = true;
                jdFg=true;
            }else if(!Objects.equals(trader.getMobile(), apply.getMobile())){
                jdFg=true;
            }else if(!Objects.equals(trader.getTaxNumber(), apply.getTaxNumber())){
                jdFg=true;
            }else if(!Objects.equals(trader.getBankName(), apply.getBankName())){
                jdFg=true;
            }else if(!Objects.equals(trader.getBankCode(), apply.getBankCode())){
                jdFg=true;
            }else if(!Objects.equals(trader.getTakeDeliveryProvince()+trader.getTakeDeliveryCity()+trader.getTakeDeliveryArea()+trader.getTakeDeliveryAddress(),
                    apply.getTakeDeliveryProvince()+apply.getTakeDeliveryCity()+apply.getTakeDeliveryArea()+apply.getTakeDeliveryAddress())){
                jdFg=true;
            }else if(!Objects.equals(trader.getActualContacts(), apply.getActualContacts())){
                jdFg=true;
            }else if(!Objects.equals(trader.getProvince()+trader.getCity()+trader.getArea()+trader.getAddress(),
                    apply.getProvince()+apply.getCity()+apply.getArea()+apply.getAddress())){
                jdFg=true;
            }

        }
        createNewTrader(apply,userId,trader);
       /* if(StringUtil.isBlank(apply.getTraderId())){
            //推给金蝶
            try {
             KingDeeResponseVo responseVo=kingDeeTraderService.saveTrader(trader);
             String kingDeeId=responseVo.getId();
             String number=responseVo.getNumber();
             trader.setKingDeeId(kingDeeId);
             trader.setKingDeeNumber(number);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(">>>>>>>>>代理商审核通过,推送金额报错 e:{}",e);
                throw new BusinessException("代理商审核通过,推送金额报错!");
            }
        }else if(StringUtil.isNotBlank(trader.getKingDeeId())){
           if(jdFg){
               try {
                   kingDeeTraderService.editTrader(trader);
               } catch (Exception e) {
                   e.printStackTrace();
                   logger.error(">>>>>>>>>代理商修改审核通过,推送金额报错 e:{}",e);
                   throw new BusinessException("代理商审核通过,推送金额报错!");
               }
           }
        }*/
        traderDao.save(trader);
        trader.setParentId(trader.getId());
        //处理旧数据
        Db.update("delete from `crm_trader_agent` where trader_id=? and (sign_flow_id is null or sign_flow_id='')",trader.getId());
        //复制数据到
        Db.update("INSERT INTO `crm_trader_agent` SELECT * FROM `crm_trader_apply_agent` WHERE trader_apply_id=? and (sign_flow_id is null or sign_flow_id = '')",apply.getId());
        Timer timer=new Timer();
        boolean finalCsReset = csReset;
        TimerTask task=new TimerTask(){
            public void run(){
                //需要延迟执行的业务数据
                SqlBuilder builder = new SqlBuilder();
                builder.line("update `crm_trader_agent` set trader_id=? ",trader.getId());
                if (finalCsReset) {
                    //重置代理区域的签约
                    builder.line(",sign_contract=null,contract_url=null,sign_flow_id=null,file_id=null ");
                }
                builder.line("where trader_apply_id=? ",apply.getId());
                if (finalCsReset) {
                    //重置代理区域的签约
                    builder.line(" or trader_id=?",trader.getId());
                }
                Db.update(builder.build(),builder.params());
               /* //同步信息到服务商
                siteInformationService.tongbuSite(trader);*/

            }
        };
        timer.schedule(task,1000);//延迟2秒执行
        cacheService.del("listTraderRecords");

        if(ifNew){
            apply.setTraderId(trader.getId());
            //默认保证金额度
            logger.info(">>>>>>>>>>>>>代理商审批完成后 给一个保证金额度：{}",apply.getBondLimit());
            if(apply.getBondLimit()!=null || apply.getBond()!=null){
                CrmTraderAccount account= accountDao.getAccountByTraderId(trader.getId());
                if(apply.getBond()!=null){
                    account.setBzjAmount(apply.getBond());
                    //生成一条保证金明细
                    bondApplyService.saveBondApply(apply.getBond(),trader.getId());
                }
                if(apply.getBondLimit()!=null){
                    account.setBondAmountLimit(apply.getBondLimit());
                }
                accountDao.save(account);
            }
            //默认一个仓库
            warehouseSettingService.addTraderWarehouseMr(apply);
        }
        return trader.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchAddTrader(List<AddTrader> traders){
        for (AddTrader req : traders) {

            if (siteInformationDao.getExistsLoginName(req.getLoginName())) {
                throw new BusinessException("登录账号已存在");
            }
            if (!traderDao.checkNameExists(req.getTraderName(), "")) {
                throw new BusinessException("代理商名称已存在");
            }
            if (!traderDao.checkMobileExists(req.getTelephone(),"")) {
                throw new BusinessException("该手机号已存在");
            }
            User user = createNewUser(req);
            userDao.save(user);
          //  CrmTrader trader = createNewTrader(req, user.getId());
           // traderDao.save(trader);
        }
        cacheService.del("listTraderRecords");
//        List<User> userList = new ArrayList<>();
//        List<CrmTrader> traderList = new ArrayList<>();
//        for(AddTrader req: traders){
//            User user = createNewUser(req);
//            user.setId(IdGen.uuid());
//            userList.add(user);
//
//            CrmTrader trader = createNewTrader(req, user.getId());
//            traderList.add(trader);
//        }
//        for (User user : userList) {
//            userDao.getSession().save(user);
//        }
//        for (CrmTrader trader : traderList) {
//            traderDao.save(trader);
//        }
    }

    public void editTrader(CrmTrader trader, AddTrader req) {
        User user = userDao.get(trader.getUserId());
        if (siteInformationDao.getExistsLoginNameNew(user.getId(), req.getLoginName())) {
            throw new BusinessException("登录账号已存在");
        }

        if (!traderDao.checkMobileExists(req.getTelephone(),user.getId())) {
            throw new BusinessException("该手机号已存在");
        }
        user.setMobile(req.getTelephone());
        user.setLoginName(req.getLoginName());
        if (!req.getPassword().equals("default") && !user.getPassword().equals(req.getPassword())) {
            user.setPassword(RandomUtil.entryptPassword(req.getPassword()));
        }
        userDao.save(user);
        if (!traderDao.checkNameExists(req.getTraderName(), req.getId())) {
            throw new BusinessException("代理商名称已存在");
        }

        setCommonField(trader, req);
        traderDao.save(trader);
    }

    public void setCommonField(CrmTrader trader, AddTrader req) {
        trader.setName(req.getTraderName());
        trader.setContacts(req.getUserName());
        trader.setTelephone(req.getTelephone());
        trader.setProvince(req.getProvince());
        trader.setCity(req.getCity());
        trader.setArea(req.getArea());
        trader.setAddress(req.getAddress());
        trader.setLicenseImg(req.getImgs());
        trader.setRemarks(req.getRemarks());
    }

    //校验批量调价商品数据
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportTrader(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        TraderExcelImportHandler handler=new TraderExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if(!handler.isCheckFlag()){
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)){
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            }else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importGoods(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        TraderExcelImportHandler handler=new TraderExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(3);
        handler.setParams(params);
        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);
            List<AddTrader> traders = handler.getRetList();
         //   batchAddTrader(traders);
            retMap.put("pass", "y");
            retMap.put("successCount", handler.getSuccessCount());
            retMap.put("errorCount", 0);
            retMap.put("importHints", "y");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }


    public List<Record> findTraderListByProvince(String province){
        return traderDao.findTraderListByProvince(province);
    }
    public List<Record> findTraderListByProvinces(String province){
        return traderDao.findTraderListByProvinces(province);
    }


    public List<Record> getAllTrader(){
        return traderDao.getAllTrader();
    }

    public List<Record> getAllTopTrader(){
        return traderDao.getAllTopTrader();
    }

    public Long getEmpCountByRole(String role,String traderIdss){
        Long count=traderDao.getEmpCountByRole(role,traderIdss);
        return count==null?0:count;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result saveSecondTrader(AddSecondTraderVo vo) {
        // 获取操作人信息
        User user = UserUtils.getUser();
        Date now = new Date();
        if (siteInformationDao.getExistsLoginName(vo.getLoginName())) {
            return Result.fail("登录账号已存在");
        }
        if (!traderDao.checkNameExists(vo.getTraderName(), "")) {
            return Result.fail("代理商名称已存在");
        }
        String traderId = CrmUtils.getCurrentTraderId(user);
        if(StringUtil.isBlank(traderId)) {
            return Result.fail("未查询到代理商信息");
        }
        // 查询父级代理商信息
        CrmTrader parentTrader = traderDao.get(traderId);
        if (parentTrader == null) {
            return Result.fail("未查询到一级代理商信息");
        }

        // 创建user信息
        User addUser = new User();
        addUser.setCreateBy(user.getId());
        if (Objects.equals(vo.getStatus(), UserConstants.USER_STATUS_NORMAL)) {
            addUser.setStatus(vo.getStatus());
        } else {
            addUser.setStatus(UserConstants.USER_STATUS_DISABLE);
        }
        addUser.setUserType(UserConstants.TYPE_TRADER);
        addUser.setCreateType(1);
        addUser.setCreateDate(now);
        addUser.setLoginName(vo.getLoginName());
        addUser.setPassword(RandomUtil.entryptPassword(vo.getPassword()));
        userDao.save(addUser);

        // 创建代理商信息
        CrmTrader trader = new CrmTrader();
        trader.setUserId(addUser.getId());
        trader.setParentId(parentTrader.getId());
        trader.setParentName(parentTrader.getName());
        trader.setType("2");
        trader.setName(vo.getTraderName());
        trader.setStatus(vo.getStatus());
        trader.setCreateBy(user.getId());
        trader.setCreator(parentTrader.getName());
        trader.setCreateTime(now);
        trader.setDepartmentId(user.getDepartmentId());
        trader.setDepartmentName(parentTrader.getName());
        trader.setContractSigning("1");
        traderDao.save(trader);

        // 新增授权仓库
        String[] ids = vo.getWarehouseIds().split(",");
        for (String warehouseId : ids) {
            traderWarehouseRelDao.createOne(trader.getId(), warehouseId);
        }
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result editSecondTrader(AddSecondTraderVo vo) {
        // 获取操作人信息
        User user = UserUtils.getUser();
        if (!traderDao.checkNameExists(vo.getTraderName(), vo.getId())) {
            return Result.fail("代理商名称已存在");
        }

        // 创建代理商信息
        CrmTrader oldTrader = traderDao.get(vo.getId());
        if (!oldTrader.getName().equals(vo.getTraderName())) {
            Db.update(" update crm_customer_entry set create_trader_name = ? where create_trader_id = ? ",vo.getTraderName(),vo.getId());
            Db.update(" update crm_customer_entry set trader_name = ? where distributor_id = ? ",vo.getTraderName(),vo.getId());
        }
        oldTrader.setName(vo.getTraderName());
        oldTrader.setStatus(vo.getStatus());

        // 修改user信息
        User oldUser = userDao.get(oldTrader.getUserId());
        oldUser.setLoginName(vo.getLoginName());
        if (!Objects.equals("defaultHtyPsd", vo.getPassword())) {
            oldUser.setPassword(RandomUtil.entryptPassword(vo.getPassword()));
        }
        if (Objects.equals(vo.getStatus(), UserConstants.USER_STATUS_NORMAL)) {
            oldUser.setStatus(vo.getStatus());
        } else {
            oldUser.setStatus(UserConstants.USER_STATUS_DISABLE);
        }

        // 删除之前授权的仓库
        traderWarehouseRelDao.deleteRelByTrader(oldTrader.getId());

        // 新增授权仓库
        String[] ids = vo.getWarehouseIds().split(",");
        for (String warehouseId : ids) {
            traderWarehouseRelDao.createOne(oldTrader.getId(), warehouseId);
        }
        // 获取代理商所属状态正常员工
        List<String> empList = traderEmployeDao.findSecondTraderEmp(oldTrader.getId());
        if (empList != null && empList.size() > 0) {
            // 启用/禁用 二级代理商下面的员工
            if (Objects.equals(vo.getStatus(), UserConstants.USER_STATUS_NORMAL)) {
                userDao.updateStatusByIds(empList, UserConstants.USER_STATUS_DISABLE, UserConstants.USER_STATUS_NORMAL);
            } else {
                userDao.updateStatusByIds(empList, UserConstants.USER_STATUS_NORMAL, UserConstants.USER_STATUS_DISABLE);
            }
        }
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result changeStatusSecondTrader(String id, String status) {
        CrmTrader trader = traderDao.get(id);
        //二级代理商启用时做判断
        if(status.equals("0")){
            CrmTrader traderFirst = traderDao.get(trader.getParentId());
            if(traderFirst.getStatus().equals("1")){
                return Result.fail("206","一级代理商处于禁用状态，请先启用一级代理商");
            }else{
                changeStatus( id, status);
                return Result.ok();
            }
        }else {
            changeStatus( id, status);
            return Result.ok();
        }
    }
    /**
     * 处理禁用启用公共方法
     */
    public void changeStatus(String id, String status){
        CrmTrader trader = traderDao.get(id);
        // 删除代理商
        trader.setStatus(status);
        // 删除user
        User user = userDao.get(trader.getUserId());
        if (Objects.equals(status, UserConstants.USER_STATUS_NORMAL)) {
            user.setStatus(status);
        } else {
            user.setStatus(UserConstants.USER_STATUS_DISABLE);
        }
        // 获取代理商所属状态正常员工
        List<String> empList = traderEmployeDao.findSecondTraderEmp(id);
        if (empList != null && empList.size() > 0) {
            // 启用/禁用 二级代理商下面的员工
            if (Objects.equals(status, UserConstants.USER_STATUS_NORMAL)) {
                userDao.updateStatusByIds(empList, UserConstants.USER_STATUS_DISABLE, UserConstants.USER_STATUS_NORMAL);
            } else {
                userDao.updateStatusByIds(empList, UserConstants.USER_STATUS_NORMAL, UserConstants.USER_STATUS_DISABLE);
            }
        }
    }
    /**
     *禁用一级代理商
     */
    @Transactional(rollbackFor = Exception.class)
    public Result changeStatusFirstTrader(String id, String status) {
        // 一、删除代理商
        CrmTrader trader = traderDao.get(id);
        trader.setStatus(status);
        //如果是启用就仅启用一级代理商，不管二级，禁用的情况全禁用
        if(status.equals("1")) {
            /*if("1".equals(trader.getType())){  //一级代理商 启用前，需要判断代理商合同是否已经签署，如果没有签署那么不能启用
                 Long count=Db.queryLong("SELECT COUNT(id) FROM `crm_trader_contract` c WHERE c.trader_id=? AND c.status='4' ",trader.getId());
                 if(count==0){
                     throw new BusinessException("启用前，请先签署代理商合同!");
                 }
            }*/
            // 二 、禁用二级代理商**********************
            // 1.首先查询对应一级代理商下的二级代理商
            List<Record> secondList = selectSecondList(id);
            //2.获取二级代理商数据后先禁用二级代理商
            Db.update("update crm_trader set status =" + status + " where parent_id=" + "\'" + id + "\'" + "");
            // 3.禁用二级代理商对应的用户user表
            List<String> userIds = secondList.stream().map(s -> s.get("user_id").toString()).collect(Collectors.toList());
            for (String userId : userIds) {
                User user = userDao.get(userId);
                if (Objects.equals(status, UserConstants.USER_STATUS_NORMAL)) {
                    user.setStatus(status);
                } else {
                    user.setStatus(UserConstants.USER_STATUS_DISABLE);
                }
            }
            // 4.禁用二级代理商下的员工
            List<String> secondIdList = secondList.stream().map(s -> s.get("id").toString()).collect(Collectors.toList());
            for (String s : secondIdList) {
                // 获取代理商所属状态正常员工
                List<String> secondEmpList = traderEmployeDao.findSecondTraderEmp(s);
                if (secondEmpList != null && secondEmpList.size() > 0) {
                    // 启用/禁用 二级代理商下面的员工
                    if (Objects.equals(status, UserConstants.USER_STATUS_NORMAL)) {
                        userDao.updateStatusByIds(secondEmpList, UserConstants.USER_STATUS_DISABLE, UserConstants.USER_STATUS_NORMAL);
                    } else {
                        userDao.updateStatusByIds(secondEmpList, UserConstants.USER_STATUS_NORMAL, UserConstants.USER_STATUS_DISABLE);
                    }
                }
            }
            //禁用二级代理结束**************************
        }
        // 删除user
        User user = userDao.get(trader.getUserId());
        if (Objects.equals(status, UserConstants.USER_STATUS_NORMAL)) {
            user.setStatus(status);
        } else {
            user.setStatus(UserConstants.USER_STATUS_DISABLE);
        }
        // 获取代理商所属状态正常员工
        List<String> empList = traderEmployeDao.findSecondTraderEmp(id);
        if (empList != null && empList.size() > 0) {
            // 启用/禁用 二级代理商下面的员工
            if (Objects.equals(status, UserConstants.USER_STATUS_NORMAL)) {
                userDao.updateStatusByIds(empList, UserConstants.USER_STATUS_DISABLE, UserConstants.USER_STATUS_NORMAL);
            } else {
                userDao.updateStatusByIds(empList, UserConstants.USER_STATUS_NORMAL, UserConstants.USER_STATUS_DISABLE);
            }
        }
        return Result.ok();
    }
    public List<Record> getTwoTrader(String topTraderId){
        StringBuilder sb=new StringBuilder();
        sb.append("  SELECT t.id,t.name FROM `crm_trader` t WHERE t.type='2' AND t.status='0' ");
        if(StringUtil.isNotBlank(topTraderId)){
           sb.append(" AND t.parent_id='"+topTraderId+"' ");
        }
        sb.append(" ORDER BY t.parent_id ");
        return Db.find(sb.toString());
    }
    public List<Record>selectSecondList(String id){
        StringBuilder sb=new StringBuilder();
        sb.append("  SELECT * FROM `crm_trader` t WHERE parent_id="+"\'"+id+"\'"+"");
        return Db.find(sb.toString());
    }
    public List<Record> getTopTrader(){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select t.*,CONCAT_WS('',t.province,t.city,t.area,t.address) AS traderAddressfrom,  u.login_name ")
                .line(",CONCAT_WS('',t.take_delivery_province,t.take_delivery_city,t.take_delivery_area,t.take_delivery_address) AS takeAddress")
                .line("from crm_trader t")
                .line("LEFT JOIN sys_user u on t.user_id = u.id")
                .line("where t.status='0' and t.type='1' ");
        builder.line("order by t.create_time desc");
        List<Record> list;
        String topTraderRecords = cacheService.get("topTraderRecords");
        topTraderRecords="";
        if(StringUtil.isNotBlank(topTraderRecords)){
            list =  new Gson().fromJson(topTraderRecords, new TypeToken< List<Record>>() {
            }.getType());
        }else{
            list=  Db.find(builder.build(), builder.params());
            cacheService.set("topTraderRecords",new Gson().toJson(list));
        }
        return list;
    }
    public List<Record> getTopTrader2(){
        User user = UserUtils.getUser();
        String traderId= "";
        if(User.USER_TYPE_WXG.equals(user.getUserType())){
            //平台人员
            //获取当前人员所负责代理商
            Record rd = CrmUtils.getByUserId(user);
            traderId = rd.getStr("trader_id");
        }
        SqlBuilder builder = new SqlBuilder();
        builder.line("select t.*,CONCAT_WS('',t.province,t.city,t.area,t.address) AS traderAddressfrom,  u.login_name ")
                .line(",CONCAT_WS('',t.take_delivery_province,t.take_delivery_city,t.take_delivery_area,t.take_delivery_address) AS takeAddress")
                .line("from crm_trader t")
                .line("LEFT JOIN sys_user u on t.user_id = u.id")
                .line("where t.status='0' and t.type='1' ");
        if (StringUtil.isNotBlank(traderId)){
            builder.inst("and t.id in ", traderId.split(","));
        }
        builder.line("order by t.create_time desc");
        List<Record> list;
        String topTraderRecords = cacheService.get("topTraderRecords");
        topTraderRecords="";
        if(StringUtil.isNotBlank(topTraderRecords)){
            list =  new Gson().fromJson(topTraderRecords, new TypeToken< List<Record>>() {
            }.getType());
        }else{
            list=  Db.find(builder.build(), builder.params());
            cacheService.set("topTraderRecords",new Gson().toJson(list));
        }
        return list;
    }

    public String getPartnerIdByTraderId(String traderId){
        return Db.queryStr("SELECT GROUP_CONCAT(partner_id) FROM `crm_trader_partner` WHERE trader_id=? ",traderId);
    }

    public List<Record> getTopTraders(Map<String, String> map){
        User user=UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){  //平台员工
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }
        SqlBuilder builder=new SqlBuilder();
        builder.line(" SELECT t.id,t.name FROM `crm_trader` t ");
        builder.line(" WHERE  t.type='1' ");
        if(StringUtil.isNotBlank(map.get("provinceE"))){
            builder.inst(" and t.province in ",map.get("provinceE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("cityE"))){
            builder.inst(" and t.city in  ",map.get("cityE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("traderIdsE"))){
            builder.inst(" and t.id in ",map.get("traderIdsE").split(","));
        }
        builder.line(" ORDER BY t.create_time DESC ");
        return Db.find(builder.build(), builder.params());
    }

}
