package com.zfire.mall.manager.logic.policy;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.MainBean;
import com.zfire.mall.manager.bean.admin.AdminUserBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.k3.KingDeeMaterialBean;
import com.zfire.mall.manager.bean.listV2.PolicyCustomerVO;
import com.zfire.mall.manager.bean.listV2.PolicyVO;
import com.zfire.mall.manager.bean.listV2.dto.PolicyDTO;
import com.zfire.mall.manager.bean.policy.*;
import com.zfire.mall.manager.bean.wallet.CustomerWalletBean;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.commonmapper.policy.PolicyCommonMapper;
import com.zfire.mall.manager.commonmapper.retail.RetailOrderCommonMapper;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.enums.PolicyTypeEnum;
import com.zfire.mall.manager.enums.WalletTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.admin.AdminUserLogic;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.k3.K3MaterialLogic;
import com.zfire.mall.manager.logic.saletype.SaleTypeLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售政策
 */
@Service
public class PolicyLogic {

    @Autowired
    PolicyService policyService;
    @Autowired
    PolicyMaterialService policyMaterialService;
    @Autowired
    PolicyConditionService policyConditionService;
    @Autowired
    PolicyConditionMaterialService policyConditionMaterialService;
    @Autowired
    PolicyCustomerService policyCustomerService;
    @Autowired
    PolicyCommonMapper policyCommonMapper;
    @Autowired
    PolicyWalletRelaService policyWalletRelaService;
    @Autowired
    KingDeeWalletService kingDeeWalletService;
    @Autowired
    KingDeeCustomerService kingDeeCustomerService;
    @Autowired
    KingDeeMaterialService kingDeeMaterialService;
    @Autowired
    WalletRebateService walletRebateService;
    @Autowired
    WalletRebateSaleTypeService walletRebateSaleTypeService;
    @Autowired
    PolicyCustomerLimitService policyCustomerLimitService;
    @Autowired
    RetailOrderCommonMapper retailOrderCommonMapper;
    @Autowired
    PolicyGroupLimitService policyGroupLimitService;
    @Autowired
    CommonCMapper commonCMapper;
    @Autowired
    PriceTypeService priceTypeService;
    @Autowired
    PriceSaleTypeRelaService priceSaleTypeRelaService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    SaleTypeLogic saleTypeLogic;
    @Autowired
    K3MaterialLogic k3MaterialLogic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    AdminUserLogic adminUserLogic;

    /**
     * 销售政策列表V2
     */
    public IPage<PolicyVO> listV2(PolicyDTO policyDTO){
        ZfireParamBean zfireParamBean = FieldUtils.supplyParam(policyDTO);

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = policyDTO.getCustomerId();
        //查询经销商可以看到的政策列表
        if(adminUser.getIsCustomer()){
            customerId = adminUser.getCustomerId();
        }
        Integer flag = 0;
        List<String> policyIds = null;
        if(StringUtils.isNotBlank(customerId)) {
            AdminUser customerAdminUser = adminUserService.lambdaQuery()
                    .eq(AdminUser::getCustomerId, customerId)
                    .eq(AdminUser::getIsMaster, true).last("limit 1").one();
            List<PolicyCustomer> list = policyCustomerService.lambdaQuery().eq(PolicyCustomer::getCustomerId, customerId).list();
            policyIds = list.stream().map(PolicyCustomer::getPolicyId).distinct().collect(Collectors.toList());
            if(customerAdminUser == null && CollectionUtils.isEmpty(policyIds)){
                return new Page<>(policyDTO.getPageNum(),policyDTO.getPageSize());
            }
            // 1=广州 2=佛山 0=都不等于，为0只能查policyIds的
            if(customerAdminUser != null) {
                AdminUserBean customerUser = adminUserLogic.detail(customerAdminUser.getAdminUserId());

                flag = adminUser.getAdminWebsit() == null || StringUtils.isEmpty(customerUser.getAdminWebsit().getWebsitNumber())
                        ? 0 : StringUtils.equals(customerUser.getAdminWebsit().getWebsitNumber(), "GZ") ? 1 : 2;

                if(flag == 0 && CollectionUtils.isEmpty(policyIds))
                    return new Page<>(policyDTO.getPageNum(),policyDTO.getPageSize());
            }
        }

        List<String> policyIdsBySpe = null;
        //查询机型规格对应的政策
        if(StringUtils.isNotEmpty(policyDTO.getSpecification())) {
            List<PolicyMaterial> list2 = policyMaterialService.lambdaQuery()
                    .like(PolicyMaterial::getSpecification, policyDTO.getSpecification())
                    .list();
            policyIdsBySpe = list2.stream().map(PolicyMaterial::getPolicyId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(policyIdsBySpe)) {
                return new Page<>(zfireParamBean.getPageNum(), zfireParamBean.getPageSize());
            }
        }
        //查询作废机型规格对应的政策
        if(StringUtils.isNotEmpty(policyDTO.getSpecification2())) {
            List<PolicyMaterial> list2 = policyMaterialService.lambdaQuery()
                    .like( PolicyMaterial::getSpecification, policyDTO.getSpecification2())
                    .eq(PolicyMaterial::getStatus,false)
                    .list();
            policyIdsBySpe = list2.stream().map(PolicyMaterial::getPolicyId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(policyIdsBySpe)) {
                return new Page<>(zfireParamBean.getPageNum(), zfireParamBean.getPageSize());
            }
        }

        IPage<PolicyVO> policyVOIPage = commonCMapper.queryPolicy(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean,policyIdsBySpe, policyIds, flag);
        return policyVOIPage;
    }


