package com.ruoyi.project.business.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.enums.SerialNumberPrefix;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.business.domain.TqContractLiftSn;
import com.ruoyi.project.business.domain.bo.contract.TqContractLift4OrderNoBo;
import com.ruoyi.project.business.domain.bo.contract.TqContractLiftBo;
import com.ruoyi.project.business.domain.dto.TqContractLiftSnDto;
import com.ruoyi.project.business.domain.vo.contract.TqContractLiftVo;
import com.ruoyi.project.business.domain.vo.currency.ContractCurrencyTime;
import com.ruoyi.project.business.mapper.contract.TqContractLiftSnMapper;
import com.ruoyi.project.business.service.ITbContractCurrencyService;
import com.ruoyi.project.business.service.ITbCountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.business.mapper.contract.TqContractLiftMapper;
import com.ruoyi.project.business.domain.TqContractLift;
import com.ruoyi.project.business.service.ITqContractLiftService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-08-14
 */
@Service
public class TqContractLiftServiceImpl implements ITqContractLiftService 
{
    @Resource
    private TqContractLiftMapper tqContractLiftMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ITbCountryService tbCountryService;

    @Resource
    private TqContractLiftSnMapper tqContractLiftSnMapper;


    @Resource
    private ITbContractCurrencyService tbContractCurrencyService;
    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public TqContractLift selectTqContractLiftById(Long id)
    {
        return tqContractLiftMapper.selectTqContractLiftById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param tqContractLiftBo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<TqContractLiftVo> selectTqContractLiftList(TqContractLiftBo tqContractLiftBo)
    {
        if (SecurityUtils.isSuperAdmin()){
            tqContractLiftBo.setPermissionChar(null);
        }
        return tqContractLiftMapper.selectTqContractLiftList(tqContractLiftBo);
    }
    @Override
    public List<TqContractLiftVo> listAllById(Long[] ids){
        return tqContractLiftMapper.listAllById(ids,null);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param tqContractLift 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTqContractLift(TqContractLift tqContractLift)
    {
        tqContractLift.setCreateTime(DateUtils.getNowDate());
        return tqContractLiftMapper.insertTqContractLift(tqContractLift);
    }

    /**
     * @Author Chenj
     * @Description 批量更新
     * @Date 17:56 2024/8/29
     **/
    @Override
    public int updateTqContractLiftBatch(List<TqContractLift> tqContractLiftList){
        //根据实际排产日期查询汇率
        List<ContractCurrencyTime> scheduleList = tqContractLiftList.stream()
                .filter(tqContractLift -> tqContractLift.getSigningDate() != null) // Filter out null signing dates
                .map(tqContractLift -> new ContractCurrencyTime(
                        Long.parseLong(tqContractLift.getCurrencyId()), // Assuming this returns a long
                        tqContractLift.getActualProductionScheduleDate()
                ))
                .collect(Collectors.toList());
        Map<Long, BigDecimal> scheduleListIdAndRateMap = tbContractCurrencyService.selectExchangeRateByCurrencyId(scheduleList);
        //根据实际发货排产日期查询汇率
        List<ContractCurrencyTime> deliveryList = tqContractLiftList.stream()
                .filter(tqContractLift -> tqContractLift.getSigningDate() != null) // Filter out null signing dates
                .map(tqContractLift -> new ContractCurrencyTime(
                        Long.parseLong(tqContractLift.getCurrencyId()), // Assuming this returns a long
                        tqContractLift.getActualDeliveryDate()
                ))
                .collect(Collectors.toList());
        Map<Long, BigDecimal> deliveryListIdAndRateMap = tbContractCurrencyService.selectExchangeRateByCurrencyId(deliveryList);

        tqContractLiftList.forEach(item -> {
            //将签单币种汇率赋值
            if(scheduleListIdAndRateMap.containsKey(Long.parseLong(item.getCurrencyId()))){
                item.setRate4ProductionScheduling(scheduleListIdAndRateMap.get(Long.parseLong(item.getCurrencyId())));
            }
            if(deliveryListIdAndRateMap.containsKey(Long.parseLong(item.getCurrencyId()))){
                item.setRate4Shipment(deliveryListIdAndRateMap.get(Long.parseLong(item.getCurrencyId())));
            }
        });
        return tqContractLiftMapper.updateTqContractLiftBatch(tqContractLiftList);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param tqContractLift 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTqContractLift(TqContractLift tqContractLift)
    {
        tqContractLift.setUpdateTime(DateUtils.getNowDate());
        return tqContractLiftMapper.updateTqContractLift(tqContractLift);
    }

    @Override
    @Transactional
    public int updateOrderNoBo(TqContractLift4OrderNoBo tqContractLift4OrderNoBo){
        //检查多选列是否有问题
        if(tqContractLift4OrderNoBo.getIds() == null || tqContractLift4OrderNoBo.getIds().length  == 0){
            throw new ServiceException("未选择正确的id");
        }
        List<TqContractLiftVo>  tqContractLiftVoList = tqContractLiftMapper.listAllById(tqContractLift4OrderNoBo.getIds(),null);
        if(CollectionUtils.isEmpty(tqContractLiftVoList)){
            throw new ServiceException("未选择正确的id");
        }
        //获取当月的sn
        TqContractLiftSnDto tqContractLiftSn  = new TqContractLiftSnDto();
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1); // 设置为当前月份的第一天
        tqContractLiftSn.setSnEnterTime(new Date[]{Date.from(firstOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant())});
        int sn = Integer.parseInt(tqContractLiftSnMapper.selectTqContractLiftSnList(tqContractLiftSn).get(0).getSn());
        for (TqContractLiftVo item : tqContractLiftVoList) {
            item.setProductionOrderNo(redisCache.generateProductionOrder(SerialNumberPrefix.KYL.getPrefix(), sn));
        }
        return tqContractLiftMapper.updateOrderNoBo(tqContractLiftVoList);
    }



    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTqContractLiftByIds(Long[] ids)
    {
        return tqContractLiftMapper.deleteTqContractLiftByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTqContractLiftById(Long id)
    {
        return tqContractLiftMapper.deleteTqContractLiftById(id);
    }

    /**
     * @Author Chenj
     * @Description 查询此序列号是否被使用过
     * @Date 13:31 2024/9/2
     **/
    @Override
    public int selectProductionOrderNo(Date productionOrderNo){
        String productionOrderNoString = "KYL"+productionOrderNo.getYear()%100 + String.format("%02d", productionOrderNo.getMonth()+1);
        return tqContractLiftMapper.selectProductionOrderNo(productionOrderNoString);
    }

}
