package cc.iotkit.manager.service.impl;


import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.data.manager.IDIccidRecordData;

import cc.iotkit.manager.config.BeanUtils;
import cc.iotkit.manager.dto.vo.category.vo.*;
import cc.iotkit.manager.dto.vo.taskinfo.TaskInfoVo;
import cc.iotkit.manager.service.DIccidRecordService;
import cc.iotkit.model.iccid.DIccidRecordDO;
import cc.iotkit.model.rule.TaskInfo;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;

import cn.hutool.db.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;



/**
 * 物联网卡 Service 实现类
 *
 * @author 芋道源码
 */
@Slf4j
@Service
public class DIccidRecordServiceImpl implements DIccidRecordService {

    @Autowired
    private IDIccidRecordData idIccidRecordData;



    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, ServiceException.class})
    public String createDIccidRecord(DIccidRecordSaveReqVO createReqVO) {
      //  TenantContextHolder.setIgnore(true);
        // 插入
        DIccidRecordDO dIccidRecord = BeanUtils.toBean(createReqVO, DIccidRecordDO.class);
        DIccidRecordDO dIccidRecordDO = idIccidRecordData.findOneByCondition(dIccidRecord);
        Assert.isNull(dIccidRecordDO, "厂商物联网卡iccid已经存在");
       // dIccidRecord.setState(0);
       // dIccidRecord.setOrderId(String.valueOf(IdUtil.getSnowflake(1, 1).nextId()));
        //修改厂商物联网数量
       // TenantContextHolder.setIgnore(true);
       // TenantDO tenantDO =  tenantMapper.selectOne(new QueryWrapper<TenantDO>().lambda().eq(TenantDO::getId, dIccidRecord.getUserCode()));

       // Assert.isTrue(tenantDO.getAccountCount() > 0, "剩余授权数量不足");
       // dIccidRecord.setExpirationTime(DateUtil.offsetDay(new Date(), dIccidRecord.getValidDays()).toLocalDateTime());
      //  dIccidRecord.setUser(tenantDO.getName());
        //dIccidRecord.setTenantId(tenantDO.getId());
        // 返回
      //  tenantMapper.update(new UpdateWrapper<TenantDO>().lambda().eq(TenantDO::getId, tenantDO.getId()).set(TenantDO::getAccountCount, tenantDO.getAccountCount() - 1));

        idIccidRecordData.save(dIccidRecord);
        return null;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, ServiceException.class})
    public void updateDIccidRecord(DIccidRecordSaveReqVO updateReqVO) {
       // TenantContextHolder.setIgnore(true);
        // 校验存在
        validateDIccidRecordExists(updateReqVO.getId());
        //TenantDO tenantDO =  tenantMapper.selectOne(new QueryWrapper<TenantDO>().lambda().eq(TenantDO::getId, updateReqVO.getUserCode()));
        // 更新
        DIccidRecordDO updateObj = BeanUtils.toBean(updateReqVO, DIccidRecordDO.class);
       // updateObj.setTenantId(tenantDO.getId());
        idIccidRecordData.save(updateObj);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, ServiceException.class})
    public void deleteDIccidRecord(Long id) {
        // 校验存在
        validateDIccidRecordExists(id);
        idIccidRecordData.deleteById(id);
        // 删除
     /*   List<String> list = Arrays.asList(id.split(","));
        List<TbDIccidRecordDO> dIccidRecordDOS = dIccidRecordMapper.selectList(new QueryWrapper<TbDIccidRecordDO>().lambda().in(TbDIccidRecordDO::getId, list));
        List<String> collected = dIccidRecordDOS.stream().map(TbDIccidRecordDO::getIccid).collect(Collectors.toList());
        List<TdProductDO> tdProductDOS = tdProductMapper.selectList(new QueryWrapper<TdProductDO>().lambda().in(TdProductDO::getIccid, collected));
        if (ObjectUtil.isNotEmpty(tdProductDOS)) {
            List<String> collect = tdProductDOS.stream().map(TdProductDO::getId).collect(Collectors.toList());
            tdProductMapper.delete(new QueryWrapper<TdProductDO>().lambda().in(TdProductDO::getId, collect));
            tdProductDeptMapper.delete(new QueryWrapper<TdProductDeptDO>().lambda().in(TdProductDeptDO::getProductId));
        }
        dIccidRecordMapper.deleteBatchIds(list);*/
    }

    private void validateDIccidRecordExists(Long id) {
        if (idIccidRecordData.findById(id) == null) {
            throw new RuntimeException("物联网卡iccid不存在");
        }
    }

    @Override
    public DIccidRecordDO getDIccidRecord(Long id) {
        return idIccidRecordData.findById(id);
    }



    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, ServiceException.class})
    public String createList(DIccidRecordListSaveReqVO createReqVO, Integer num) {
        //修改厂商物联网数量
      //  TenantContextHolder.setIgnore(true);
      //  TenantDO tenantDO =  tenantMapper.selectOne(new QueryWrapper<TenantDO>().lambda().eq(TenantDO::getId, createReqVO.getUserCode()));
        DIccidRecordDO dIccidRecord = BeanUtils.toBean(createReqVO, DIccidRecordDO.class);
       // DeptDO deptDO = deptMapper.selectOne(new QueryWrapper<DeptDO>().lambda().eq(DeptDO::getId, createReqVO.getUserCode()));
       // Assert.isTrue(tenantDO.getAccountCount() - num > 0, "剩余授权数量不足");
        List<DIccidRecordDO> dIccidRecordDOS = new ArrayList<>();
        List<DIccidRecordDO> dIccidRecordDOS1 = idIccidRecordData.findAllByCondition(dIccidRecord);
        Map<String, Long> collect = dIccidRecordDOS1.stream().collect(Collectors.toMap(DIccidRecordDO::getIccid, DIccidRecordDO::getId));
        for (int i = createReqVO.getStartIccid(); i <= createReqVO.getEndIccid(); i++) {
            DIccidRecordDO dIccidRecord1 = BeanUtils.toBean(createReqVO, DIccidRecordDO.class);
            Long s1 = collect.get(dIccidRecord.getIccid() + i);
            if (ObjectUtil.isEmpty(s1)) {
                dIccidRecord1.setIccid(dIccidRecord.getIccid() + i);
                dIccidRecord1.setState(0);
                //dIccidRecord1.setUser(tenantDO.getName());
               // dIccidRecord.setTenantId(tenantDO.getId());
                dIccidRecord1.setExpirationTime(DateUtil.offsetDay(new Date(), dIccidRecord.getValidDays()).toLocalDateTime());
                dIccidRecord1.setOrderId(String.valueOf(IdUtil.getSnowflake(1, 1).nextId()));
                dIccidRecordDOS.add(dIccidRecord1);
            }
        }
        // 插入
      //  tenantMapper.update(new UpdateWrapper<TenantDO>().lambda().eq(TenantDO::getId, tenantDO.getId()).set(TenantDO::getAccountCount, tenantDO.getAccountCount() - num));
        idIccidRecordData.batchSave(dIccidRecordDOS);
        return "录入成功";
    }

    @Override
    public Paging<DIccidRecordRespVO> getDIccidRecordPage(PageRequest<DIccidRecordPageReqVO> pageReqVO) {

        return idIccidRecordData.findAll(pageReqVO.to(DIccidRecordDO.class)).to(DIccidRecordRespVO.class);

    }

}