    public IPage<PolicyCustomerVO> customerListV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        return commonCMapper.queryPolicyCustomer(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),zfireParamBean);
    }




    /**
     * 销售政策列表
     */
    public IPage<Policy> list(String customerId,String customerNumber,String code,String title,String remark,String startTime1,String endTime1,
                              String startTime2,String endTime2, String startCreateTime,String endCreateTime,String createBy,String examineBy,
                              Boolean status,String type,String specification, Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //查询经销商可以看到的政策列表
        if(adminUser.getIsCustomer() && StringUtils.isEmpty(customerId)){
            customerId = adminUser.getCustomerId();
        }
        if(StringUtils.isNotEmpty(customerNumber)){
            KingDeeCustomer one = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerNumber).one();
            if(one != null) {
                customerId = one.getId();
            }
        }
        List<PolicyCustomer> list = policyCustomerService.lambdaQuery().eq(PolicyCustomer::getCustomerId, customerId).list();
        List<String> policyIds = list.stream().map(PolicyCustomer::getPolicyId).distinct().collect(Collectors.toList());
        final List<String> pIds = policyIds;
        final Integer flag = adminUser.getAdminWebsit() == null ? 0 : Integer.parseInt(StringUtils.equals(adminUser.getAdminWebsit().getWebsitNumber(),"GZ")?"1":"2");

        List<String> policyIdsBySpe = null;
        //查询机型规格对应的政策
        if(StringUtils.isNotEmpty(specification)) {
            List<PolicyMaterial> list2 = policyMaterialService.lambdaQuery()
                    .like(StringUtils.isNotEmpty(specification), PolicyMaterial::getSpecification, specification).list();
            policyIdsBySpe = list2.stream().map(PolicyMaterial::getPolicyId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(policyIdsBySpe)) {
                return new Page<>(pageNum, pageSize);
            }
        }

        IPage<Policy> page = policyService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()),Policy::getAdminCompanyId,adminUser.getAdminCompanyIds())
                .in(CollectionUtils.isNotEmpty(policyIdsBySpe),Policy::getId,policyIdsBySpe)
                .like(StringUtils.isNotEmpty(code), Policy::getCode, code)
                .like(StringUtils.isNotEmpty(title), Policy::getTitle, title)
                .like(StringUtils.isNotEmpty(remark), Policy::getRemark, remark)
                .like(StringUtils.isNotEmpty(examineBy),Policy::getExamineBy,examineBy)
                .between(StringUtils.isNotEmpty(startTime1) && StringUtils.isNotEmpty(endTime1), Policy::getStartTime, startTime1, endTime1)
                .between(StringUtils.isNotEmpty(startTime2) && StringUtils.isNotEmpty(endTime2), Policy::getEndTime, startTime2, endTime2)
                .between(StringUtils.isNotEmpty(startCreateTime) && StringUtils.isNotEmpty(endCreateTime), Policy::getCreateTime, startCreateTime, endCreateTime)
                .like(StringUtils.isNotEmpty(createBy), Policy::getCreateBy, createBy)
                .eq(status != null, Policy::getStatus, status)
                .le(status != null && status,Policy::getStartTime,new Date())
                .ge(status != null && status,Policy::getEndTime,new Date())
                .eq(StringUtils.isNotEmpty(type), Policy::getType, type)
                .and(StringUtils.isNotEmpty(customerId),
                        v -> v.in(CollectionUtils.isNotEmpty(pIds),Policy::getId,pIds)
                                .eq(CollectionUtils.isNotEmpty(pIds),Policy::getFlag,0)
                                .or().eq(flag != 0,Policy::getFlag,flag)
                ).orderByDesc(Policy::getCreateTime, Policy::getId)
                .page(new Page<>(pageNum, pageSize));
        return page;
    }

    /**
     * 新增销售政策 和 经销商
     */
    @Transactional
    public void add(PolicyBean policyBean){
        List<PolicyCustomer> policyCustomers = policyBean.getPolicyCustomers();
        if(CollectionUtils.isEmpty(policyBean.getPolicyCustomers()) && policyBean.getFlag() == 0){
            throw new RemoteServiceException("请选择经销商");
        }
        if(StringUtils.isEmpty(policyBean.getType())){
            throw new RemoteServiceException("请选择政策类型");
        }

        Integer count = policyConditionService.lambdaQuery().eq(PolicyCondition::getPolicyId, policyBean.getCode()).count();
        if(count == 0 && StringUtils.equals(policyBean.getType(),PolicyTypeEnum.PROVISION.toString())){
            throw new RemoteServiceException("配提类型需要创建条件");
        }
//        if(count > 0 && StringUtils.equals(policyBean.getType(),PolicyTypeEnum.LIMIT.toString())){
//            throw new RemoteServiceException("限量类型不需要创建条件");
//        }

        AdminUserCom adminUser = commonLogic.getAdminUser();
        policyBean.setStatus(false);
        policyBean.setExamineStatus(ExamineStatusEnum.SAVE.toString());
        policyBean.setAdminCompanyId(adminUser.getAdminCompanyId());
        policyBean.setId(policyBean.getCode());

        policyBean.insertOrUpdate();
        //添加经销商
        policyCustomers = policyCustomers.stream().distinct().collect(Collectors.toList());
        policyCustomerService.lambdaUpdate().eq(PolicyCustomer::getPolicyId,policyBean.getId()).remove();
        policyCustomerService.saveBatch(policyCustomers);
    }


    /**
     * 编辑政策
     */
    public void update(PolicyBean policyBean){
        //检查是否可以编辑
        this.checkPolicy(policyBean.getId());

        if(CollectionUtils.isEmpty(policyBean.getPolicyCustomers()) && policyBean.getFlag() == 0){
            throw new RemoteServiceException("请选择经销商");
        }
        if(StringUtils.isEmpty(policyBean.getType())){
            throw new RemoteServiceException("请选择政策类型");
        }

        Integer count = policyConditionService.lambdaQuery().eq(PolicyCondition::getPolicyId, policyBean.getId()).count();
        if(count == 0 && StringUtils.equals(policyBean.getType(),PolicyTypeEnum.PROVISION.toString())){
            throw new RemoteServiceException("配提类型需要创建条件");
        }

        policyBean.updateById();
        //先删除经销商，再新增
        if(CollectionUtils.isNotEmpty(policyBean.getPolicyCustomers())) {
            List<PolicyCustomer> policyCustomers = policyBean.getPolicyCustomers().stream().distinct().collect(Collectors.toList());
            policyCustomerService.lambdaUpdate().eq(PolicyCustomer::getPolicyId, policyBean.getId()).remove();
            policyCustomerService.saveBatch(policyCustomers);
        }
    }

    /**
     * 删除政策
     */
    public void delete(String id){
        policyService.removeById(id);
    }

    /**
     * 作废
     */
    public void cancel(String id){
        policyService.lambdaUpdate()
                .set(Policy::getStatus,false)
                .set(Policy::getUpdateBy,CommonUtils.getNickName())
                .set(Policy::getUpdateTime,new Date())
                .eq(Policy::getId,id).update();
    }

    /**
     * 提审
     */
    public void submit(String policyId){
        Policy policy = policyService.getById(policyId);
        if(!StringUtils.equals(policy.getExamineStatus(),ExamineStatusEnum.SAVE.toString())){
            throw new RemoteServiceException("当前状态无法提审");
        }
        policy.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        policy.updateById();
    }

    /**
     *  销售政策审核
     */
    public void examine(String policyId,String examineStatus,String examineRemark){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Policy policy = policyService.getById(policyId);
        if(!policy.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())){
            throw new RemoteServiceException("无需审核");
        }
        //检查是否有商品
        Integer count = policyMaterialService.lambdaQuery().eq(PolicyMaterial::getPolicyId, policyId).count();
        if(count == 0){
            throw new RemoteServiceException("请添加必要的政策机型");
        }
        if(policy.getType().equals(PolicyTypeEnum.PROVISION.toString())){
            Integer count1 = policyConditionMaterialService.lambdaQuery().eq(PolicyConditionMaterial::getPolicyId, policyId).count();
            if(count1 == 0){
                throw new RemoteServiceException("配提政策请添加必要的政策条件和机型");
            }
        }
        policy.setExamineStatus(examineStatus.equals(ExamineStatusEnum.FAIL.toString())?"SAVE":examineStatus);
        policy.setExamineRemark(examineRemark);
        policy.setExamineTime(new Date());
        policy.setStatus(policy.getExamineStatus().equals(ExamineStatusEnum.OK.toString()));
        policy.setExamineBy(adminUser.getNickName());
        policy.updateById();
    }


    /**
     * 新增政策条件
     */
    @Transactional
    public void addCondition(PolicyConditionAdd policyConditionAdd){

        policyConditionMaterialService.lambdaUpdate().eq(PolicyConditionMaterial::getPolicyId,policyConditionAdd.getPolicyId()).remove();
        policyConditionService.lambdaUpdate().eq(PolicyCondition::getPolicyId,policyConditionAdd.getPolicyId()).remove();

        //检查是否可以编辑
        this.checkPolicy(policyConditionAdd.getPolicyId());

        //条件id主键
        String id = IdWorker.getIdStr();
        policyConditionAdd.setId(id);

        List<PolicyConditionMaterial> policyConditionMaterials = policyConditionAdd.getPolicyConditionMaterials();
        if(CollectionUtils.isEmpty(policyConditionMaterials)){
            throw new RemoteServiceException("请添加机型");
        }
        if(policyConditionAdd.getPop().indexOf(":") == -1){
            throw new RemoteServiceException("请填写正确的比例");
        }
        List<PolicyConditionMaterial> distinctList = policyConditionMaterials.stream().distinct().collect(Collectors.toList());
        if(policyConditionMaterials.size() != distinctList.size()){
            throw new RemoteServiceException("存在政策条件内的限定机型和配提机型配置了重复的机型");
        }
        //判断条件的比例和对应的机型是否合格
        String[] split = policyConditionAdd.getPop().split(":");
        for (int i = 1;i <= split.length; i++) {
            int a = i;
            long count = policyConditionMaterials.stream().filter(v -> v.getPopType().intValue() == a).count();
            if(count == 0){
                throw new RemoteServiceException("条件比例与机型配置错误");
            }
            //判断比例格式是否正确
            try {
                int i1 = Integer.parseInt(split[i - 1]);
            }catch(Exception e){
                throw new RemoteServiceException("请填写正确的比例,例如  1:2");
            }
        }
        //检查条件中的限定机型没在本政策其他条件中被引用过
        List<String> materialIds = policyConditionMaterials.stream().filter(v -> v.getPopType() == 1)
                .map(PolicyConditionMaterial::getMaterialId).collect(Collectors.toList());
        Integer count = policyConditionMaterialService.lambdaQuery()
                .in(PolicyConditionMaterial::getMaterialId, materialIds)
                .eq(PolicyConditionMaterial::getPolicyId, policyConditionAdd.getPolicyId())
                .eq(PolicyConditionMaterial::getPopType,1)
                .count();
        if(count > 0){
            throw new RemoteServiceException("限定政策商品在各条件中不可重复被引用");
        }
        for(PolicyConditionMaterial material: policyConditionMaterials){
            PolicyMaterial policyMaterial = this.getPolicyMaterial(material.getPolicyId(), material.getMaterialId(),material.getSaleTypeId());
            if(policyMaterial == null){
                throw new RemoteServiceException("机型:"+material.getMaterialName()+material.getSpecification()+"不存在");
            }
            material.setSaleTypeId(policyMaterial.getSaleTypeId());
            material.setSaleTypeName(policyMaterial.getSaleTypeName());
            material.setSaleTypeCode(policyMaterial.getSaleTypeCode());
            material.setK3CategoryId(policyMaterial.getK3CategoryId());
            material.setK3CategoryNumber(policyMaterial.getK3CategoryNumber());
            material.setK3CategoryName(policyMaterial.getK3CategoryName());
            material.setPolicyMaterialId(policyMaterial.getId());
            material.setDiscAmount(policyMaterial.getDiscAmount());
            material.setUnit(policyMaterial.getUnit());
            material.setTax(policyMaterial.getTax());
            material.setMainId(policyMaterial.getMainId());
            material.setMainName(policyMaterial.getMainName());
            material.setPolicyConditionId(id);
        }

        policyConditionService.save(policyConditionAdd);
        policyConditionMaterialService.saveBatch(policyConditionMaterials);
    }


    /**
     * 修改政策条件
     * @param id
     * @param name
     */
    public void updateCondition(String id,String name){
        PolicyCondition policyCondition = new PolicyCondition();
        policyCondition.setId(id);
        policyCondition.setName(name);
        policyCondition.updateById();
    }

    /**
     * 删除政策条件
     */
    public void deleteCondition(String id){
        policyConditionService.removeById(id);
        policyConditionMaterialService.lambdaUpdate().eq(PolicyConditionMaterial::getPolicyConditionId,id).remove();
    }

    /**
     * 政策条件-详情
     */
    public PolicyCondition detailCondition(String id){
        return policyConditionService.getById(id);
    }

    /**
     *  删除政策产品
     */
    @Transactional
    public void deleteMaterial(String policyMaterialId){
        PolicyMaterial policyMaterial = policyMaterialService.getById(policyMaterialId);
        String policyId = policyMaterial.getPolicyId();

        //检查是否可以编辑
        this.checkPolicy(policyId);

        //检查是否已使用到政策条件中
//        Integer count = policyConditionMaterialService.lambdaQuery().eq(PolicyConditionMaterial::getPolicyMaterialId, policyMaterialId).count();
//        if(count > 0){
//            throw new RemoteServiceException("删除失败，产品已被使用到政策条件中");
//        }
        policyMaterialService.removeById(policyMaterialId);
        policyConditionMaterialService.lambdaUpdate()
                .eq(PolicyConditionMaterial::getPolicyId,policyId)
                .eq(PolicyConditionMaterial::getPolicyMaterialId,policyMaterialId).remove();
    }

    /**
     * 启用/作废政策机型
     */
    @Transactional
    public void statusMaterial(String policyMaterialId,Boolean status){
        PolicyMaterial policyMaterial = policyMaterialService.getById(policyMaterialId);
        if(policyMaterial == null){
            throw new RemoteServiceException("政策机型不存在");
        }
        policyMaterial.setStatus(status);
        policyMaterial.updateById();
        //处理机型条件
        policyConditionMaterialService.lambdaUpdate()
                .set(PolicyConditionMaterial::getStatus,status)
                .eq(PolicyConditionMaterial::getPolicyMaterialId,policyMaterialId).update();
    }
    

    /**
     * 导入政策产品
     */
    @Transactional
    public void importMaterial(String policyId,List<Object> rows){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> k3CategoryIds = adminUser.getK3CategoryIds();
        //检查是否可以编辑
        this.checkPolicy(policyId);
        //所有销售类型code
        List<SaleType> saleTypes = saleTypeLogic.listAll();
        Map<String, SaleType> saleTypeMap = saleTypes.stream().collect(Collectors.toMap(SaleType::getSaleCode, v -> v));
        //所有物料
        List<KingDeeMaterial> kingDeeMaterials = k3MaterialLogic.allList();
        Map<String, KingDeeMaterial> materialMap = kingDeeMaterials.stream().collect(Collectors.toMap(KingDeeMaterial::getNumber, v -> v));
        //查询所有现金钱包
        List<KingDeeWallet> wallets = walletLogic.list(null);
        Map<String, KingDeeWallet> walletMap = wallets.stream().collect(Collectors.toMap(KingDeeWallet::getName, v -> v));
        //查询所有返利钱包
        List<WalletRebate> walletRebates = walletLogic.queryWalletRebateList();
        Map<String, WalletRebate> walletRebateMap = walletRebates.stream().collect(Collectors.toMap(WalletRebate::getName, v -> v));
        //所有销售类型
        List<PriceType> priceTypeList = priceTypeService.lambdaQuery().eq(PriceType::getStatus, true).list();
        Map<String, PriceType> priceTypeMap = priceTypeList.stream().collect(Collectors.toMap(PriceType::getPriceTypeName, v -> v));

        List<PolicyMaterial> list = new ArrayList<>();
        List<PolicyWalletRela> relas = new ArrayList<>();
        for(Object o : rows){
            String id = IdWorker.getIdStr();
            List<Object> row = (List<Object>)o;

            CommonUtils.initList2(row,row.size() + 10);

            String materialNumber = (String)row.get(0);
            if(StringUtils.isEmpty(materialNumber)){
                continue;
            }
            String saleTypeCode = (String)row.get(3);
            BigDecimal price = new BigDecimal(row.get(5).toString());
            String remark = (String)row.get(6);
            BigDecimal discAmount = new BigDecimal(row.get(7) == null ? "0" : row.get(7).toString().equals("")?"0":row.get(7).toString());
            String walletNames = (String)row.get(8);
            String rebateWalletNames = (String)row.get(9);
            String orgPrice = (String)row.get(10);
            String priceType = (String)row.get(11);
            String[] walletName = walletNames.trim().replaceAll("，",",").split(",");

            if(StringUtils.isEmpty(materialNumber) || StringUtils.isEmpty(saleTypeCode) || price == null
                    || walletName == null || walletName.length == 0){
                throw new RemoteServiceException("检测到物料编码/销售类型编码/单价/现金钱包有为空的情况");
            }
            if(!saleTypeMap.keySet().contains(saleTypeCode)){
                throw new RemoteServiceException("销售类型编码:"+saleTypeCode+"不存在");
            }
            if(!materialMap.keySet().contains(materialNumber)){
                throw new RemoteServiceException("物料编码:"+materialNumber+"不存在");
            }
            SaleType saleType = saleTypeMap.get(saleTypeCode);
            KingDeeMaterial kingDeeMaterial = materialMap.get(materialNumber);
            MainBean mainBean = commonLogic.getMainBean(kingDeeMaterial.getId());
            //价格类型
            if(StringUtils.isNotBlank(priceType) ){
                if(!priceTypeMap.containsKey(priceType))
                    throw new RemoteServiceException("价格类型【"+priceType+"】不存在");
                PriceType priceTypeBean = priceTypeMap.get(priceType);
                //检测是否有价格类型和销售类型的对应关系
                Integer count1 = priceSaleTypeRelaService.lambdaQuery().eq(PriceSaleTypeRela::getStatus, true)
                        .eq(PriceSaleTypeRela::getPriceTypeId, priceTypeBean.getPriceTypeId())
                        .eq(PriceSaleTypeRela::getSaleId, saleType.getId()).count();
                if(count1 == 0)
                    throw new RemoteServiceException("价格类型【"+priceTypeBean.getPriceTypeName()+"】与销售类型【"+saleType.getSaleName()+"】对应关系不存在");
            }

            //检测是否有权限
            if(CollectionUtils.isNotEmpty(k3CategoryIds) && !k3CategoryIds.contains(kingDeeMaterial.getCategoryId())){
                throw new RemoteServiceException("检测到您暂无机型【"+kingDeeMaterial.getSpecification()+"】的权限");
            }

            //政策产品
            PolicyMaterial policyMaterial = new PolicyMaterial();
            policyMaterial.setId(id);
            policyMaterial.setPolicyId(policyId);
            if(mainBean != null) {
                policyMaterial.setMainId(mainBean.getMainId());
                policyMaterial.setMainName(mainBean.getMainName());
            }
            policyMaterial.setMaterialId(kingDeeMaterial.getId());
            policyMaterial.setMaterialName(kingDeeMaterial.getName());
            policyMaterial.setMaterialNumber(kingDeeMaterial.getNumber());
            policyMaterial.setK3CategoryId(kingDeeMaterial.getCategoryId());
            policyMaterial.setK3CategoryNumber(kingDeeMaterial.getCategoryNumber());
            policyMaterial.setK3CategoryName(kingDeeMaterial.getCategoryName());
            policyMaterial.setSpecification(kingDeeMaterial.getSpecification());
            policyMaterial.setSaleTypeId(saleType.getId());
            policyMaterial.setSaleTypeCode(saleType.getSaleCode());
            policyMaterial.setSaleTypeName(saleType.getSaleName());
            policyMaterial.setPrice(price);
            policyMaterial.setRemark(remark);
            policyMaterial.setDiscAmount(discAmount);
            policyMaterial.setTax(kingDeeMaterial.getTaxRateId());
            policyMaterial.setUnit(kingDeeMaterial.getBaseUnitId());
            if(orgPrice != null){
                policyMaterial.setOrgPrice(new BigDecimal(orgPrice));
            }
            policyMaterial.setPriceType(priceType);
            list.add(policyMaterial);

            for(String name : walletName){
                KingDeeWallet wallet = walletMap.get(name);
                if(wallet == null){
                    throw new RemoteServiceException("钱包名称："+name+"，不存在");
                }
                //政策钱包
                PolicyWalletRela policyWalletRela = new PolicyWalletRela();
                policyWalletRela.setPolicyId(policyId);
                policyWalletRela.setPolicyMaterialId(id);
                policyWalletRela.setWalletName(name);
                policyWalletRela.setType(WalletTypeEnum.COMMONLY.getKey());
                policyWalletRela.setWalletId(wallet.getId());
                relas.add(policyWalletRela);
            }

            if(StringUtils.isNotEmpty(rebateWalletNames)) {
                String[] rebateWalletName = rebateWalletNames.trim().replaceAll("，",",").split(",");
                for (String name : rebateWalletName) {
                    WalletRebate walletRebate = walletRebateMap.get(name);
                    if (walletRebate == null) {
                        throw new RemoteServiceException("返利钱包名称：" + name + "，不存在");
                    }
                    Integer count = commonLogic.getRebateSaleTypeCount(saleType.getId(), walletRebate.getWalletRebateId());
                    if (count == 0) {
                        throw new RemoteServiceException("返利钱包+【"+walletRebate.getName() + "】与销售类型【" + saleType.getSaleName() + "】对应关系不存在");
                    }
                    //政策钱包
                    PolicyWalletRela policyWalletRela = new PolicyWalletRela();
                    policyWalletRela.setPolicyId(policyId);
                    policyWalletRela.setPolicyMaterialId(id);
                    policyWalletRela.setWalletName(name);
                    policyWalletRela.setType(WalletTypeEnum.REBATE.getKey());
                    policyWalletRela.setWalletId(walletRebate.getWalletRebateId());
                    relas.add(policyWalletRela);
                }
            }

        }

        Set<String> distinct = new HashSet<>();
        for(PolicyMaterial policyMaterial : list){
            distinct.add(policyMaterial.getSaleTypeCode()+policyMaterial.getMaterialId());
        }
        if(distinct.size() != list.size()){
            throw new RemoteServiceException("请检查是否存在同销售类型同物料编号的商品");
        }

        //覆盖，先删后增
        policyMaterialService.lambdaUpdate().eq(PolicyMaterial::getPolicyId,policyId).remove();
        policyMaterialService.saveBatch(list);
        //覆盖，先删后增
        policyWalletRelaService.lambdaUpdate().eq(PolicyWalletRela::getPolicyId,policyId).remove();
        policyWalletRelaService.saveBatch(relas);
    }


    /**
     * 销售政策详情
     */
    public Policy detail(String policyId){
        Policy policy = policyService.getById(policyId);
        return policy;
    }

    /**
     * 政策产品信息列表
     */
    public IPage<PolicyMaterialBean> materialList(String policyId,String specification,Boolean isProvision,Boolean status,
                                                  String saleTypeCode,String priceType,Integer pageNum,Integer pageSize){

        List<String> policyMaterialIds = new ArrayList<>();
        //查询配提机型，则需要过滤限定机型
        if(isProvision != null && isProvision) {
            List<PolicyConditionMaterial> policyConditionMaterials = policyConditionMaterialService.lambdaQuery()
                    .eq(PolicyConditionMaterial::getPolicyId, policyId)
                    .eq(status!= null ,PolicyConditionMaterial::getStatus,status)
                    .eq(PolicyConditionMaterial::getPopType, 1).list();

            policyMaterialIds = policyConditionMaterials.stream().map(PolicyConditionMaterial::getPolicyMaterialId).collect(Collectors.toList());
        }

        IPage page = policyMaterialService.lambdaQuery()
                .like(StringUtils.isNotEmpty(priceType),PolicyMaterial::getPriceType,priceType)
                .eq(StringUtils.isNotEmpty(saleTypeCode),PolicyMaterial::getSaleTypeCode,saleTypeCode)
                .like(StringUtils.isNotEmpty(specification),PolicyMaterial::getSpecification,specification)
                .eq(PolicyMaterial::getPolicyId, policyId)
                .eq(status != null,PolicyMaterial::getStatus,status)
                .notIn(CollectionUtils.isNotEmpty(policyMaterialIds),PolicyMaterial::getMaterialId,policyMaterialIds)
                .orderByDesc(PolicyMaterial::getId)
                .page(new Page<>(pageNum, pageSize));

        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<CustomerWalletBean> customerWalletBeans = new ArrayList<>();
        if(adminUser.getIsCustomer()) {
            customerWalletBeans = walletLogic.queryWalletByCustomerId(adminUser.getCustomerId(), null,null);
        }

        List<PolicyWalletRela> policyWalletRelas = policyWalletRelaService.lambdaQuery()
                .eq(PolicyWalletRela::getPolicyId, policyId)
                .orderByAsc(PolicyWalletRela::getId).list();

        List<PolicyMaterialBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            PolicyMaterial policyMaterial = (PolicyMaterial)o;
            PolicyMaterialBean policyMaterialBean = new PolicyMaterialBean();
            BeanUtils.copyProperties(policyMaterial,policyMaterialBean);

//            List<PolicyWalletRela> wallets = policyWalletRelaService.lambdaQuery()
//                    .eq(PolicyWalletRela::getPolicyId, policyMaterial.getPolicyId())
//                    .eq(PolicyWalletRela::getPolicyMaterialId, policyMaterial.getId())
//                    .list();
            List<PolicyWalletRela> wallets = policyWalletRelas.stream().filter(v -> v.getPolicyMaterialId().equals(policyMaterial.getId())).collect(Collectors.toList());
            List<String> walletIds = wallets.stream().map(PolicyWalletRela::getWalletId).collect(Collectors.toList());
            List<CustomerWalletBean> customerWalletBeans2 = customerWalletBeans.stream().filter(v -> walletIds.contains(v.getWalletRebateId())).collect(Collectors.toList());
            policyMaterialBean.setWalletRelaList(wallets);

            //现金钱包
//            if(policyMaterialBean.getMainName() != null && policyMaterialBean.getMainName() != null && policyMaterialBean.getMainName().indexOf(Constant.MAIN_SY) > -1) {
//                policyMaterialBean.getWallets().addAll(customerWalletBeans.stream()
//                        .filter(v -> v.getType().equals(WalletTypeEnum.COMMONLY.getKey()) && v.getName().indexOf(Constant.MAIN_SY) > -1)
//                        .collect(Collectors.toList()));
//            }else{
                policyMaterialBean.getWallets().addAll(customerWalletBeans2.stream()
                        .filter(v -> v.getType().equals(WalletTypeEnum.COMMONLY.getKey()))
                        .collect(Collectors.toList()));
            //}
            //返利钱包
            List<CustomerWalletBean> rebateWallet = CommonUtils.findRebateRate(customerWalletBeans2, policyMaterial.getSaleTypeId());
            policyMaterialBean.getRebateWallets().addAll(rebateWallet);

            list.add(policyMaterialBean);
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 保存产品
     */
    @Transactional
    public void saveMaterial(List<PolicyMaterialAddBean> policyMaterialAddBeans){
        if(policyMaterialAddBeans.size() == 0){
            return;
        }
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> k3CategoryIds = adminUser.getK3CategoryIds();

        List<String> policyIds = policyMaterialAddBeans.stream().map(PolicyMaterialAddBean::getPolicyId).distinct().collect(Collectors.toList());
        if(policyIds.size() > 1){
            throw new RemoteServiceException("参数存在错误数据");
        }
        String policyId = policyIds.get(0);

        Policy policy = policyService.getById(policyId);
        if(policy != null){
            if(!policy.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString())){
                throw new RemoteServiceException("政策非保存状态不可更改");
            }
        }

        List<String> policyMaterialIds = policyMaterialAddBeans.stream().map(PolicyMaterialAddBean::getId).collect(Collectors.toList());
        List<PolicyConditionMaterial> policyConditionMaterials = policyConditionMaterialService.lambdaQuery().in(PolicyConditionMaterial::getPolicyId, policyId).list();
        for(PolicyConditionMaterial pcm : policyConditionMaterials){
            if(!policyMaterialIds.contains(pcm.getPolicyMaterialId()) && policy != null && policy.getType().equals(PolicyTypeEnum.PROVISION.toString())){
                throw new RemoteServiceException("政策条件的机型【"+pcm.getSpecification()+"】不存在政策机型中");
            }
        }

        //检查是否存在配提机型
//        Integer conditionMaterialCount = policyConditionService.lambdaQuery()
//                .eq(PolicyCondition::getPolicyId, policyId)
//                .count();
//        if(conditionMaterialCount > 0){
//            throw new RemoteServiceException("保存失败，请先删除政策条件");
//        }

        //钱包配置先删后增
        //1.remove
        policyWalletRelaService.lambdaUpdate().eq(PolicyWalletRela::getPolicyId, policyMaterialAddBeans.get(0).getPolicyId()).remove();
        List<String> distincts = new ArrayList<>();
        for(PolicyMaterialAddBean bean : policyMaterialAddBeans) {
            String id = bean.getId();
            String materialId = bean.getMaterialId();
            String saleTypeId = bean.getSaleTypeId();
            BigDecimal price = bean.getPrice();
            BigDecimal discAmount = bean.getDiscAmount() == null ? BigDecimal.valueOf(0):bean.getDiscAmount();
            String remark = bean.getRemark();
            List<String> walletIds = bean.getWalletIds();
            List<String> rebateWalletIds = bean.getRebateWalletIds();

            if(materialId == null){
                throw new RemoteServiceException("请选择机型");
            }
            if(CollectionUtils.isEmpty(walletIds)){
                throw new RemoteServiceException("请选择钱包");
            }
//            if(CollectionUtils.isEmpty(rebateWalletIds)){
//                throw new RemoteServiceException("请选择返利钱包");
//            }
            if(price == null){
                throw new RemoteServiceException("请填写单价");
            }
            if(distincts.contains(materialId + saleTypeId)){
                throw new RemoteServiceException("同一政策不可存在相同销售类型的机型");
            }else{
                distincts.add(materialId + saleTypeId);
            }
            if (price.doubleValue() < 0) {
                throw new RemoteServiceException("单价不可小于0");
            }
            if (discAmount.doubleValue() < 0) {
                throw new RemoteServiceException("格力折扣不可小于0");
            }
            if (discAmount.doubleValue() > price.doubleValue()) {
                throw new RemoteServiceException("格力折扣不可大于单价");
            }

//            if(policyConditionMaterial != null){
//                throw new RemoteServiceException("保存失败，存在机型已被使用到政策条件中");
//            }

            KingDeeMaterialBean detail = k3MaterialLogic.detail(materialId);
            SaleType saleType = saleTypeLogic.detail(saleTypeId);

            MainBean mainBean = commonLogic.getMainBean(materialId);

            //检测是否有权限
            if(CollectionUtils.isNotEmpty(k3CategoryIds) && !k3CategoryIds.contains(detail.getCategoryId())){
                throw new RemoteServiceException("检测到您暂无机型【"+detail.getSpecification()+"】的权限");
            }

            PolicyMaterial policyMaterial = new PolicyMaterial();
            policyMaterial.setPolicyId(policyId);
            policyMaterial.setMaterialId(materialId);
            policyMaterial.setMaterialNumber(detail.getNumber());
            policyMaterial.setMaterialName(detail.getName());
            policyMaterial.setK3CategoryId(detail.getCategoryId());
            policyMaterial.setK3CategoryNumber(detail.getCategoryNumber());
            policyMaterial.setK3CategoryName(detail.getCategoryName());
            policyMaterial.setUnit(detail.getBaseUnitId());
            policyMaterial.setSpecification(detail.getSpecification());
            policyMaterial.setSaleTypeId(saleTypeId);
            policyMaterial.setSaleTypeCode(saleType.getSaleCode());
            policyMaterial.setSaleTypeName(saleType.getSaleName());
            policyMaterial.setPrice(price);
            policyMaterial.setDiscAmount(discAmount);
            policyMaterial.setRemark(remark);
            policyMaterial.setOrgPrice(bean.getOrgPrice());
            policyMaterial.setPriceType(bean.getPriceType());
            if (StringUtils.isNotEmpty(id)) {
                policyMaterial.setId(id);
            }
            if(mainBean != null){
                policyMaterial.setMainId(mainBean.getMainId());
                policyMaterial.setMainName(mainBean.getMainName());
            }
            policyMaterial.insertOrUpdate();


            //检查是否存在配提机型
            PolicyConditionMaterial policyConditionMaterial = policyConditionMaterialService.lambdaQuery()
                    .eq(PolicyConditionMaterial::getPolicyId, policyId)
                    .eq(PolicyConditionMaterial::getPolicyMaterialId,policyMaterial.getId())
                    .one();
            if(policyConditionMaterial != null) {
                String oldId = policyConditionMaterial.getId();
                BeanUtils.copyProperties(policyMaterial,policyConditionMaterial);
                policyConditionMaterial.setId(oldId);
                policyConditionMaterial.updateById();
            }


            //2.add wallet
            List<PolicyWalletRela> wallets = new ArrayList<>();
            for (String wId : walletIds) {
                KingDeeWallet wallet = kingDeeWalletService.getById(wId);
                PolicyWalletRela policyWalletRela = new PolicyWalletRela();
                policyWalletRela.setWalletId(wId);
                policyWalletRela.setWalletName(wallet.getName());
                policyWalletRela.setPolicyId(policyId);
                policyWalletRela.setPolicyMaterialId(policyMaterial.getId());
                policyWalletRela.setType(WalletTypeEnum.COMMONLY.getKey());
                wallets.add(policyWalletRela);
            }
            //3.add rebate wallet
            if(CollectionUtils.isNotEmpty(rebateWalletIds)) {
                for (String wId : rebateWalletIds) {
                    Integer count = commonLogic.getRebateSaleTypeCount(saleTypeId, wId);
                    WalletRebate wallet = walletRebateService.getById(wId);
                    if (count == 0) {
                        throw new RemoteServiceException("返利钱包+【"+wallet.getName() + "】与销售类型【" + saleType.getSaleName() + "】对应关系不存在");
                    }
                    PolicyWalletRela policyWalletRela = new PolicyWalletRela();
                    policyWalletRela.setWalletId(wId);
                    policyWalletRela.setWalletName(wallet.getName());
                    policyWalletRela.setPolicyId(policyId);
                    policyWalletRela.setPolicyMaterialId(policyMaterial.getId());
                    policyWalletRela.setType(WalletTypeEnum.REBATE.getKey());
                    wallets.add(policyWalletRela);
                }
            }
            policyWalletRelaService.saveBatch(wallets);
        }
        List<PolicyMaterial> list = policyMaterialService.lambdaQuery()
                .eq(PolicyMaterial::getPolicyId, policyId)
                .list();
        List<String> pMaterialIds = list.stream().map(PolicyMaterial::getId).collect(Collectors.toList());
        //删除配提的机型，可能在外已经不存在的配提机型
        policyConditionMaterialService.lambdaUpdate()
                .eq(PolicyConditionMaterial::getPolicyId,policyId)
                .notIn(PolicyConditionMaterial::getPolicyMaterialId,pMaterialIds).remove();
    }


    /**
     * 政策的限定机型列表
     * @param policyId
     * @param saleTypeCode
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<PolicyConditionMaterialBean> type1MaterialList(String policyId,String saleTypeCode,String specification,Boolean status,Integer pageNum,Integer pageSize){
        IPage page = policyConditionMaterialService.lambdaQuery()
                .eq(PolicyConditionMaterial::getPolicyId, policyId)
                .eq(PolicyConditionMaterial::getPopType, 1)
                .eq(PolicyConditionMaterial::getStatus,status)
                .like(StringUtils.isNotEmpty(specification),PolicyConditionMaterial::getSpecification,specification)
                .eq(StringUtils.isNotEmpty(saleTypeCode), PolicyConditionMaterial::getSaleTypeCode, saleTypeCode)
                .orderByDesc(PolicyConditionMaterial::getId)
                .page(new Page<>(pageNum, pageSize));

        List<PolicyConditionMaterialBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            PolicyConditionMaterial bean = (PolicyConditionMaterial)o;
            PolicyConditionMaterialBean policyMaterialBean = new PolicyConditionMaterialBean();
            BeanUtils.copyProperties(bean,policyMaterialBean);

            list.add(policyMaterialBean);
        }
        page.setRecords(list);
        return page;
    }


    /**
     * 指定的政策产品
     */
    public PolicyMaterial getPolicyMaterial(String policyId,String materialId,String saleTypeId){
        return policyMaterialService.lambdaQuery()
                .eq(PolicyMaterial::getPolicyId,policyId)
                .eq(PolicyMaterial::getMaterialId,materialId)
                .eq(PolicyMaterial::getSaleTypeId,saleTypeId)
                .one();
    }


    /**
     * 政策经销商列表
     */
    public IPage<PolicyCustomer> customerList(String policyId,Integer pageNum,Integer pageSize){
        IPage<PolicyCustomer> page = policyCustomerService.lambdaQuery()
                .eq(PolicyCustomer::getPolicyId, policyId)
                .orderByDesc(PolicyCustomer::getCreateTime, PolicyCustomer::getId)
                .page(new Page<>(pageNum, pageSize));
        return page;
    }

    /**
     *对应经销商列表
     */
    public IPage<PolicyBean> queryPolicyCount(String code,String remark,String title,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        IPage<PolicyBean> policyBeanIPage = policyCommonMapper.queryPolicyCustomer(new Page(pageNum, pageSize), code, remark, title, adminUser.getAdminCompanyIds());
        return policyBeanIPage;
    }


    /**
     * 批量设置对应的经销商列表
     */
    public void batchSetup(List<String> policyCustomerIds,Integer limitTakeNum,String remark){
        if(StringUtils.isEmpty(remark) && limitTakeNum == null){
            throw new RemoteServiceException("最多提货数量和备注必填其中之一");
        }
        policyCustomerService.lambdaUpdate()
                .set(limitTakeNum != null,PolicyCustomer::getLimitTakeNum,limitTakeNum)
                .set(StringUtils.isNotEmpty(remark),PolicyCustomer::getRemark,remark)
                .in(PolicyCustomer::getId,policyCustomerIds).update();
    }

    /**
     * 政策条件
     */
    public List<PolicyCondition> conditionList(String policyId){
        List<PolicyCondition> list = policyConditionService.lambdaQuery()
                .eq(PolicyCondition::getPolicyId, policyId)
                .orderByDesc(PolicyCondition::getCreateTime, PolicyCondition::getId).list();
        return list;
    }

    /**
     * 政策条件的机型
     */
    public IPage<PolicyConditionMaterialBean> conditionMaterialList(String policyConditionId,Integer popType,String specification,String customerId,
                                                                    Boolean status,String priceType,Integer pageNum,Integer pageSize){

        IPage page = policyConditionMaterialService.lambdaQuery()
                .like(StringUtils.isNotEmpty(priceType),PolicyConditionMaterial::getPriceType,priceType)
                .eq(PolicyConditionMaterial::getPopType,popType)
                .eq(PolicyConditionMaterial::getPolicyConditionId, policyConditionId)
                .eq(status != null,PolicyConditionMaterial::getStatus,status)
                .like(StringUtils.isNotEmpty(specification),PolicyConditionMaterial::getSpecification,specification)
                .orderByDesc(PolicyConditionMaterial::getPolicyConditionId, PolicyConditionMaterial::getId)
                .page(new Page<>(pageNum, pageSize));

        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<CustomerWalletBean> customerWalletBeans = new ArrayList<>();
        if(adminUser.getIsCustomer()) {
            customerWalletBeans = walletLogic.queryWalletByCustomerId(adminUser.getCustomerId(), null,null);
        }else{
            if(StringUtils.isNotEmpty(customerId)) {
                customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, null, null);
            }
        }

        Map<String, CustomerWalletBean> commonlyCustomerWalletMap = customerWalletBeans.stream()
                .collect(Collectors.toMap(CustomerWalletBean::getWalletRebateId, v -> v));

        List<PolicyConditionMaterialBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            PolicyConditionMaterial bean = (PolicyConditionMaterial)o;
            PolicyConditionMaterialBean policyMaterialBean = new PolicyConditionMaterialBean();
            BeanUtils.copyProperties(bean,policyMaterialBean);
            List<CustomerWalletBean> customerWallets = this.supplyWallet(bean.getPolicyMaterialId(),bean.getPolicyId(), commonlyCustomerWalletMap);
            //现金钱包
