package com.ruoyi.projetctCost.run;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.mesInfo.domain.MesInfo;
import com.ruoyi.mesInfo.service.IMesInfoService;
import com.ruoyi.projetctCost.beenfactory.ServiceBeenFactory;
import com.ruoyi.projetctCost.util.RedisLockMethodUtil;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;

@Slf4j
public class InstallationCostSummaryCallable implements Callable<Boolean> {

    /*本次线程任务处理的mes_info数据的主键起始位*/
    private final Long startId;
    /*本次线程任务处理的mes_info数据的主键结束位*/
    private final Long endId;
    /*serviceBeen工厂*/
    private final ServiceBeenFactory serviceBeenFactory;
    /*redis工具*/
    private final RedisLockMethodUtil redisLockMethodUtil;

    private final RedisCache redisCache;

    public InstallationCostSummaryCallable(Long startId, Long endId, ServiceBeenFactory serviceBeenFactory, RedisLockMethodUtil redisLockMethodUtil, RedisCache redisCache) {
        this.startId = startId;
        this.endId = endId;
        this.serviceBeenFactory = serviceBeenFactory;
        this.redisLockMethodUtil = redisLockMethodUtil;
        this.redisCache = redisCache;
    }

    @Override
    public Boolean call() throws Exception {
        BigDecimal value = BigDecimal.valueOf(-1);
        BigDecimal mark = BigDecimal.valueOf(-1);
        int record = 0;
        UUID uuid = UUID.randomUUID();
        /*mes_info 装机信息卡service*/
        IMesInfoService mesInfoService = serviceBeenFactory.getMesInfoService();
        List<MesInfo> mesInfos = mesInfoService.selectMesInfoByKeyIdRange(startId, endId);
        for (int i = 0; i < mesInfos.size(); i++) {
            log.info(""+i);
            MesInfo mesInfo = mesInfos.get(i);
            String taskno = mesInfo.getTaskno();
            log.info(taskno);
            while (value.equals(mark)) {
                value = redisLockMethodUtil.redisCacheTaskNoLock(taskno, uuid, redisCache);
            }

            //数量
            BigDecimal num = mesInfo.getQty();
            //采购单价
            BigDecimal purchaseprice = mesInfo.getPurchaseprice();
            //装机成本
            BigDecimal zjcb = num.multiply(purchaseprice);
            //累加
            value = value.add(zjcb);

            boolean bool = redisLockMethodUtil.redisCacheTaskNoUnlock(taskno, uuid, value, redisCache);

//            if (!bool) {
//                if (record == 3) return false;
//                i--;
//                record += 1;
//            }
            value = BigDecimal.valueOf(-1);
        }
        return true;
    }
}
