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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import com.aliyuncs.utils.StringUtils;
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.ReceivableOrderBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.listV2.RebateOrderVO;
import com.zfire.mall.manager.bean.listV2.dto.ExamineZfireParamBean;
import com.zfire.mall.manager.bean.rebateorder.RebateOrderItemBean;
import com.zfire.mall.manager.bean.wallet.*;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.customer.CustomerProductTypeLogic;
import com.zfire.mall.manager.plus.entity.AdminUser;
import com.zfire.mall.manager.plus.entity.CustomerWalletTransfer;
import com.zfire.mall.manager.plus.entity.RebateOrder;
import com.zfire.mall.manager.plus.entity.RebateOrderItem;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.RedisUtil;
import com.zfire.mall.manager.zfire.bean.QueryParamBean;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RebateOrderLogic {

    @Autowired
    private RebateOrderService rebateOrderService;
    @Autowired
    RebateOrderItemService rebateOrderItemService;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    CustomerProductTypeLogic customerProductTypeLogic;
    @Autowired
    KingDeeCustomerService kingDeeCustomerService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    WalletRebateService walletRebateService;
    @Autowired
    CustomerWalletRecordService customerWalletRecordService;
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    CommonCMapper commonCMapper;


    /**
     * 列表v2
     */
    public IPage<RebateOrderVO> listV2(ExamineZfireParamBean zfireParamBean){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getCustomerId();
        String examineStatus = zfireParamBean.getExamineStatus();

        //GZ=广州  FS=佛山  ""=所有
        String websitNumber = adminUser.getAdminWebsit().getWebsitNumber();


        for(QueryParamBean bean : zfireParamBean.getParams()){
            if(bean.getParam().equals("a.examineStatus") && StringUtils.isEmpty(examineStatus)){
                String value = (String)bean.getValue();
                examineStatus = value;
            }
        }

        Boolean isConfirm = null;
        if(examineStatus != null && ExamineStatusEnum.OK_ONE_AND_CONFIRM.toString().equals(examineStatus)){
            examineStatus = ExamineStatusEnum.OK_ONE.toString();
            isConfirm = true;
        }

        ZfireParamBean zfireParamBean1 = FieldUtils.supplyParam(zfireParamBean);
        IPage<RebateOrderVO> page = commonCMapper
                .queryRebateOrder(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                        zfireParamBean1, examineStatus,customerId,isConfirm,websitNumber);
        return page;
    }


    /**
     * 列表
     * @param id
     * @param customerNumber
     * @param customerName
     * @param walletName
     * @param isConfirm
     * @param startTime
     * @param endTime
     * @param isSecondExamine
     * @param examineStatus
     * @param createBy
     * @param examineBy
     * @param remark1
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<RebateOrderItem> list(String id,String customerNumber,String customerName,String walletName,Boolean isConfirm,
                                       String startTime,String endTime,Boolean isSecondExamine, String examineStatus,
                                       String createBy,String examineBy,String remark1,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if(examineStatus != null && ExamineStatusEnum.OK_ONE_AND_CONFIRM.toString().equals(examineStatus)){
            examineStatus = ExamineStatusEnum.OK_ONE.toString();
            isConfirm = true;
        }

        IPage<RebateOrderItem> page = rebateOrderItemService.lambdaQuery()
                    .like(StringUtils.isNotEmpty(id),RebateOrderItem::getRebateOrderId,id)
                    .like(StringUtils.isNotEmpty(customerNumber), RebateOrderItem::getCustomerNumber, customerNumber)
                    .like(StringUtils.isNotEmpty(customerName), RebateOrderItem::getCustomerName, customerName)
                    .like(StringUtils.isNotEmpty(walletName), RebateOrderItem::getWalletName, walletName)
                    .like(StringUtils.isNotEmpty(remark1),RebateOrderItem::getRemark1,remark1)
                    .like(StringUtils.isNotEmpty(createBy),RebateOrderItem::getCreateBy,createBy)
                    .like(StringUtils.isNotEmpty(examineBy),RebateOrderItem::getExamineBy,examineBy)
                    .eq(isConfirm != null,RebateOrderItem::getCustomerIsConfirm,isConfirm)
                    .between(StringUtils.isNotEmpty(startTime) &&
                            StringUtils.isNotEmpty(endTime), RebateOrderItem::getTheTime, startTime, endTime)
                    .notIn(adminUser.getIsCustomer(),RebateOrderItem::getExamineStatus,Arrays.asList(ExamineStatusEnum.SAVE.toString(),ExamineStatusEnum.WAIT.toString()))
                    .eq(adminUser.getIsCustomer(),RebateOrderItem::getCustomerId,adminUser.getCustomerId())
                    .eq(isSecondExamine != null && isSecondExamine,RebateOrderItem::getExamineStatus,ExamineStatusEnum.OK)
                    .eq(isSecondExamine != null && !isSecondExamine,RebateOrderItem::getExamineStatus,ExamineStatusEnum.OK_ONE)
                    .eq(StringUtils.isNotEmpty(examineStatus),RebateOrderItem::getExamineStatus,examineStatus)
                    .eq(adminUser.getIsCustomer() ,RebateOrderItem::getWithholdAmount,0)
                    .orderByDesc(RebateOrderItem::getCreateTime).page(new Page<>(pageNum, pageSize));
        return page;
    }

    @Transactional
    public void add(RebateOrderBean rebateOrderBean){

        AdminUserCom adminUser = commonLogic.getAdminUser();

        rebateOrderBean.setServiceId(adminUser.getAdminUserId());
        rebateOrderBean.setServiceName(adminUser.getNickName());
        rebateOrderBean.setTheTime(new Date());
        rebateOrderBean.insert();

        List<RebateOrderItem> items = rebateOrderBean.getItems();
        for(RebateOrderItem orderItem:items){
            if(orderItem.getWithholdAmount() != null && orderItem.getWithholdAmount().doubleValue() != 0) {
                BigDecimal sum = orderItem.getAmount().add(orderItem.getWithholdAmount());
                if (sum.doubleValue() != 0) {
                    throw new RemoteServiceException("返利总金额与暂扣返利未按规则填写");
                }
            }
            orderItem.setServiceId(rebateOrderBean.getServiceId());
            orderItem.setServiceName(rebateOrderBean.getServiceName());
            orderItem.setRebateOrderId(rebateOrderBean.getId());
            orderItem.setExamineStatus(ExamineStatusEnum.SAVE.toString());
            orderItem.setTheTime(rebateOrderBean.getTheTime());
        }
        rebateOrderItemService.saveBatch(items);
    }


    public void update(RebateOrderBean rebateOrderBean){
        RebateOrder rebateOrder = rebateOrderService.getById(rebateOrderBean.getId());

        //保存随便改
        if(rebateOrder.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString())){

                /*       //未复核之前商家可以修改
            if (!rebateOrder.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString())) {
                //非保存状态 ，只可修改备注
                RebateOrder rebateOrder2 = new RebateOrder();
                rebateOrder2.setId(rebateOrderBean.getId());
                rebateOrder2.setRemark(rebateOrderBean.getRemark());
                rebateOrder.setTheTime(rebateOrderBean.getTheTime());
                rebateOrder2.updateById();
                return;
            }*/
            for (RebateOrderItem rebateOrderItem : rebateOrderBean.getItems()) {
                CustomerWallet customerWallet = customerWalletService.getById(rebateOrderItem.getCustomerWalletId());
                if (customerWallet != null) {
                    rebateOrderItem.setWalletName(customerWallet.getCustomerWalletName());
                }
            }

            rebateOrder.updateById();
            rebateOrderItemService.updateBatchById(rebateOrderBean.getItems());

            return;
            //非保存只能改限制字段
        }else {

            RebateOrder rebateOrder2 = new RebateOrder();
            rebateOrder2.setId(rebateOrderBean.getId());
            rebateOrder2.setRemark(rebateOrderBean.getRemark());
            List<RebateOrderItem> rebateOrderItems = new ArrayList<>();
            for (RebateOrderItem item : rebateOrderBean.getItems()) {
                RebateOrderItem rebateOrderItem = rebateOrderItemService.getById(item.getId());
                rebateOrderItem.setPolicyFileNo(item.getPolicyFileNo());
                rebateOrderItem.setPolicyDocNo(item.getPolicyDocNo());
                rebateOrderItem.setPolicyMonth(item.getPolicyMonth());
                rebateOrderItem.setPolicyOrg(item.getPolicyOrg());
                rebateOrderItem.setPolicyYear(item.getPolicyYear());
                rebateOrderItem.setCustomerArea(item.getCustomerArea());
                rebateOrderItem.setCustomerAttr(item.getCustomerAttr());
                rebateOrderItem.setRewardActualCustomers(item.getRewardActualCustomers());
                rebateOrderItem.setRemark1(item.getRemark1());
                rebateOrderItem.setRemark2(item.getRemark2());
                rebateOrderItems.add(rebateOrderItem);
            }
            rebateOrder2.updateById();
            rebateOrderItemService.updateBatchById(rebateOrderItems);
        }
    }

    @Transactional
    public void batchDel(List<String> ids){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if(adminUser.getIsCustomer()){
            throw new RemoteServiceException("经销商无权删除。");
        }
        //查询
        List<RebateOrder> rebateOrders = rebateOrderService.lambdaQuery().eq(RebateOrder::getExamineStatus,ExamineStatusEnum.SAVE).in(RebateOrder::getId,ids).list();
        if(null != rebateOrders && rebateOrders.size() >0){
            List<String> delIds = rebateOrders.stream().map(RebateOrder::getId).collect(Collectors.toList());
            rebateOrderService.lambdaUpdate().in(RebateOrder::getId,delIds).remove();
            rebateOrderItemService.lambdaUpdate().in(RebateOrderItem::getRebateOrderId,delIds).remove();
        }

    }


    public RebateOrderBean detail(String id,Boolean isConfirm){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        RebateOrder rebateOrder = rebateOrderService.getById(id);
        RebateOrderBean bean = new RebateOrderBean();
        BeanUtils.copyProperties(rebateOrder,bean);
        List<RebateOrderItem> list = rebateOrderItemService.lambdaQuery()
                .eq(RebateOrderItem::getRebateOrderId, id)
                .eq(adminUser.getIsCustomer(),RebateOrderItem::getCustomerId,adminUser.getCustomerId())
                .eq(isConfirm != null,RebateOrderItem::getCustomerIsConfirm,isConfirm)
                .list();
        bean.setItems(list);
        return bean;
    }


    /**
     * 提审
     * @param id
     */
    @Transactional
    public void apply(String id){
        RebateOrder rebateOrder = rebateOrderService.getById(id);
        if(!rebateOrder.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString())){
            throw new RemoteServiceException("不可提审");
        }
        rebateOrder.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        rebateOrder.updateById();

        rebateOrderItemService.lambdaUpdate()
                .set(RebateOrderItem::getExamineStatus,ExamineStatusEnum.WAIT.toString())
                .eq(RebateOrderItem::getRebateOrderId,id)
                .update();
    }

    /**
     * 批量提审
     * @param ids
     */
    @Transactional
    public void batchApply(List<String> ids){
        Integer count = rebateOrderService.lambdaQuery().in(RebateOrder::getId,ids).ne(RebateOrder::getExamineStatus,ExamineStatusEnum.SAVE.toString()).count();
        if(count > 0){
            throw new RemoteServiceException("存在非保存状态数据,不可提审");
        }
        //修改主表
        rebateOrderService.lambdaUpdate()
                        .set(RebateOrder::getExamineStatus,ExamineStatusEnum.WAIT.toString())
                        .in(RebateOrder::getId,ids).eq(RebateOrder::getExamineStatus,ExamineStatusEnum.SAVE.toString()).update();
        //修改名细表
        rebateOrderItemService.lambdaUpdate()
                .set(RebateOrderItem::getExamineStatus,ExamineStatusEnum.WAIT.toString())
                .in(RebateOrderItem::getRebateOrderId,ids)
                .eq(RebateOrderItem::getExamineStatus,ExamineStatusEnum.SAVE.toString())
                .update();
    }

    /**
     * 审核
     */
    @Transactional
    public void examine(String id,String examineStatus,String examineRemark) throws InterruptedException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        RebateOrder rebateOrder  = rebateOrderService.getById(id);
        if(rebateOrder == null){
            throw new RemoteServiceException("审核失败");
        }
        if(!rebateOrder.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())){
            throw new RemoteServiceException("非待审批状态不可审批");
        }

        //判断整单中是否有填暂扣返利 , 有的话必须全部是全部填了暂扣返利
        List<RebateOrderItem> rebateOrderItems = rebateOrderItemService.lambdaQuery()
                .eq(RebateOrderItem::getRebateOrderId, rebateOrder.getId()).list();
        Boolean hasWithhold = false;
        if(null != rebateOrderItems && rebateOrderItems.size() >0){
            int i = 0;
            for(RebateOrderItem rebateOrderItem:rebateOrderItems){
                // 判断是否填了暂扣返利
                if(!(rebateOrderItem.getWithholdAmount().compareTo(BigDecimal.ZERO) == 0)){
                    hasWithhold = true;
                    i = i + 1;
                }
            }

            if(hasWithhold && i !=  rebateOrderItems.size()){
                throw new RemoteServiceException("填了暂扣返利的单,必须整单都填。");
            }
        }

        examineStatus = examineStatus.equals(ExamineStatusEnum.OK.toString())?ExamineStatusEnum.OK_ONE.toString():ExamineStatusEnum.FAIL_ONE.toString();
        if(hasWithhold && ExamineStatusEnum.OK_ONE.toString().equals(examineStatus)){
            examineStatus =  ExamineStatusEnum.OK.toString();
        }
        rebateOrder.setExamineStatus(examineStatus);
        rebateOrder.setExamineBy(adminUser.getNickName());
        rebateOrder.setExamineTime(new Date());
        rebateOrder.setExamineRemark(examineRemark);

        rebateOrderItemService.lambdaUpdate()
                .set(RebateOrderItem::getExamineStatus,rebateOrder.getExamineStatus())
                .set(RebateOrderItem::getExamineBy,rebateOrder.getExamineBy())
                .set(RebateOrderItem::getExamineTime,rebateOrder.getExamineTime())
                .set(RebateOrderItem::getExamineRemark,rebateOrder.getExamineRemark())
                .eq(RebateOrderItem::getRebateOrderId,id)
                .update();
        rebateOrder.updateById();

        List<CustomerWalletAmountBean> beans = new ArrayList<>();
        for(RebateOrderItem rebateOrderItem:rebateOrderItems){

            BigDecimal opAmount = rebateOrderItem.getRebateAmount() != null ? rebateOrderItem.getRebateAmount() : rebateOrderItem.getAmount();
            if(hasWithhold && ExamineStatusEnum.WAIT.toString().equals(rebateOrderItem.getExamineStatus())
                && ExamineStatusEnum.OK.toString().equals(examineStatus)){
                if(opAmount.doubleValue() < 0){
                    //负负得正
                    BigDecimal amount = BigDecimal.valueOf(0).subtract(opAmount);
                    beans.add(new CustomerWalletAmountBean(rebateOrderItem.getCustomerWalletId(),amount,rebateOrderItem.getRemark1(),Constant.BILLTYPE_FLD_ZR,rebateOrderItem.getTheTime(),rebateOrderItem.getRebateOrderId(),0, rebateOrderItem.getAllowanceAmount(), rebateOrderItem.getWithholdAmount(),null,"sub"));
                } else {
                    //需要处理的金额
                    beans.add(new CustomerWalletAmountBean(rebateOrderItem.getCustomerWalletId(), opAmount, rebateOrderItem.getRemark1(), "返利单", rebateOrderItem.getTheTime(), rebateOrderItem.getRebateOrderId(), 0, rebateOrderItem.getAllowanceAmount(), rebateOrderItem.getWithholdAmount(),null,"add"));
                }
            }
        }
        walletLogic.doWalletAmount(beans);

        // 没有暂扣返利就通知
        if(!hasWithhold){
            for(RebateOrderItem rebateOrderItem:rebateOrderItems) {
                String key = Constant.RedisPrefix.REBATE_NOTICE + Constant.REDIS_ROLE_DEALERS + rebateOrderItem.getCustomerId();
                String message = redisUtil.get(key) == null ? "您有新的返利单，请及时确认！" : redisUtil.get(key) + "^您有新的返利单，请及时确认";
                redisUtil.set(key, message, 30 * 60);
            }
        }
    }



    /**
     * 取消审核
     * @param id
     */
    @Transactional
    public void cancel(String id,String cancelRemark){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        RebateOrder rebateOrder  = rebateOrderService.getById(id);
        if(rebateOrder == null){
            throw new RemoteServiceException("取消审核失败");
        }
        if(!rebateOrder.getExamineStatus().equals(ExamineStatusEnum.OK_ONE.toString())){
            throw new RemoteServiceException("初审通过状态下才可取消审核");
        }

        rebateOrder.setExamineStatus(ExamineStatusEnum.SAVE.toString());
        rebateOrder.setCancelBy(adminUser.getNickName());
        rebateOrder.setCancelTime(new Date());
        rebateOrder.setCancelRemark(cancelRemark);

        rebateOrderItemService.lambdaUpdate()
                .set(RebateOrderItem::getExamineStatus,rebateOrder.getExamineStatus())
                .set(RebateOrderItem::getCancelBy,rebateOrder.getCancelBy())
                .set(RebateOrderItem::getCancelTime,rebateOrder.getCancelTime())
                .set(RebateOrderItem::getCancelRemark,rebateOrder.getCancelRemark())
                .eq(RebateOrderItem::getRebateOrderId,id)
                .update();
        rebateOrder.updateById();

    }


    /**
     * 审核
     */
    @Transactional
    public void examine2(RebateOrderItemBean rebateOrderItemBean) throws InterruptedException {
      AdminUserCom adminUser = commonLogic.getAdminUser();
//        if(!adminUser.getIsCw() && adminUser.getType() == 0){
//            throw new RemoteServiceException("权限不足，无法复审");
//        }
        RebateOrder rebateOrder = rebateOrderService.getById(rebateOrderItemBean.getId());
        List<RebateOrderItem> items = rebateOrderItemBean.getItems();
        List<String> rebateOrderItemIds = new ArrayList<>();
        for(RebateOrderItem item:items){
            rebateOrderItemIds.add(item.getId());
        }

        Integer count = rebateOrderItemService.lambdaQuery()
                .eq(RebateOrderItem::getRebateOrderId, rebateOrderItemBean.getId())
                .in(CollectionUtils.isNotEmpty(rebateOrderItemIds),RebateOrderItem::getId,rebateOrderItemIds)
                .eq(RebateOrderItem::getCustomerIsConfirm, false)
                .eq(RebateOrderItem::getWithholdAmount,0)
                .count();
        if(count > 0 ){
            throw new RemoteServiceException("存在客户未确认,请等待");
        }

        //rebateOrder.setExamineStatus(rebateOrderItemBean.getExamineStatus());
        rebateOrder.setSecondExamineBy(adminUser.getNickName());
        rebateOrder.setSecondExamineRemark(rebateOrderItemBean.getExamineRemark());
        rebateOrder.setSecondExamineTime(new Date());
        rebateOrder.updateById();

        List<CustomerWalletAmountBean> beans = new ArrayList<>();
        for(RebateOrderItem item:items){
            //不信任前端其他数据，通过id查询现在保存的数据
            RebateOrderItem roiData = rebateOrderItemService.getById(item.getId());
            item.setExamineStatus(rebateOrderItemBean.getExamineStatus());
            item.setSecondExamineBy(rebateOrder.getSecondExamineBy());
            item.setSecondExamineTime(rebateOrder.getSecondExamineTime());
            item.setSecondExamineRemark(rebateOrder.getSecondExamineRemark());

            if(item.getAllowanceAmount().doubleValue() < 0){
                throw new RemoteServiceException("折让金额不可小于0");
            }
            //当前状态为初审通过 且审核通过才扣钱
            BigDecimal opAmount = roiData.getRebateAmount() != null ? roiData.getRebateAmount() : roiData.getAmount();

            if (ExamineStatusEnum.OK_ONE.toString().equals(roiData.getExamineStatus()) || ExamineStatusEnum.FAIL.toString().equals(roiData.getExamineStatus())) {
                //审核通过
                if (ExamineStatusEnum.OK.toString().equals(rebateOrderItemBean.getExamineStatus())) {
                    if (opAmount.doubleValue() < 0) {
                        //负负得正
                        BigDecimal amount = BigDecimal.valueOf(0).subtract(opAmount);
                        beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(), amount, item.getRemark1(), Constant.BILLTYPE_FLD_ZR, roiData.getTheTime(), roiData.getRebateOrderId(), 0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(), null, "sub"));
                    } else {
                        //需要处理的金额
                        beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(), opAmount, item.getRemark1(), "返利单", roiData.getTheTime(), roiData.getRebateOrderId(), 0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(), null, "add"));
                    }
                }
            }

            //复核完取消复核 （如果已钱包余额已经变动,将钱回滚）
            if(ExamineStatusEnum.OK.toString().equals(roiData.getExamineStatus()) && ExamineStatusEnum.FAIL.toString().equals(rebateOrderItemBean.getExamineStatus())){
                //如果是取消复核 将客户确认改为未确认
                item.setCustomerIsConfirm(false);
                if(opAmount.doubleValue() < 0){
                    BigDecimal amount = BigDecimal.valueOf(0).subtract(opAmount);
                    beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(), amount, item.getRemark1(), "返利单", roiData.getTheTime(), roiData.getRebateOrderId(), 0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(),null,"add"));
                } else {
                    beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(),opAmount,item.getRemark1(),Constant.BILLTYPE_FLD_ZR,roiData.getTheTime(),roiData.getRebateOrderId(),0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(),null,"sub"));
                }
            }
        }
        rebateOrderItemService.updateBatchById(items);
        //操作钱包
        walletLogic.doWalletAmount(beans);
        //通知商家
        noticeCustomer(items,rebateOrderItemBean.getExamineStatus());
    }


    public void noticeCustomer(List<RebateOrderItem> items,String examineStatus){
        for(RebateOrderItem item:items) {
            if(ExamineStatusEnum.OK.toString().equals(examineStatus)){
                String key = Constant.RedisPrefix.REBATE_NOTICE + Constant.REDIS_ROLE_DEALERS + item.getCustomerId();
                String message = redisUtil.get(key) == null ? "返利单已复核通过!" : redisUtil.get(key) + "^返利单已复核通过!";
                redisUtil.set(key, message, 30 * 60);
            }
        }
    }


    @Transactional
    public void batchExamine2(List<String> ids, String examineStatus, String remark) throws InterruptedException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //防止状态不对应
        examineStatus = examineStatus.equals(ExamineStatusEnum.OK.toString()) ? ExamineStatusEnum.OK.toString() : ExamineStatusEnum.FAIL.toString();

        for (String id : ids) {
            RebateOrder rebateOrder = rebateOrderService.getById(id);
            List<RebateOrderItem> items = rebateOrderItemService.lambdaQuery().eq(RebateOrderItem::getRebateOrderId,id).list();
            List<String> rebateOrderItemIds = new ArrayList<>();
            for(RebateOrderItem item:items){
                rebateOrderItemIds.add(item.getId());
            }

            Integer count = rebateOrderItemService.lambdaQuery()
                    .eq(RebateOrderItem::getRebateOrderId, id)
                    .in(CollectionUtils.isNotEmpty(rebateOrderItemIds),RebateOrderItem::getId,rebateOrderItemIds)
                    .eq(RebateOrderItem::getCustomerIsConfirm, false)
                    .eq(RebateOrderItem::getWithholdAmount,0)
                    .count();
            if(count > 0 ){
                throw new RemoteServiceException("存在客户未确认,请等待");
            }

            rebateOrder.setExamineStatus(examineStatus);
            rebateOrder.setSecondExamineBy(adminUser.getNickName());
            rebateOrder.setSecondExamineRemark(remark);
            rebateOrder.setSecondExamineTime(new Date());
            rebateOrder.updateById();

            List<CustomerWalletAmountBean> beans = new ArrayList<>();
            for(RebateOrderItem item:items){
                //不信任前端其他数据，通过id查询现在保存的数据
                RebateOrderItem roiData = rebateOrderItemService.getById(item.getId());
                item.setExamineStatus(examineStatus);
                item.setSecondExamineBy(rebateOrder.getSecondExamineBy());
                item.setSecondExamineTime(rebateOrder.getSecondExamineTime());
                item.setSecondExamineRemark(rebateOrder.getSecondExamineRemark());

                if(item.getAllowanceAmount().doubleValue() < 0){
                    throw new RemoteServiceException("折让金额不可小于0");
                }
                //当前状态为初审通过 且审核通过才扣钱
                BigDecimal opAmount = roiData.getRebateAmount() != null ? roiData.getRebateAmount() : roiData.getAmount();

                if (ExamineStatusEnum.OK_ONE.toString().equals(roiData.getExamineStatus())) {
                    //审核通过
                    if (ExamineStatusEnum.OK.toString().equals(examineStatus)) {
                        if (opAmount.doubleValue() < 0) {
                            //负负得正
                            BigDecimal amount = BigDecimal.valueOf(0).subtract(opAmount);
                            beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(), amount, item.getRemark1(), Constant.BILLTYPE_FLD_ZR, roiData.getTheTime(), roiData.getRebateOrderId(), 0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(), null, "sub"));
                        } else {
                            //需要处理的金额
                            beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(), opAmount, item.getRemark1(), "返利单", roiData.getTheTime(), roiData.getRebateOrderId(), 0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(), null, "add"));
                        }
                    }
                }

                //复核完取消复核 （如果已钱包余额已经变动,将钱回滚）
                if(ExamineStatusEnum.OK.toString().equals(roiData.getExamineStatus())
                        && ExamineStatusEnum.FAIL.toString().equals(examineStatus)){
                    item.setCustomerIsConfirm(false);
                    if(opAmount.doubleValue() < 0){
                        BigDecimal amount = BigDecimal.valueOf(0).subtract(opAmount);
                        beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(), amount, item.getRemark1(), "返利单", roiData.getTheTime(), roiData.getRebateOrderId(), 0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(),null,"add"));
                    } else {
                        beans.add(new CustomerWalletAmountBean(roiData.getCustomerWalletId(),opAmount,item.getRemark1(),Constant.BILLTYPE_FLD_ZR,roiData.getTheTime(),roiData.getRebateOrderId(),0, roiData.getAllowanceAmount(), roiData.getWithholdAmount(),null,"sub"));
                    }
                }
            }
            rebateOrderItemService.updateBatchById(items);
            walletLogic.doWalletAmount(beans);
            noticeCustomer(items,examineStatus);
        }

    }


    /**
     * 客户确认
     */
    public void ack(List<RebateOrderAck> list){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());

        for(RebateOrderAck rebateOrderAck : list) {
            String itemId = rebateOrderAck.getItemId();
            RebateOrderItem orderItem = rebateOrderItemService.getById(itemId);
            BigDecimal allowanceAmount = rebateOrderAck.getAllowanceAmount();
            BigDecimal rebateAmount = rebateOrderAck.getRebateAmount();

            if(allowanceAmount == null){
                allowanceAmount = BigDecimal.valueOf(0);
            }
            if(rebateAmount == null){
                rebateAmount =  BigDecimal.valueOf(0);
            }

            if(!kingDeeCustomer.getIsZr() && allowanceAmount.doubleValue() != 0){
                throw new RemoteServiceException("没有转折让钱包权限");
            }

            if (allowanceAmount.doubleValue() != 0 && orderItem.getAmount().doubleValue() < allowanceAmount.doubleValue()) {
                throw new RemoteServiceException("折让金额不能比返利金额大");
            }
            if(allowanceAmount.doubleValue() != 0 && allowanceAmount.doubleValue() < 0 ){
                throw new RemoteServiceException("折让金额不能能为负数");
            }

            if(allowanceAmount.add(rebateAmount).doubleValue() != orderItem.getAmount().doubleValue()){
                throw new RemoteServiceException("折让金额与返利金额相加不等于总返利金额");
            }

            //当负数返利时 不能存在折让金额
            if(orderItem.getAmount().doubleValue() < 0 && allowanceAmount.doubleValue() != 0){
                throw new RemoteServiceException("返利金额为负数时，不能存在折让金额");
            }

            //计算总返利金额
            BigDecimal amount = allowanceAmount.add(rebateAmount);

            orderItem.setId(itemId);
            orderItem.setAllowanceAmount(allowanceAmount);
            orderItem.setAmount(amount);
            orderItem.setRebateAmount(rebateAmount);
            orderItem.setCustomerIsConfirm(true);
            orderItem.setCustomerConfirmTime(new Date());
            orderItem.updateById();
        }

        String key = Constant.RedisPrefix.REBATE_NOTICE + Constant.REDIS_ROLE_BUSINESS;
        String message  =  redisUtil.get(key) == null ? "有返利单已确认，请及时复核！" : redisUtil.get(key) +"^有返利单已确认，请及时复核！";
        redisUtil.set(key, message, 30 * 60);
    }

    @Transactional
    public void ackUpdate(List<RebateOrderAck> list){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());

        for(RebateOrderAck rebateOrderAck : list) {
            String itemId = rebateOrderAck.getItemId();
            RebateOrderItem orderItem = rebateOrderItemService.getById(itemId);
            BigDecimal allowanceAmount = rebateOrderAck.getAllowanceAmount();
            BigDecimal rebateAmount = rebateOrderAck.getRebateAmount();

            if(allowanceAmount == null){
                allowanceAmount = BigDecimal.valueOf(0);
            }
            if(rebateAmount == null){
                rebateAmount =  BigDecimal.valueOf(0);
            }

            if(!kingDeeCustomer.getIsZr() && allowanceAmount.doubleValue() != 0){
                throw new RemoteServiceException("没有转折让钱包权限");
            }

            if (allowanceAmount.doubleValue() != 0 && orderItem.getAmount().doubleValue() < allowanceAmount.doubleValue()) {
                throw new RemoteServiceException("折让金额不能比返利金额大");
            }
            if(allowanceAmount.doubleValue() != 0 && allowanceAmount.doubleValue() < 0 ){
                throw new RemoteServiceException("折让金额不能能为负数");
            }

            if(allowanceAmount.add(rebateAmount).doubleValue() != orderItem.getAmount().doubleValue()){
                throw new RemoteServiceException("折让金额与返利金额相加不等于总返利金额");
            }
            //计算总返利金额
            BigDecimal amount = allowanceAmount.add(rebateAmount);

            orderItem.setId(itemId);
            orderItem.setAllowanceAmount(allowanceAmount);
            orderItem.setAmount(amount);
            orderItem.setRebateAmount(rebateAmount);
            orderItem.updateById();
        }

    }


    public void checkNeedAck(String customerWalletId){
        if(StringUtils.isEmpty(customerWalletId)){
            return;
        }
        //有负数录入 并且财务审核的也不能使用 //排除掉 填写了暂扣返利的单
        Integer count = rebateOrderItemService.lambdaQuery()
                .le(RebateOrderItem::getAmount, 0)
                .eq(RebateOrderItem::getCustomerIsConfirm,false)
                .eq(RebateOrderItem::getExamineStatus,ExamineStatusEnum.OK_ONE)
                .eq(RebateOrderItem::getCustomerWalletId, customerWalletId)
                .eq(RebateOrderItem::getWithholdAmount,0)
                .count();
        if(count > 0){
            throw new RemoteServiceException("您有红字返利单未确认或未复核，请先确认。如果已确认待格力复核后才可使用返利。");
        }
    }

    /**
     * 导入销售返利单数据
     */
    @Transactional
    public List<String> importRebateOrder(List<Object> rows) throws Exception{
        AdminUserCom adminUser = commonLogic.getAdminUser();
//        RebateOrderBean rebateOrderBean = new RebateOrderBean();
//        rebateOrderBean.setServiceId(adminUser.getAdminUserId());
//        rebateOrderBean.setServiceName(adminUser.getNickName());
//        rebateOrderBean.insert();
        String serviceId = adminUser.getAdminUserId();
        String serviceName = adminUser.getNickName();

        List<RebateOrderItem> rebateOrderItems = new ArrayList<>();
        List<RebateOrder> rebateOrders = new ArrayList<>();
        List<String> saveIds = new ArrayList<>();

        for(Object o : rows){
            String id = IdWorker.getIdStr();
            saveIds.add(id);
            List<Object> row = (List<Object>) o;
            String customerNumber = (String)row.get(0);
            String theTime = (String)row.get(1);
            String remark = (String)row.get(2);
           // String customerName = (String)row.get(3);
            String walletName = (String)row.get(4);
            String amount = (String) row.get(5);
            //暂扣返利
            String withholdAmount = (String) row.get(6);
            String policyFileNo = (String) row.get(7);
            String policyDocNo = (String) row.get(8);
            String policyYear = (String) row.get(9);
            String policyMonth = (String) row.get(10);
            String policyOrg = (String) row.get(11);
            String customerArea  = (String) row.get(12);
            String customerAttr  = (String) row.get(13);
            String rewardActualCustomers = (String) row.get(14);
            String remark1 = (String) row.get(15);
            String remark2 = (String) row.get(16);

            if(StringUtils.isEmpty(customerNumber) || StringUtils.isEmpty(walletName) ||StringUtils.isEmpty(amount)  ){
                throw new RemoteServiceException("经销商编码/返利类型/返利总金额不能为空");
            }

            if(withholdAmount != null && new BigDecimal(withholdAmount).doubleValue() != 0) {
                BigDecimal sum = new BigDecimal(amount).add(new BigDecimal(withholdAmount));
                if (sum.doubleValue() != 0) {
                    throw new RemoteServiceException("返利总金额与暂扣返利未按规则填写");
                }
            }
            //验证返利钱包是否存在

            //验证经销商数据是否存在
            List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerNumber).list();
            if(list.size() < 1){
                throw new RemoteServiceException("经销商编码：" + customerNumber + "，不存在");
            }
            String  customerId = list.get(0).getId();
            List<CustomerWalletBean> customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, "REBATE",false);
            RebateOrderItem rebateOrderItem = new RebateOrderItem();
            Boolean  walletExist = false;
            for(CustomerWalletBean customerWallet:customerWalletBeans){
                if(walletName.equals(customerWallet.getName())){
                    rebateOrderItem.setCustomerWalletId(customerWallet.getCustomerWalletId());
                    rebateOrderItem.setWalletName(customerWallet.getName());
                    walletExist = true;
                    continue;
                }
            }

            if(!walletExist){
                throw new RemoteServiceException("返利钱包：" + walletName + "，不存在");
            }
            rebateOrderItem.setId(id);
            rebateOrderItem.setCustomerNumber(customerNumber);
            rebateOrderItem.setCustomerId(customerId);
            rebateOrderItem.setCustomerName(list.get(0).getName());
            rebateOrderItem.setAmount(new BigDecimal(amount));
            if(null != withholdAmount){
                rebateOrderItem.setWithholdAmount(new BigDecimal(withholdAmount));
            }
            rebateOrderItem.setPolicyFileNo(policyFileNo);
            rebateOrderItem.setPolicyDocNo(policyDocNo);
            rebateOrderItem.setPolicyYear(policyYear);

            rebateOrderItem.setPolicyMonth(policyMonth);
            rebateOrderItem.setPolicyOrg(policyOrg);
            rebateOrderItem.setCustomerArea(customerArea);
            rebateOrderItem.setCustomerAttr(customerAttr);
            rebateOrderItem.setRewardActualCustomers(rewardActualCustomers);
            rebateOrderItem.setRemark1(remark1);
            rebateOrderItem.setRemark2(remark2);
            rebateOrderItem.setTheTime(new Date());
            //rebateOrderItem.setRemark(remark);
            rebateOrderItem.setServiceId(serviceId);
            rebateOrderItem.setServiceName(serviceName);
            rebateOrderItem.setRebateOrderId(id);
            rebateOrderItem.setExamineStatus(ExamineStatusEnum.SAVE.toString());
            rebateOrderItems.add(rebateOrderItem);

            RebateOrder rebateOrder = new RebateOrder();
            BeanUtils.copyProperties(rebateOrderItem,rebateOrder);
            rebateOrder.setRemark(remark);
            rebateOrders.add(rebateOrder);
        }
        rebateOrderItemService.saveBatch(rebateOrderItems);
        rebateOrderService.saveBatch(rebateOrders);
        return saveIds;
    }