//            if(policyMaterialBean.getMainName() != null && policyMaterialBean.getMainName() != null && policyMaterialBean.getMainName().indexOf(Constant.MAIN_SY) > -1) {
//                policyMaterialBean.getWallets().addAll(customerWallets.stream()
//                        .filter(v -> v.getType().equals(WalletTypeEnum.COMMONLY.getKey()) && v.getName().indexOf(Constant.MAIN_SY) > -1)
//                        .collect(Collectors.toList())
//                );
//            }else{
                policyMaterialBean.getWallets().addAll(customerWallets.stream()
                        .filter(v -> v.getType().equals(WalletTypeEnum.COMMONLY.getKey()))
                        .collect(Collectors.toList()));
            //}
            //返利钱包
            List<CustomerWalletBean> rebateWallet = CommonUtils.findRebateRate(customerWallets, bean.getSaleTypeId());
            policyMaterialBean.getRebateWallets().addAll(rebateWallet);

            list.add(policyMaterialBean);
        }
        page.setRecords(list);
        return page;
    }


    public List<CustomerWalletBean> supplyWallet(String policyMaterialId, String policyId,Map<String, CustomerWalletBean> customerWalletMap){
        List<PolicyWalletRela> policyWalletRelas = policyWalletRelaService.lambdaQuery()
                .eq(PolicyWalletRela::getPolicyMaterialId, policyMaterialId)
                .eq(PolicyWalletRela::getPolicyId,policyId)
                .list();
        List<CustomerWalletBean> list = new ArrayList<>();
        for(PolicyWalletRela wallet : policyWalletRelas){
            CustomerWalletBean customerWalletBean = customerWalletMap.get(wallet.getWalletId());
            if(customerWalletBean != null && customerWalletBean.getType().equals(WalletTypeEnum.COMMONLY.getKey())){
                //现金钱包
                list.add(customerWalletBean);
            }else if(customerWalletBean != null && customerWalletBean.getType().equals(WalletTypeEnum.REBATE.getKey())){
                //返利钱包
                list.add(customerWalletBean);
            }
        }
        return list;
    }


    /**
     * 根据机型id和政策id反查政策条件
     */
    public PolicyCondition getCondition(String policyId,String materialId){
        PolicyConditionMaterial policyConditionMaterial = policyConditionMaterialService.lambdaQuery()
                .eq(PolicyConditionMaterial::getPolicyId, policyId)
                .eq(PolicyConditionMaterial::getMaterialId, materialId)
                .eq(PolicyConditionMaterial::getPopType,1)
                .one();
        PolicyCondition policyCondition = policyConditionService.getById(policyConditionMaterial.getPolicyConditionId());
        return policyCondition;
    }

    /**
     * 查询条件
     */
    public PolicyCondition getCondition(String id){
        PolicyCondition policyCondition = policyConditionService.getById(id);
        return policyCondition;
    }

    public List<PolicyCondition> getConditionByPolicyId(String policyId){
        List<PolicyCondition> list = policyConditionService.lambdaQuery().eq(PolicyCondition::getPolicyId, policyId).list();
        return list;
    }

    /**
     * 克隆政策
     */
    @Transactional
    public void clonePolicy(String policyId){
        Policy policy = policyService.getById(policyId);
        List<PolicyMaterial> policyMaterials = policyMaterialService.lambdaQuery()
                .eq(PolicyMaterial::getPolicyId, policyId).orderByAsc(PolicyMaterial::getId).list();
        List<PolicyCondition> conditionList = policyConditionService.lambdaQuery().eq(PolicyCondition::getPolicyId, policyId).list();
        List<PolicyConditionMaterial> conditionMaterials = policyConditionMaterialService.lambdaQuery()
                .eq(PolicyConditionMaterial::getPolicyId,policyId).orderByAsc(PolicyConditionMaterial::getId).list();
        List<PolicyCustomer> policyCustomers = policyCustomerService.lambdaQuery()
                .eq(PolicyCustomer::getPolicyId, policyId)
                .orderByAsc(PolicyCustomer::getId).list();
        List<PolicyWalletRela> relas = policyWalletRelaService.lambdaQuery()
                .eq(PolicyWalletRela::getPolicyId,policyId).orderByAsc(PolicyWalletRela::getId).list();
        List<PolicyCustomerLimit> limits = policyCustomerLimitService.lambdaQuery()
                .eq(PolicyCustomerLimit::getPolicyId, policyId).orderByAsc(PolicyCustomerLimit::getId).list();

        //政策
        policy.setId("P"+IdWorker.getIdStr());
        policy.setCode(policy.getId());
        policy.setExamineStatus(ExamineStatusEnum.SAVE.toString());
        policy.setStatus(false);
        policy.setCreateTime(null);
        policy.setCreateBy(null);
        policy.setUpdateBy(null);
        policy.setUpdateTime(null);
        policy.insert();
        //政策经销商
        for (PolicyCustomer policyCustomer : policyCustomers) {
            policyCustomer.setPolicyId(policy.getId());
            policyCustomer.setId(IdWorker.getIdStr());
            policyCustomer.setCreateTime(null);
            policyCustomer.setCreateBy(null);
            policyCustomer.setUpdateBy(null);
            policyCustomer.setUpdateTime(null);
        }
        policyCustomerService.saveBatch(policyCustomers);

        //key = 旧id  value = 新id
        Map<String,String> idMap = new HashMap<>();
        //政策条件
        for (PolicyCondition policyCondition : conditionList) {

            String newId = IdWorker.getIdStr();
            idMap.put(policyCondition.getId(),newId);

            policyCondition.setPolicyId(policy.getId());
            policyCondition.setId(newId);
            policyCondition.setCreateTime(null);
            policyCondition.setCreateBy(null);
            policyCondition.setUpdateBy(null);
            policyCondition.setUpdateTime(null);
        }
        policyConditionService.saveBatch(conditionList);
        //政策机型
        for (PolicyMaterial policyMaterial : policyMaterials) {

            String newId = IdWorker.getIdStr();
            idMap.put(policyMaterial.getId(),newId);

            policyMaterial.setPolicyId(policy.getId());
            policyMaterial.setId(newId);
            policyMaterial.setCreateTime(null);
            policyMaterial.setCreateBy(null);
            policyMaterial.setUpdateBy(null);
            policyMaterial.setUpdateTime(null);
        }
        policyMaterialService.saveBatch(policyMaterials);
        //政策条件机型
        for (PolicyConditionMaterial conditionMaterial : conditionMaterials) {
            conditionMaterial.setPolicyId(policy.getId());
            conditionMaterial.setId(null);
            conditionMaterial.setPolicyConditionId(idMap.get(conditionMaterial.getPolicyConditionId()));
            conditionMaterial.setPolicyMaterialId(idMap.get(conditionMaterial.getPolicyMaterialId()));
            conditionMaterial.setCreateTime(null);
            conditionMaterial.setCreateBy(null);
            conditionMaterial.setUpdateBy(null);
            conditionMaterial.setUpdateTime(null);
        }
        policyConditionMaterialService.saveBatch(conditionMaterials);

        List<PolicyWalletRela> newRelas = new ArrayList<>();
        for (PolicyWalletRela rela : relas) {
            if(idMap.get(rela.getPolicyMaterialId()) == null){
                continue;
            }
            rela.setPolicyId(policy.getId());
            rela.setPolicyMaterialId(idMap.get(rela.getPolicyMaterialId()));
            rela.setId(null);
            rela.setCreateTime(null);
            rela.setCreateBy(null);
            rela.setUpdateBy(null);
            rela.setUpdateTime(null);
            newRelas.add(rela);
        }
        policyWalletRelaService.saveBatch(newRelas);

        for(PolicyCustomerLimit limit : limits){
            limit.setPolicyId(policy.getId());
            limit.setId(null);
            limit.setCreateTime(null);
            limit.setCreateBy(null);
        }
        policyCustomerLimitService.saveBatch(limits);

    }


    /**
     * 弃审
     */
    public void abandon(String policyId){
        Policy policy = policyService.getById(policyId);
        policy.setExamineStatus(ExamineStatusEnum.SAVE.toString());
        policy.setStatus(false);
        policy.updateById();
    }

    /**
     * 检查政策是否可以编辑
     */
    public void checkPolicy(String policyId){
        Policy policy = policyService.getById(policyId);
        if(policy != null && !StringUtils.equals(policy.getExamineStatus(),ExamineStatusEnum.SAVE.toString())){
            throw new RemoteServiceException("非保存状态不可更改");
        }
    }

    /**
     * 导入经销商
     */
    public List<KingDeeCustomer>  importCustomer(List<Object> objects){
        List<String> customerCodes = new ArrayList<>();
        for(Object o : objects){
            List<Object> row = (List<Object>) o;
            String customerCode = (String)row.get(0);
            if(StringUtils.isNotEmpty(customerCode)){
                customerCodes.add(customerCode);
            }
        }
        List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().in(KingDeeCustomer::getNumber, customerCodes).list();
        return list;
    }

    /**
     * 导入经销商购买上限
     */
    @Transactional
    public void importCustomerLimit(String policyId,List<Object> objects){
        
        List<PolicyCustomerLimit> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        List<Object> collect = objects.stream().distinct().collect(Collectors.toList());
        for(Object o : collect){
            List<Object> row = (List<Object>)o;
            CommonUtils.initList2(row,10);
            String customerNumber = (String)row.get(0);
            String materialNumber = (String)row.get(1);
            String limitQty = (String)row.get(2);
            //String popQty = (String)row.get(3);
//            String minBuyNum = (String)row.get(3);
//            String maxBuyNum = (String)row.get(4);

            set.add(customerNumber + materialNumber);

            if(StringUtils.isEmpty(customerNumber)){
                continue;
            }
            if(StringUtils.isEmpty(customerNumber) || StringUtils.isEmpty(materialNumber) || StringUtils.isEmpty(limitQty)){
                throw new RemoteServiceException("经销商编号/物料编号/购买上限不能为空");
            }

            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerNumber).one();
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, materialNumber).one();
            if(kingDeeCustomer == null){
                throw new RemoteServiceException("经销商编号:"+customerNumber +"在当前政策不存在");
            }
            if(kingDeeMaterial == null){
                throw new RemoteServiceException("物料编号:"+materialNumber +"在当前政策不存在");
            }
            PolicyCustomerLimit policyCustomerLimit = new PolicyCustomerLimit();
            policyCustomerLimit.setCustomerId(kingDeeCustomer.getId());
            policyCustomerLimit.setCustomerNumber(kingDeeCustomer.getNumber());
            policyCustomerLimit.setCustomerName(kingDeeCustomer.getName());
            policyCustomerLimit.setMaterialId(kingDeeMaterial.getId());
            policyCustomerLimit.setMaterialNumber(kingDeeMaterial.getNumber());
            policyCustomerLimit.setMaterialName(kingDeeMaterial.getName());
            policyCustomerLimit.setSpecification(kingDeeMaterial.getSpecification());
            policyCustomerLimit.setPolicyId(policyId);
            policyCustomerLimit.setLimitQty(Integer.parseInt(limitQty));
