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

import cn.hutool.core.date.DateUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.listV2.CustomerWalletCreditRecordVO;
import com.zfire.mall.manager.bean.wallet.CustomerWalletBean;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.commonmapper.wallet.WalletCommonMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.k3.K3CustomerLogic;
import com.zfire.mall.manager.plus.entity.CustomerWallet;
import com.zfire.mall.manager.plus.entity.CustomerWalletCreditRecord;
import com.zfire.mall.manager.plus.entity.KingDeeCustomer;
import com.zfire.mall.manager.plus.service.CustomerWalletCreditRecordService;
import com.zfire.mall.manager.plus.service.CustomerWalletService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Service
public class CustomerWalletCreditLogic {

    @Autowired
    CustomerWalletCreditRecordService customerWalletCreditRecordService;
    @Autowired
    WalletCommonMapper walletCommonMapper;
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    CommonCMapper commonCMapper;
    @Autowired
    K3CustomerLogic k3CustomerLogic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;

    /**
     * 列表记录V2
     */
    public IPage<CustomerWalletCreditRecordVO> recordListV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerWalletCreditRecordVO> page = commonCMapper.queryCustomerWalletCreditRecord(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 列表记录
     */
    public IPage<CustomerWalletCreditRecord> recordList(String customerWalletId,String startTime,String endTime,Integer pageNum,Integer pageSize){
        IPage<CustomerWalletCreditRecord> list = customerWalletCreditRecordService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(customerWalletId),CustomerWalletCreditRecord::getCustomerWalletId,customerWalletId)
                .between(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime),CustomerWalletCreditRecord::getCreateTime,startTime,endTime)
                .orderByDesc(CustomerWalletCreditRecord::getCreateTime)
                .page(new Page<>(pageNum,pageSize));
        return list;
    }

    /**
     * 列表-导出
     */
    public ExcelData recordExportData(List<CustomerWalletCreditRecord> list){
        List<String> titles = Arrays.asList("经销商编码", "经销商名称", "关联钱包","变更金额","开始日期","结束日期","变更时间");
        List<List<Object>> rows = new ArrayList<>();
        for(CustomerWalletCreditRecord bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getCustomerNumber());
            row.add(bean.getCustomerName());
            row.add(bean.getCustomerWalletName());
            row.add(bean.getAmount());
            row.add(DateUtil.formatDate(bean.getStartTime()));
            row.add(DateUtil.formatDate(bean.getEndTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(titles);
        excelData.setRows(rows);
        return excelData;
    }




    /**
     *  设置额度
     */
    @Transactional
    public void addRecord(String customerId,BigDecimal amount,String customerWalletId,String startTime,String endTime){

//        if(amount.doubleValue() <= 0){
//            throw new RemoteServiceException("请填写大于0的金额");
//        }
        startTime = startTime.substring(0,10)+" 00:00:00";
        endTime = endTime.substring(0,10) + " 23:59:59";

        CustomerWalletBean customerWalletBean = walletLogic.queryWalletDetailByCustomerId(customerWalletId);
        KingDeeCustomer customer = k3CustomerLogic.detail(customerId);

        CustomerWalletCreditRecord record = new CustomerWalletCreditRecord();
        record.setStartTime(DateUtil.parseDateTime(startTime));
        record.setEndTime(DateUtil.parseDateTime(endTime));
        record.setCustomerId(customer.getId());
        record.setCustomerName(customer.getName());
        record.setCustomerNumber(customer.getNumber());
        record.setCustomerWalletId(customerWalletId);
        record.setCustomerWalletName(customerWalletBean.getName());
        record.setAmount(amount);
        record.insert();

        walletCommonMapper.reloadCustomerWalletCert(customerId);
    }


    /**
     * 使用信用额度支付
     * @param customerWalletId
     * @param amount
     * @return
     * @throws InterruptedException
     */
    public Boolean payCredit(String customerWalletId,BigDecimal amount) throws InterruptedException {
//        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_WALLET + customerWalletId);
//        if(!obtain.tryLock(5,TimeUnit.SECONDS)){
//            throw new RemoteServiceException("系统繁忙请稍后再试");
//        }
//        try {
//            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
//            if(customerWallet == null || customerWallet.getFreeCreditAmount().doubleValue() < 0 || customerWallet.getFreeCreditAmount().doubleValue() < amount.doubleValue()){
//                return false;
//            }
//            //记录已使用的信用额度
//            customerWallet.setUsedCreditAmount(customerWallet.getUsedCreditAmount().add(amount));
//            customerWallet.setFreeCreditAmount(customerWallet.getFreeCreditAmount().subtract(amount));
//            customerWallet.updateById();
////            List<CustomerWalletCreditRecord> records = customerWalletCreditRecordService.lambdaQuery()
////                    .eq(CustomerWalletCreditRecord::getCustomerWalletCreditId, customerWalletCredit.getCustomerWalletId())
////                    .le(CustomerWalletCreditRecord::getStartTime, new Date())
////                    .ge(CustomerWalletCreditRecord::getEndTime, new Date())
////                    .orderByAsc(CustomerWalletCreditRecord::getEndTime)
////                    .list();
//
////            double needPayAmount = amount.doubleValue();
////            for(CustomerWalletCreditRecord record : records){
////                if(needPayAmount <= 0){
////                    continue;
////                }
////                double ye = record.getAmount().subtract(record.getUseAmount()).doubleValue();
////                if(ye == 0){
////                    continue;
////                }
////
////                //如果需要支付的钱大于该笔信用额度，就减去，并循环到下笔信用额度来扣减
////                if(needPayAmount > ye){
////                    record.setUseAmount(record.getAmount());
////                    record.setStatus(false);
////                    needPayAmount = ArithUtils.sub(needPayAmount,ye);
////                }else{
////                    record.setUseAmount(BigDecimal.valueOf(ArithUtils.sub(ye,needPayAmount)).add(record.getUseAmount()));
////                    record.setStatus(true);
////                    needPayAmount = 0;
////                }
////                record.updateById();
////            }
//            //刷新剩余的信用额度
////            walletCommonMapper.reloadCustomerWalletCert(customerWalletCredit.getCustomerId());
//        }finally {
//            obtain.unlock();
//        }
        return true;
    }

}
