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

import cn.hutool.core.date.DateUtil;
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.admin.AdminUserCom;
import com.zfire.mall.manager.bean.engin.deposit.CustomerEnginDepositBean;
import com.zfire.mall.manager.commonmapper.engin.deposit.CusEnginDepositeMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.CustomerEnginDeposit;
import com.zfire.mall.manager.plus.entity.KingDeeCustomer;
import com.zfire.mall.manager.plus.entity.TaxConfig;
import com.zfire.mall.manager.plus.service.CustomerEnginDepositService;
import com.zfire.mall.manager.plus.service.KingDeeCustomerService;
import com.zfire.mall.manager.plus.service.TaxConfigService;
import lombok.extern.slf4j.Slf4j;
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.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 经销商工程机押金
 */
@Service
@Slf4j
public class CustomerEnginDepositLogic {

    @Autowired
    CustomerEnginDepositService customerEnginDepositService;
    @Autowired
    CommonLogic commonLogic;
    @Resource
    TaxConfigService taxConfigService;

    @Autowired
    CusEnginDepositeMapper cusEnginDepositeMapper;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    /**
     * 经销商列表
     * @param id 主键
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<CustomerEnginDepositBean> listDetail(String id, Integer pageNum, Integer pageSize){
        CustomerEnginDeposit ced = customerEnginDepositService.getById(id);
        IPage page = customerEnginDepositService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(ced.getCustomerId()),CustomerEnginDeposit::getCustomerId,ced.getCustomerId())
                .orderByDesc(CustomerEnginDeposit::getUpdateTime)
                .page(new Page<>(pageNum, pageSize));

        List<CustomerEnginDepositBean> list = new ArrayList<>();
        Long nowTime = new Date().getTime();
        for(Object o : page.getRecords()){
            CustomerEnginDeposit customerEnginDeposit = (CustomerEnginDeposit) o;
            CustomerEnginDepositBean bean = new CustomerEnginDepositBean();
            BeanUtils.copyProperties(customerEnginDeposit,bean);
            if(customerEnginDeposit.getStartTime().getTime() <= nowTime && customerEnginDeposit.getEndTime().getTime() > nowTime){
                bean.setCurrentStatus(Constant.STATUS_EFFECT);
            }else if(customerEnginDeposit.getStartTime().getTime() > nowTime){
                bean.setCurrentStatus(Constant.STATUS_NOT_START);
            }else if(customerEnginDeposit.getEndTime().getTime() < nowTime){
                bean.setCurrentStatus(Constant.STATUS_END);
            }
            list.add(bean);
        }
        page.setRecords(list);
        return page;
    }

    public IPage<CustomerEnginDepositBean> list(String keyword,String status,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds())){
            companyIds =  adminUser.getAdminCompanyIds();
        }
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : null;
        IPage<CustomerEnginDepositBean> page = cusEnginDepositeMapper.listPage(new Page<>(pageNum, pageSize),companyIds,keyword,customerId,status);
        Long nowTime = new Date().getTime();
        List<CustomerEnginDepositBean> list = new ArrayList<>();
        for(CustomerEnginDepositBean o : page.getRecords()){
            if(o.getStartTime().getTime() <= nowTime && o.getEndTime().getTime() > nowTime){
                o.setCurrentStatus(Constant.STATUS_EFFECT);
            }else if(o.getStartTime().getTime() > nowTime){
                o.setCurrentStatus(Constant.STATUS_NOT_START);
            }else if(o.getEndTime().getTime() < nowTime){
                o.setCurrentStatus(Constant.STATUS_END);
            }
            list.add(o);
        }
        page.setRecords(list);
        return page;
    }


    /**
     * 新增经销商工程机押金比例
     */
    public void add(CustomerEnginDeposit customerEnginDeposit){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String adminCompanyId = adminUser.getAdminCompanyId();
        if(customerEnginDeposit.getRate().doubleValue() > 1){
            throw new RemoteServiceException("押金比例请输入1到100之间的数字");
        }
        if(customerEnginDeposit.getRate() == null && customerEnginDeposit.getAmount() == null){
            throw new RemoteServiceException("押金比例与金额必填之一");
        }
        if(customerEnginDeposit.getRate().doubleValue() == 0 && customerEnginDeposit.getAmount().doubleValue() == 0){
            throw new RemoteServiceException("押金比例与金额必填之一");
        }
        if(customerEnginDeposit.getEndTime().getTime() < customerEnginDeposit.getStartTime().getTime()){
            throw new RemoteServiceException("结束时间不可小于开始时间");
        }
        customerEnginDeposit.setAdminCompanyId(adminCompanyId);
        customerEnginDeposit.insert();
    }