//            policyCustomerLimit.setMinBuyNum(Integer.parseInt(minBuyNum));
//            policyCustomerLimit.setMaxBuyNum(Integer.parseInt(maxBuyNum));
            list.add(policyCustomerLimit);
        }
        if(set.size() != objects.size()){
            throw new RemoteServiceException("检测到导入的数据存在重复的经销商编码和物料编码,去重前数量"+objects.size()+",去重后数量"+set.size());
        }

        policyCustomerLimitService.lambdaUpdate()
                .eq(PolicyCustomerLimit::getPolicyId,policyId).remove();
        policyCustomerLimitService.saveBatch(list);
    }

    /**
     * 经销商购买上限保存
     * @param bean
     */
    @Transactional
    public void saveLimit(PolicyLimitBean bean){
        //List<PolicyCustomerLimit> list = new ArrayList<>();
        KingDeeCustomer customer = kingDeeCustomerService.getById(bean.getCustomerId());
        KingDeeMaterial material = kingDeeMaterialService.getById(bean.getMaterialId());
        PolicyCustomerLimit policyCustomerLimit = new PolicyCustomerLimit();
        policyCustomerLimit.setSpecification(material.getSpecification());
        policyCustomerLimit.setPolicyId(bean.getPolicyId());
        policyCustomerLimit.setMaterialId(material.getId());
        policyCustomerLimit.setMaterialNumber(material.getNumber());
        policyCustomerLimit.setMaterialName(material.getName());
        policyCustomerLimit.setCustomerNumber(customer.getNumber());
        policyCustomerLimit.setCustomerName(customer.getName());
        policyCustomerLimit.setCustomerId(customer.getId());
        policyCustomerLimit.setLimitQty(bean.getLimitQty());
        if(StringUtils.isNotBlank(bean.getId())){
            policyCustomerLimit.setId(bean.getId());
            PolicyCustomerLimit old = policyCustomerLimitService.getById(bean.getId());
            String content = "";
            if(old != null && !old.getLimitQty().equals(bean.getLimitQty())){
                content = "修改前经销商【%s】购买上限"+old.getLimitQty()+",修改后经销商【%s】购买上限"+bean.getLimitQty();
            }
            content = String.format(content,old.getCustomerName(),old.getCustomerName());
            commonLogic.saveLog(old.getPolicyId(),"编辑",content);
        }
        policyCustomerLimitService.saveOrUpdate(policyCustomerLimit);
    }

    /**
     * 经销商购买上限-删除
     */
    public void deleteLimit(String id){
        policyCustomerLimitService.removeById(id);
    }

    /**
     * 经销商购买上限-详情
     * @param id
     * @return
     */
    public PolicyCustomerLimit detailLimit(String id){
        return policyCustomerLimitService.getById(id);
    }


    /**
     * 经销商购买上限列表
     */
    public IPage<PolicyCustomerLimitBean> limitList(String policyId,String keyword,String specification,Integer pageNum,Integer pageSize){
        Policy policy = policyService.getById(policyId);

        IPage page = policyCustomerLimitService.lambdaQuery()
                .eq(PolicyCustomerLimit::getPolicyId, policyId)
                .like(StringUtils.isNotBlank(specification),PolicyCustomerLimit::getSpecification,specification)
                .and(StringUtils.isNotEmpty(keyword),v -> v.like(PolicyCustomerLimit::getCustomerNumber, keyword).or().like(PolicyCustomerLimit::getCustomerName, keyword))
                .orderByDesc(PolicyCustomerLimit::getCreateTime, PolicyCustomerLimit::getId)
                .page(new Page<>(pageNum, pageSize));

        List<PolicyCustomerLimitBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            PolicyCustomerLimit policyCustomerLimit = (PolicyCustomerLimit)o;
            PolicyCustomerLimitBean bean = new PolicyCustomerLimitBean();
            BeanUtils.copyProperties(policyCustomerLimit,bean);

            //查询已审核的台数量
            Integer examineOrderNums = retailOrderCommonMapper.queryPolicyOrderNums(policyCustomerLimit.getCustomerId(),
                    policyCustomerLimit.getMaterialId(),policyCustomerLimit.getPolicyId(),ExamineStatusEnum.OK.getKey());
            //已下单台数
            Integer orderNums = retailOrderCommonMapper.queryPolicyOrderNums(policyCustomerLimit.getCustomerId(),
                    policyCustomerLimit.getMaterialId(),policyCustomerLimit.getPolicyId(),null);

            bean.setExamineOrderNums(examineOrderNums == null ? 0 : examineOrderNums);
            bean.setOrderNums(orderNums == null ? 0: orderNums);
            list.add(bean);
        }
        page.setRecords(list);

        return page;
    }


    /**
     * 经销商配提套数上限-保存
     */
    public void saveGroupLimit(PolicyGroupLimit groupLimit){
        groupLimit.insertOrUpdate();
    }
    /**
     * 经销商配提套数上限-详情
     */
    public PolicyGroupLimit detailGroupLimit(String id){
        return policyGroupLimitService.getById(id);
    }
    /**
     * 经销商配提套数上限-删除
     */
    public void deleteGroupLimit(String id){
        policyGroupLimitService.removeById(id);
    }


    /**
     * 导入经销商配提套数上限
     */
    public void importCustomerLimit2(String policyId,List<Object> objects){
        List<PolicyGroupLimit> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        List<Object> collect = objects.stream().distinct().collect(Collectors.toList());
        for(Object o : collect) {
            List<Object> row = (List<Object>) o;
            CommonUtils.initList2(row, 10);
            String customerNumber = (String) row.get(0);
            String groupLimitNum = (String)row.get(1);
            String minBuyNum = (String)row.get(2);
            String maxBuyNum = (String)row.get(3);
            set.add(customerNumber);

            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery()
                    .eq(KingDeeCustomer::getNumber, customerNumber).last("limit 1").one();

            if(StringUtils.isEmpty(customerNumber)){
                continue;
            }
            if(StringUtils.isEmpty(customerNumber) || StringUtils.isEmpty(groupLimitNum)){
                throw new RemoteServiceException("经销商编号/购买上限 不能为空");
            }
            PolicyGroupLimit policyGroupLimit = new PolicyGroupLimit();
            policyGroupLimit.setPolicyId(policyId);
            policyGroupLimit.setCustomerNumber(customerNumber);
            policyGroupLimit.setCustomerName(kingDeeCustomer.getName());
            policyGroupLimit.setCustomerId(kingDeeCustomer.getId());
            policyGroupLimit.setMinBuyNum(Integer.parseInt(minBuyNum));
            policyGroupLimit.setMaxBuyNum(Integer.parseInt(maxBuyNum));
            policyGroupLimit.setGroupLimitNum(Integer.parseInt(groupLimitNum));
            list.add(policyGroupLimit);
        }
        if(set.size() != objects.size()){
            throw new RemoteServiceException("检测到导入的数据存在重复的经销商编码,去重前数量"+objects.size()+",去重后数量"+set.size());
        }
        policyGroupLimitService.lambdaUpdate().eq(PolicyGroupLimit::getPolicyId,policyId).remove();
        policyGroupLimitService.saveBatch(list);
    }

    /**
     * 经销商配提套数-购买上限列表
     */
    public IPage<PolicyGroupLimitBean> limitGroupList(String policyId,String keyword,Integer pageNum,Integer pageSize){
        Policy policy = policyService.getById(policyId);
        IPage page = policyGroupLimitService.lambdaQuery()
                .eq(PolicyGroupLimit::getPolicyId, policyId)
                .and(StringUtils.isNotEmpty(keyword),v -> v.like(PolicyGroupLimit::getCustomerNumber, keyword).or().like(PolicyGroupLimit::getCustomerName, keyword))
                .orderByDesc(PolicyGroupLimit::getCreateTime, PolicyGroupLimit::getId)
                .page(new Page<>(pageNum, pageSize));

        List<PolicyGroupLimitBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            PolicyGroupLimit policyGroupLimit = (PolicyGroupLimit)o;
            PolicyGroupLimitBean bean = new PolicyGroupLimitBean();
            BeanUtils.copyProperties(policyGroupLimit,bean);

            //查询已审核的数量
            Integer examineOrderNums = retailOrderCommonMapper
                    .queryPolicyOrderNums(policyGroupLimit.getCustomerId(),null, policyGroupLimit.getPolicyId(),ExamineStatusEnum.OK.getKey());
            //已下单数
            Integer orderNums = retailOrderCommonMapper.queryPolicyOrderNums(policyGroupLimit.getCustomerId(),
                    null,policyGroupLimit.getPolicyId(),null);

            bean.setExamineOrderNums(examineOrderNums == null ? 0 : examineOrderNums);
            bean.setOrderNums(orderNums == null ? 0: orderNums);
            list.add(bean);
        }
        page.setRecords(list);

        return page;
    }

    /**
     * 批量修改配套套数上限
     * @param ids 上限列表ids
     * @param groupLimitNum
     */
    @Transactional
    public void batchGroupUpdateLimit(List<String> ids,Integer minBuyNum,Integer maxBuyNum, Integer groupLimitNum){
//        if(CollectionUtils.isEmpty(ids) || minBuyNum == null || maxBuyNum == null || groupLimitNum == null)
//            throw new RemoteServiceException("请满足提交参数");

        //经销商上限列表
        List<PolicyGroupLimit> list = policyGroupLimitService.lambdaQuery().in(PolicyGroupLimit::getId,ids).list();
        String policyId = list.get(0).getPolicyId();

        policyGroupLimitService.lambdaUpdate()
                .set(minBuyNum != null ,PolicyGroupLimit::getMinBuyNum,minBuyNum)
                .set(maxBuyNum != null,PolicyGroupLimit::getMaxBuyNum,maxBuyNum)
                .set(groupLimitNum != null,PolicyGroupLimit::getGroupLimitNum,groupLimitNum)
                .in(PolicyGroupLimit::getId,ids)
                .update();

        //记录操作日志
        for(PolicyGroupLimit bean : list) {
            String content = "";
            if(minBuyNum != null && !bean.getMinBuyNum().equals(minBuyNum)) {
                content = "修改前经销商【%s】起提数"+bean.getMinBuyNum()+",修改后经销商【%s】起提数"+minBuyNum;
            }else if(maxBuyNum != null && !bean.getMaxBuyNum().equals(maxBuyNum)){
                content = "修改前经销商【%s】最大提货数"+bean.getMinBuyNum()+",修改后经销商【%s】最大提货数"+maxBuyNum;
            }else if(groupLimitNum != null && !bean.getGroupLimitNum().equals(groupLimitNum)){
                content = "修改前经销商【%s】可配提套数上限"+bean.getGroupLimitNum()+",修改后经销商【%s】可配提套数上限"+groupLimitNum;
            }
            content = String.format(content,bean.getCustomerName(),bean.getCustomerName());
            commonLogic.saveLog(policyId,"编辑",content);
        }
    }



    /**
     * 批量延期政策
     * @param list
     */
    @Transactional
    public void batchUpdateDelay(List<PolicyDelayBean> list){
        if(CollectionUtils.isEmpty(list)){
            throw new RemoteServiceException("请传参");
        }
        //需要变更的信息，转换成map方便对比修改数据
        Map<String, Date> map = list.stream().collect(Collectors.toMap(PolicyDelayBean::getPolicyId, PolicyDelayBean::getEndTime));

        List<String> policyIds = list.stream().map(PolicyDelayBean::getPolicyId).collect(Collectors.toList());
        List<Policy> policyList = policyService.lambdaQuery().in(Policy::getId, policyIds).list();
        for(Policy policy : policyList){
            Date endTime = map.get(policy.getId());
            if(policy.getEndTime().getTime() != endTime.getTime()){
                //需要修改日志
                String content = "修改前政策结束时间"+DateUtil.formatDateTime(policy.getEndTime())+",修改后政策结束时间"+DateUtil.formatDateTime(endTime);
                //记录操作日志
                commonLogic.saveLog(policy.getId(), "修改", content);
            }

            policy.setEndTime(map.get(policy.getId()));
            policy.setStatus(endTime.getTime() > new Date().getTime() && policy.getStartTime().getTime() < new Date().getTime());
            policy.updateById();
        }
    }

    /**
     * 批量替换政策机型
     * @param policyIds
     * @param oldMaterialId
     * @param newMaterialId
     */
    @Transactional
    public void batchUpdateMaterial(List<String> policyIds,String oldMaterialId,String newMaterialId){
        List<Policy> list = policyService.lambdaQuery().in(Policy::getId, policyIds).list();
        KingDeeMaterial oldMaterial = kingDeeMaterialService.getById(oldMaterialId);
        KingDeeMaterial newMaterial = kingDeeMaterialService.getById(newMaterialId);
        if(oldMaterial == null || newMaterial == null)
            throw new RemoteServiceException("物料id错误，请联系相关人员");

        //修改机型
        policyMaterialService.lambdaUpdate()
                .set(PolicyMaterial::getMaterialId,newMaterialId)
                .set(PolicyMaterial::getMaterialNumber,newMaterial.getNumber())
                .set(PolicyMaterial::getMaterialName,newMaterial.getName())
                .set(PolicyMaterial::getSpecification,newMaterial.getSpecification())
                .set(PolicyMaterial::getK3CategoryId,newMaterial.getCategoryId())
                .set(PolicyMaterial::getK3CategoryNumber,newMaterial.getCategoryNumber())
                .set(PolicyMaterial::getK3CategoryName,newMaterial.getCategoryName())
                .in(PolicyMaterial::getPolicyId,policyIds)
                .eq(PolicyMaterial::getMaterialId,oldMaterialId)
                .update();

        //修改配提机型
        policyConditionMaterialService.lambdaUpdate()
                .set(PolicyConditionMaterial::getMaterialId,newMaterialId)
                .set(PolicyConditionMaterial::getMaterialNumber,newMaterial.getNumber())
                .set(PolicyConditionMaterial::getMaterialName,newMaterial.getName())
                .set(PolicyConditionMaterial::getSpecification,newMaterial.getSpecification())
                .set(PolicyConditionMaterial::getK3CategoryId,newMaterial.getCategoryId())
                .set(PolicyConditionMaterial::getK3CategoryNumber,newMaterial.getCategoryNumber())
                .set(PolicyConditionMaterial::getK3CategoryName,newMaterial.getCategoryName())
                .in(PolicyConditionMaterial::getPolicyId,policyIds)
                .eq(PolicyConditionMaterial::getMaterialId,oldMaterialId)
                .update();

        //判断新机型是否已存在
        List<PolicyCustomerLimit> list1 = policyCustomerLimitService.lambdaQuery()
                .eq(PolicyCustomerLimit::getMaterialId, newMaterialId)
                .in(PolicyCustomerLimit::getPolicyId, policyIds)
                .list();
        if(list1.size() > 0){
            List<String> pids = list1.stream().map(PolicyCustomerLimit::getPolicyId).collect(Collectors.toList());
            String join = StringUtils.join(pids, ",");
            throw new RemoteServiceException("操作失败,机型规格【"+newMaterial.getSpecification()+"】已存在以下政策中:"+join);
        }

        //修改上限机型
        policyCustomerLimitService.lambdaUpdate()
                .set(PolicyCustomerLimit::getMaterialId,newMaterialId)
                .set(PolicyCustomerLimit::getMaterialNumber,newMaterial.getNumber())
                .set(PolicyCustomerLimit::getMaterialName,newMaterial.getName())
                .in(PolicyCustomerLimit::getPolicyId,policyIds)
                .eq(PolicyCustomerLimit::getMaterialId,oldMaterialId)
                .update();

        //记录操作日志
        List<OperatorLog> operatorLogs = new ArrayList<>();
        for(Policy bean : list) {
            String content = "修改前型号:"+oldMaterial.getSpecification()+",修改后机型型号:"+newMaterial.getSpecification();
            OperatorLog operatorLog = commonLogic.supplyLog(bean.getId(), "批量修改机型", content);
            operatorLogs.add(operatorLog);
        }
        commonLogic.saveLog(operatorLogs);
    }

    /**
     * 批量作废机型
     * @param policyIds
     * @param materialIds
     */
    @Transactional
    public void batchMaterialCancel(List<String> policyIds,List<String> materialIds){
        policyMaterialService.lambdaUpdate()
                .set(PolicyMaterial::getStatus,false)
                .in(PolicyMaterial::getMaterialId,materialIds)
                .in(PolicyMaterial::getPolicyId,policyIds)
                .update();

        policyConditionMaterialService.lambdaUpdate()
                .set(PolicyConditionMaterial::getStatus,false)
                .in(PolicyConditionMaterial::getMaterialId,materialIds)
                .in(PolicyConditionMaterial::getPolicyId,policyIds)
                .update();
    }


    /**
     * 批量修改最小起提数/最大可提数..
     * @param ids 上限列表ids
     * @param limitQty
     */
    @Transactional
    public void batchUpdateLimit(List<String> ids,Integer limitQty){
        if(limitQty == null)
            throw new RemoteServiceException("请传参至少1个相关数量配置");

        //经销商上限列表
        List<PolicyCustomerLimit> list = policyCustomerLimitService.lambdaQuery().in(PolicyCustomerLimit::getId,ids).list();
        String policyId = list.get(0).getPolicyId();

        policyCustomerLimitService.lambdaUpdate()
//                .set(minBuyNum != null ,PolicyCustomerLimit::getMinBuyNum,minBuyNum)
//                .set(maxBuyNum != null,PolicyCustomerLimit::getMaxBuyNum,maxBuyNum)
                .set(limitQty != null,PolicyCustomerLimit::getLimitQty,limitQty)
                .in(PolicyCustomerLimit::getId,ids)
                .update();

        //记录操作日志
        for(PolicyCustomerLimit bean : list) {
            String content = "";
            if(limitQty != null && !bean.getLimitQty().equals(limitQty)){
                content = "修改前经销商【%s】购买上限"+bean.getLimitQty()+",修改后经销商【%s】购买上限"+limitQty;
            }
//            else if(popQty != null && !bean.getPopQty().equals(popQty)){
//                content = "修改前经销商【%s】可配提套数"+bean.getPopQty()+",修改后经销商【%s】可配提套数"+popQty;
//            }
            content = String.format(content,bean.getCustomerName(),bean.getCustomerName());
            commonLogic.saveLog(policyId,"编辑",content);
        }
    }


    /**
     * 导出销售政策
     */
    public ExcelData exportData(List<Policy> list){
        String[] titles = new String[]{"状态","销售政策编号","销售政策说明","表头备注","生效日期","结束日期","制表人","制表日期","审核人","审核日期"};
        List<List<Object>> rows = new ArrayList<>();
        for(Policy policy : list){
            List<Object> row = new ArrayList<>();
            row.add(policy.getStatus()?"已生效":"未生效");
            row.add(policy.getCode());
            row.add(policy.getRemark());
            row.add(policy.getTitle());
            row.add(DateUtil.formatDate(policy.getStartTime()));
            row.add(DateUtil.formatDate(policy.getEndTime()));
            row.add(policy.getCreateBy());
            row.add(DateUtil.formatDate(policy.getCreateTime()));
            row.add(policy.getExamineBy());
            row.add(DateUtil.formatDate(policy.getExamineTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }


    /**
     * 政策对应经销商导出
     */
    public ExcelData customerExport(List<PolicyBean> list){
        String[] titles = new String[]{"状态","销售政策编号","销售政策说明","表头备注","关联经销商",
                "生效日期","结束日期","制表人","制表日期"};
        List<List<Object>> rows = new ArrayList<>();
        for(Policy policy : list){
            List<Object> row = new ArrayList<>();
            row.add(policy.getStatus().equals("1") ? "已生效":"未生效");
            row.add(policy.getCode());
            row.add(policy.getTitle());
            row.add(policy.getRemark());
            row.add("");
            row.add(DateUtil.formatDate(policy.getStartTime()));
            row.add(DateUtil.formatDate(policy.getEndTime()));
            row.add(policy.getCreateBy());
            row.add(DateUtil.formatDate(policy.getCreateTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }

    /**
     * 导出政策商品
     */
    public ExcelData exportMaterial(List<PolicyMaterialBean> list){
        String[] titles = new String[]{"政策编号","物料编码","货品名称","规格型号","销售类型编码","销售类型","单价","备注","格力折扣","支付钱包","返利类型","原供价","价格类型","状态"};
        List<List<Object>> rows = new ArrayList<>();
        for(PolicyMaterialBean bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getPolicyId());
            row.add(bean.getMaterialNumber());
            row.add(bean.getMaterialName());
            row.add(bean.getSpecification());
            row.add(bean.getSaleTypeCode());
            row.add(bean.getSaleTypeName());
            row.add(bean.getPrice());
            row.add(bean.getRemark());
            row.add(bean.getDiscAmount());
            String rebateWallets = "";
            List<PolicyWalletRela> rebateWalletLists = bean.getWalletRelaList().stream().filter(v -> v.getType().equals(WalletTypeEnum.REBATE.getKey())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(rebateWalletLists)){
                List<String> rebateNames = rebateWalletLists.stream().map(PolicyWalletRela::getWalletName).collect(Collectors.toList());
                rebateWallets = StringUtils.join(rebateNames,",");
            }

            String wallets = "";
            List<PolicyWalletRela> walletRelas = bean.getWalletRelaList().stream().filter(v -> v.getType().equals(WalletTypeEnum.COMMONLY.getKey())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(walletRelas)){
                List<String> walletNames = walletRelas.stream().map(PolicyWalletRela::getWalletName).collect(Collectors.toList());
                wallets = StringUtils.join(walletNames,",");
            }
            row.add(wallets);
            row.add(rebateWallets);
            row.add(bean.getOrgPrice());
            row.add(bean.getPriceType());
            row.add(bean.getStatus()?"启用":"作废");
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }

    /**
     * 导出经销商
     */
    public ExcelData exportCustomer(List<PolicyCustomer> list){
        String[] titles = new String[]{"政策编号","经销商编号","经销商名称"};
        List<List<Object>> rows = new ArrayList<>();
        for(PolicyCustomer bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getPolicyId());
            row.add(bean.getCustomerNumber());
            row.add(bean.getCustomerName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }


    /**
     * 导出经销商上限
     */
    public ExcelData exportLimit(List<PolicyCustomerLimitBean> list){
        String[] titles = new String[]{"经销商编号","经销商名称","物料编号","物料名称","机型","已下订单台数","已审订单台数","购买数量上限"};
        List<List<Object>> rows = new ArrayList<>();
        for(PolicyCustomerLimitBean bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getCustomerNumber());
            row.add(bean.getCustomerName());
            row.add(bean.getMaterialNumber());
            row.add(bean.getMaterialName());
            row.add(bean.getSpecification());
            row.add(bean.getOrderNums());
            row.add(bean.getExamineOrderNums());
            row.add(bean.getLimitQty());
            //row.add(bean.getPopQty());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }

    /**
     * 导出经销商配提套数上限
     */
    public ExcelData exportGroupLimit(List<PolicyGroupLimitBean> list){
        String[] titles = new String[]{"经销商编号","经销商名称","配提套数上限","最小起提数量","最大提货数量","已下订单数","已审订单数"};
        List<List<Object>> rows = new ArrayList<>();
        for(PolicyGroupLimitBean bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getCustomerNumber());
            row.add(bean.getCustomerName());
            row.add(bean.getGroupLimitNum());
            row.add(bean.getMinBuyNum());
            row.add(bean.getMaxBuyNum());
            row.add(bean.getOrderNums());
            row.add(bean.getExamineOrderNums());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }


}