//    /**
//     * 返回数据
//     * @param rows
//     * @return
//     * @throws Exception
//     */
//    public RebateOrderBean importRebateOrderData(List<Object> rows) throws Exception{
//        RebateOrderBean rebateOrderBean = new RebateOrderBean();
//        List<RebateOrderItem> rebateOrderItems = new ArrayList<>();
//        for(Object o : rows){
//            List<Object> row = (List<Object>) o;
//            String customerNumber = (String)row.get(0);
//            String theTime = (String)row.get(1);
//            String remark = (String)row.get(2);
//            // String customerName = (String)row.get(3);
//            String walletName = (String)row.get(4);
//            String amount = (String) row.get(5);
//            //暂扣返利
//            String withholdAmount = (String) row.get(6);
//            String policyFileNo = (String) row.get(7);
//            String policyDocNo = (String) row.get(8);
//            String policyYear = (String) row.get(9);
//            String policyMonth = (String) row.get(10);
//            String policyOrg = (String) row.get(11);
//            String customerArea  = (String) row.get(12);
//            String customerAttr  = (String) row.get(13);
//            String rewardActualCustomers = (String) row.get(14);
//            String remark1 = (String) row.get(15);
//            String remark2 = (String) row.get(16);
//            rebateOrderBean.setRemark(remark);
//
//            if(StringUtils.isEmpty(customerNumber) || StringUtils.isEmpty(walletName) ||StringUtils.isEmpty(amount)){
//                throw new RemoteServiceException("经销商编码/返利类型/返利总金额");
//            }
//
//            if(withholdAmount != null && new BigDecimal(withholdAmount).doubleValue() != 0) {
//                BigDecimal sum = new BigDecimal(amount).add(new BigDecimal(withholdAmount));
//                if (sum.doubleValue() != 0) {
//                    throw new RemoteServiceException("返利总金额与暂扣返利未按规则填写");
//                }
//            }
//            //验证返利钱包是否存在
//
//
//            //验证经销商数据是否存在
//            List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerNumber).list();
//            if(list.size() < 1){
//                throw new RemoteServiceException("经销商编码：" + customerNumber + "，不存在");
//            }
//            String  customerId = list.get(0).getId();
//            List<CustomerWalletBean> customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, "REBATE",false);
//            RebateOrderItem rebateOrderItem = new RebateOrderItem();
//            Boolean  walletExist = false;
//            for(CustomerWalletBean customerWallet:customerWalletBeans){
//                if(walletName.equals(customerWallet.getName())){
//                    rebateOrderItem.setCustomerWalletId(customerWallet.getCustomerWalletId());
//                    rebateOrderItem.setWalletName(customerWallet.getName());
//                    walletExist = true;
//                    continue;
//                }
//            }
//
//            if(!walletExist){
//                throw new RemoteServiceException("返利钱包：" + walletName + "，不存在");
//            }
//            rebateOrderItem.setCustomerNumber(customerNumber);
//            rebateOrderItem.setCustomerId(customerId);
//            rebateOrderItem.setCustomerName(list.get(0).getName());
//            rebateOrderItem.setAmount(new BigDecimal(amount));
//            if(null != withholdAmount){
//                rebateOrderItem.setWithholdAmount(new BigDecimal(withholdAmount));
//            }
//            rebateOrderItem.setPolicyFileNo(policyFileNo);
//            rebateOrderItem.setPolicyDocNo(policyDocNo);
//            rebateOrderItem.setPolicyYear(policyYear);
//
//            rebateOrderItem.setPolicyMonth(policyMonth);
//            rebateOrderItem.setPolicyOrg(policyOrg);
//            rebateOrderItem.setCustomerArea(customerArea);
//            rebateOrderItem.setCustomerAttr(customerAttr);
//            rebateOrderItem.setRewardActualCustomers(rewardActualCustomers);
//            rebateOrderItem.setRemark1(remark1);
//            rebateOrderItem.setRemark2(remark2);
//            rebateOrderItem.setTheTime(new Date());
//            //rebateOrderItem.setRemark(remark);
//            rebateOrderItems.add(rebateOrderItem);
//        }
//        rebateOrderBean.setItems(rebateOrderItems);
//        return rebateOrderBean;
//    }



    /**
     * 返回数据
     * @param rows
     * @return
     * @throws Exception
     */
    public ReceivableOrderBean importReceivableOrderData(List<Object> rows) throws Exception{
        ReceivableOrderBean receivableOrderBean = new ReceivableOrderBean();
        List<ReceivableOrderItem> receivableOrderItems = new ArrayList<>();
        String defaultSource = null;
        for(Object o : rows){
            List<Object> row = (List<Object>) o;
            String billType = (String)row.get(0);
            if(!StringUtils.isNotEmpty(defaultSource)){
                defaultSource = (String)row.get(1);
            }
            String source = (String)row.get(1);
            String finishDate = (String)row.get(2);
            String remark = (String)row.get(3);
            String customerName = (String)row.get(4);
            String feeCode = (String)row.get(5);
            String feeName = (String) row.get(6);
            String feeDept = (String) row.get(7);
            String incomeDept = (String) row.get(8);
            String walletName = (String) row.get(9);
            String fpType = (String) row.get(10);
            String totalAmount = (String) row.get(11);
            String taxRate  = (String) row.get(12);
            String itemRemark  = (String) row.get(13);
            receivableOrderBean.setRemark(remark);
            receivableOrderBean.setSource(defaultSource);
            if(!defaultSource.equals(source)){
                throw new RemoteServiceException("不支持导入不同类型的数据。");
            }

            receivableOrderBean.setBillType(billType);
            if(null !=finishDate){
                receivableOrderBean.setEndTime(new SimpleDateFormat("yyyy/MM/dd").parse(finishDate));
            }

            if(StringUtils.isEmpty(customerName) || StringUtils.isEmpty(walletName) ||StringUtils.isEmpty(totalAmount)){
                throw new RemoteServiceException("经销商/返利类型/总金额不可为空");
            }

            //验证经销商数据是否存在
            List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getName, customerName).list();
            if(list.size() < 1){
                throw new RemoteServiceException("经销商名称：" + customerName + "，不存在");
            }
            String customerId = list.get(0).getId();
            List<CustomerWalletBean> customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, "COMMONLY",false);
            ReceivableOrderItem receivableOrderItem = new ReceivableOrderItem();
            Boolean  walletExist = false;
            for(CustomerWalletBean customerWallet:customerWalletBeans){
                if(walletName.equals(customerWallet.getName())){
                    receivableOrderItem.setCustomerWalletId(customerWallet.getCustomerWalletId());
                    receivableOrderItem.setCustomerWalletName(customerWallet.getCustomerWalletName());
                    walletExist = true;
                    continue;
                }
            }
            if(!walletExist){
                throw new RemoteServiceException("钱包：" + walletName + "，不存在");
            }
            receivableOrderItem.setCustomerNumber(list.get(0).getNumber());
            receivableOrderItem.setCustomerId(list.get(0).getId());
            receivableOrderItem.setCustomerName(list.get(0).getName());
            receivableOrderItem.setIncomeDept(incomeDept);
            receivableOrderItem.setProjectCode(feeCode);
            receivableOrderItem.setProjectName(feeName);
            receivableOrderItem.setDepartmentId(feeDept);
            receivableOrderItem.setInvoiceType(fpType);
            if(null != totalAmount){
                receivableOrderItem.setTotalAmount(new BigDecimal(totalAmount));
            }
            if(null != taxRate) {
                receivableOrderItem.setTaxRate(new BigDecimal(taxRate));
            }
            receivableOrderItem.setRemark(itemRemark);
            receivableOrderItems.add(receivableOrderItem);
        }
        receivableOrderBean.setItems(receivableOrderItems);
        return receivableOrderBean;
    }

    public RebateMessageBean rebateMessage(){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //如果是经销商
        RebateMessageBean rm = new RebateMessageBean();
        rm.setHasMessage(false);
        String key;
        if(adminUser.getIsCustomer()){
             key = Constant.RedisPrefix.REBATE_NOTICE + Constant.REDIS_ROLE_DEALERS + adminUser.getCustomerId();
        } else {
             key = Constant.RedisPrefix.REBATE_NOTICE + Constant.REDIS_ROLE_BUSINESS;
        }
        Object message = redisUtil.get(key);
        //获取完数据删除
        if(message != null){
            rm.setHasMessage(true);
            rm.setMessages(message.toString().split("^"));
            redisUtil.del(key);
        }
        return rm;
    }

    public ExcelData export(List<RebateOrderItem> rebateOrderItems) {
        String[] titles = new String[]{"状态", "是否确认","返利单号", "返利日期",
                "标题备注","经销商编码","经销商名称","返利类型","总返利金额",
                "返利金额","暂扣返利","折让金额","折让编号","折让账号","已办理折让金额","折让对应收款单号",
                "政策文件流水号","政策文号","政策年份","政策月份","政策归属部门","客户区域"
                ,"客户属性","奖励实际归属客户","备注1","备注2","制单人","制单时间","审核人",
                "审核时间","确认人","确认时间","复核人","复核时间"};
//        String[] customerTitles = new String[]{"状态", "是否确认","返利单号", "返利日期",
//                "标题备注","经销商编码","经销商名称","返利类型","总返利金额",
//                "返利金额","暂扣返利","折让金额","折让编号","折让账号","已办理折让金额","折让对应收款单号",
//                "政策文件流水号","政策文号","政策年份","政策月份","政策归属部门","客户区域"
//                ,"客户属性","奖励实际归属客户","备注1","备注2","制单人","制单时间","审核人",
//                "审核时间","确认人","确认时间","复核人","复核时间"};

        List<List<Object>> rows = new ArrayList<>();
        for (RebateOrderItem rebateOrderItem : rebateOrderItems) {
            List<Object> row = new ArrayList<>();
//            row.add(ExamineStatusEnum.valueOf(rebateOrderItem.getExamineStatus()).getMsg());//状态
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(rebateOrderItem.getExamineStatus()));
            row.add(rebateOrderItem.getCustomerIsConfirm()  ? "已确认" : "未确认");//是否确认
            row.add(rebateOrderItem.getRebateOrderId());//返利单号
            row.add(DateUtil.formatDate(rebateOrderItem.getTheTime()));//返利日期
            row.add(rebateOrderItem.getPolicyDocNo());//标题备注
            row.add(rebateOrderItem.getCustomerNumber());//经销商编号
            row.add(rebateOrderItem.getCustomerName());//经销商名称
            row.add(rebateOrderItem.getWalletName());//返利类型
            row.add(rebateOrderItem.getAmount());//总返利金额
            row.add(rebateOrderItem.getRebateAmount());//返利金额
            row.add(rebateOrderItem.getWithholdAmount());//暂扣返利
            row.add(rebateOrderItem.getAllowanceAmount());//折让金额
            row.add(rebateOrderItem.getAllowanceCode());//折让编号
            row.add(rebateOrderItem.getAllowanceAccount());//折让帐号
            row.add(rebateOrderItem.getHandledAllowanceAmount());//已办理折让金额
            row.add(rebateOrderItem.getAllowanceOrderNo());//折让对应收款单号
            row.add(rebateOrderItem.getPolicyFileNo());//政策文件流水号
            row.add(rebateOrderItem.getPolicyDocNo());//政策文号
            row.add(rebateOrderItem.getPolicyYear());
            row.add(rebateOrderItem.getPolicyMonth());
            row.add(rebateOrderItem.getPolicyOrg());
            row.add(rebateOrderItem.getCustomerArea());
            row.add(rebateOrderItem.getCustomerAttr());
            row.add(rebateOrderItem.getRewardActualCustomers());
            row.add(rebateOrderItem.getRemark1());
            row.add(rebateOrderItem.getRemark2());
            row.add(rebateOrderItem.getCreateBy());
            row.add(DateUtil.formatDateTime(rebateOrderItem.getCreateTime()));
            row.add(rebateOrderItem.getExamineBy());
            row.add(DateUtil.formatDate(rebateOrderItem.getExamineTime()));
            row.add(rebateOrderItem.getCustomerName());
            row.add(DateUtil.formatDate(rebateOrderItem.getCustomerConfirmTime()));
            row.add(rebateOrderItem.getSecondExamineBy());
            row.add(DateUtil.formatDate(rebateOrderItem.getSecondExamineTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }


    /**
     * 返回数据
     * @param rows
     * @return
     * @throws Exception
     */

    @Transactional(rollbackFor = Exception.class)
    public void dataImportData(List<Object> rows) throws ParseException {


        List<ReceivableOrderBean> receivableOrderBeans = new ArrayList<>();

        for(Object o : rows){

            ReceivableOrderBean receivableOrderBean = new ReceivableOrderBean();

            List<ReceivableOrderItem> receivableOrderItems = new ArrayList<>();

            List<Object> row = (List<Object>) o;
            String billType = (String)row.get(0);
            String source = (String)row.get(1);
            String finishDate = (String)row.get(2);
            String remark = (String)row.get(3);
            String customerName = (String)row.get(4);
            String feeCode = (String)row.get(5);
            String feeName = (String) row.get(6);
            String feeDept = (String) row.get(7);
            String incomeDept = (String) row.get(8);
            String walletName = (String) row.get(9);
            String fpType = (String) row.get(10);
            String totalAmount = (String) row.get(11);
            String taxRate  = (String) row.get(12);
            String itemRemark  = (String) row.get(13);

            receivableOrderBean.setRemark(remark);
            receivableOrderBean.setSource(source);

            receivableOrderBean.setBillType(billType);
            if(null !=finishDate){
                receivableOrderBean.setEndTime(new SimpleDateFormat("yyyy/MM/dd").parse(finishDate));
            }

            if(StringUtils.isEmpty(customerName) || StringUtils.isEmpty(walletName) ||StringUtils.isEmpty(totalAmount)){
                throw new RemoteServiceException("经销商/返利类型/总金额不可为空");
            }

            //验证经销商数据是否存在
            List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getName, customerName).list();
            if(list.size() < 1){
                throw new RemoteServiceException("经销商名称：" + customerName + "，不存在");
            }
            String customerId = list.get(0).getId();
            List<CustomerWalletBean> customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, "COMMONLY",false);
            ReceivableOrderItem receivableOrderItem = new ReceivableOrderItem();
            Boolean  walletExist = false;
            for(CustomerWalletBean customerWallet:customerWalletBeans){
                if(walletName.equals(customerWallet.getName())){
                    receivableOrderItem.setCustomerWalletId(customerWallet.getCustomerWalletId());
                    receivableOrderItem.setCustomerWalletName(customerWallet.getCustomerWalletName());
                    receivableOrderItem.setWalletId(customerWallet.getWalletRebateId());
                    walletExist = true;
                    continue;
                }
            }
            if(!walletExist){
                throw new RemoteServiceException("钱包：" + walletName + "，不存在");
            }
            receivableOrderItem.setCustomerNumber(list.get(0).getNumber());
            receivableOrderItem.setCustomerId(list.get(0).getId());
            receivableOrderItem.setCustomerName(list.get(0).getName());
            receivableOrderItem.setIncomeDept(incomeDept);
            receivableOrderItem.setProjectCode(feeCode);
            receivableOrderItem.setProjectName(feeName);
            receivableOrderItem.setDepartmentId(feeDept);
            receivableOrderItem.setInvoiceType(fpType);

            if (fpType.equals("增值税发票"))
                receivableOrderItem.setInvoiceType("1");
            if (fpType.equals("机票"))
                receivableOrderItem.setInvoiceType("P");
            if (fpType.equals("火车票"))
                receivableOrderItem.setInvoiceType("R");
            if (fpType.equals("其他运输票"))
                receivableOrderItem.setInvoiceType("O");
            if (fpType.equals("其他"))
                receivableOrderItem.setInvoiceType("E");

            if(null != totalAmount){
                receivableOrderItem.setTotalAmount(new BigDecimal(totalAmount));
            }
            if(null != taxRate) {
                receivableOrderItem.setTaxRate(new BigDecimal(taxRate));
            }
            receivableOrderItem.setRemark(itemRemark);
            receivableOrderItems.add(receivableOrderItem);

            receivableOrderBean.setItems(receivableOrderItems);

            receivableOrderBean.setIsContinue(true);

            receivableOrderBeans.add(receivableOrderBean);
        }

        for (ReceivableOrderBean receivableOrderBean : receivableOrderBeans) {
            walletLogic.addOtherRece(receivableOrderBean);
        }



    }
}