    /**
     * 编辑经销商工程机押金比例
     */
    public void update(CustomerEnginDeposit customerEnginDeposit){
        if(customerEnginDeposit.getRate().doubleValue() > 1){
            throw new RemoteServiceException("押金比例请输入1到100之间的数字");
        }
        if(customerEnginDeposit.getRate() == null && customerEnginDeposit.getAmount() == null){
            throw new RemoteServiceException("押金比例与金额必填之一");
        }
        if(customerEnginDeposit.getRate().doubleValue() == 0 && customerEnginDeposit.getAmount().doubleValue() == 0){
            throw new RemoteServiceException("押金比例与金额必填之一");
        }
        if(customerEnginDeposit.getEndTime().getTime() < customerEnginDeposit.getStartTime().getTime()){
            throw new RemoteServiceException("结束时间不可小于开始时间");
        }
        //复制旧数据保存一份
        CustomerEnginDeposit oldDep = customerEnginDepositService.getById(customerEnginDeposit.getId());
        com.zfire.mall.manager.bean.engin.deposit.CustomerEnginDeposit newDep = new com.zfire.mall.manager.bean.engin.deposit.CustomerEnginDeposit();
        BeanUtils.copyProperties(oldDep, newDep);
        newDep.setId(IdWorker.getIdStr());
        newDep.setCreateTime(oldDep.getCreateTime());
        cusEnginDepositeMapper.insertWithTime(newDep);
        customerEnginDeposit.updateById();

        commonLogic.saveLog(customerEnginDeposit.getId());
    }

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

    /**
     * 详情
     */
    public CustomerEnginDeposit detail(String id){
        CustomerEnginDeposit customerEnginDeposit = customerEnginDepositService.getById(id);
        return customerEnginDeposit;
    }


    /**
     * 查找经销商押金比例
     */
    public BigDecimal findCustomerDepositRate(String customerId) {
        List<CustomerEnginDeposit> customerEnginDeposits = customerEnginDepositService.lambdaQuery()
                .eq(CustomerEnginDeposit::getCustomerId, customerId)
                .lt(CustomerEnginDeposit::getStartTime,new Date())
                .ge(CustomerEnginDeposit::getEndTime,new Date())
                .orderByDesc(CustomerEnginDeposit::getCreateTime)
                .page(new Page<>(1,1,false)).getRecords();

        // 有单独设置经销商押金比例
        if (customerEnginDeposits.size() > 0 ) {
            CustomerEnginDeposit customerEnginDeposit = customerEnginDeposits.get(0);
            BigDecimal zero = new BigDecimal("0");
            if (customerEnginDeposit.getRate().compareTo(zero) > 0) {
                return customerEnginDeposit.getRate();
            }

            if (customerEnginDeposit.getAmount().compareTo(zero) > 0
                    && Objects.nonNull(customerEnginDeposit.getStartTime())
                    && Objects.nonNull(customerEnginDeposit.getEndTime())) {
                long startTime = customerEnginDeposit.getStartTime().getTime();
                long endTime = customerEnginDeposit.getEndTime().getTime();
                long curTime = DateUtil.current();
                if (curTime >= startTime && curTime <= endTime) {
                    return zero.subtract(customerEnginDeposit.getAmount());
                }
            }
        }
        // 返回通用押金比例
        TaxConfig taxConfig = taxConfigService.lambdaQuery().one();
        return taxConfig.getDepositTax();
    }


    /**
     * 导入工程押金单数据
     */
    @Transactional
    public void importData(List<Object> rows) throws Exception{
        List<CustomerEnginDeposit> cedList = new ArrayList<>();
        for(Object o : rows){
            List<Object> row = (List<Object>) o;
            String customerNumber = (String) row.get(0);
            String customeName = (String) row.get(1);
            String rate = (String) row.get(2);
            String amount = (String) row.get(3);
            String startTime = (String) row.get(4);
            String endTime = (String) row.get(5);
            String remark = (String) row.get(6);

            if(StringUtils.isEmpty(customerNumber)   ){
                throw new RemoteServiceException("经销商编码不存在");
            }
            //验证经销商数据是否存在
            List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerNumber).list();
            if(list.size() < 1){
                throw new RemoteServiceException("经销商编码：" + customerNumber + "，不存在");
            }
            CustomerEnginDeposit ced = new CustomerEnginDeposit();
            ced.setId(IdWorker.getIdStr());
            ced.setCustomerName(customeName);
            ced.setCustomerNumber(customerNumber);
            ced.setCustomerId(list.get(0).getId());
            if(StringUtils.isNotEmpty(rate)){
                ced.setRate(new BigDecimal(rate));
            }
            if(StringUtils.isNotEmpty(amount)){
                ced.setAmount(new BigDecimal(amount));
            }
            ced.setStartTime(DateUtil.parseDateTime(startTime));
            if(StringUtils.isNotEmpty(endTime)){
                ced.setEndTime(DateUtil.parseDateTime(endTime));
            }
            ced.setRemark(remark);
            cedList.add(ced);
        }
        customerEnginDepositService.saveBatch(cedList);
    }

}
