package com.cusc.nirvana.user.rnr.fp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.loader.CollectionUtils;
import com.cusc.nirvana.common.loader.StringUtils;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.rnr.fp.constants.CryptKeyHelper;
import com.cusc.nirvana.user.rnr.fp.converter.FpCarInfoConverter;
import com.cusc.nirvana.user.rnr.fp.converter.FpT1UploadStatusConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpT1UploadStatusDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpT1UploadStatusPO;
import com.cusc.nirvana.user.rnr.fp.dto.FpCarInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FpT1UploadStatusDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpT1UploadStatusService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * T1上报状态(FpT1UploadStatus)表服务实现类
 *
 * @author yuy336
 * @since 2022-07-06 14:12:22
 */
@Service
@Slf4j
public class FpT1UploadStatusServiceImpl extends ServiceImpl<FpT1UploadStatusDao, FpT1UploadStatusPO>
        implements IFpT1UploadStatusService {

    @Resource
    private CacheFactory cacheFactory;

    /**
     * 通过UUID查询单条数据
     *
     * @param bean
     * @return 实例对象
     */
    @Override
    public FpT1UploadStatusDTO getByUuid(FpT1UploadStatusDTO bean) {
        FpT1UploadStatusPO record = this.getPoByUuid(bean.getUuid());
        return FpT1UploadStatusConverter.INSTANCE.poToDto(record);
    }

    /**
     * 通过查询条件查询集合数据
     *
     * @param bean
     * @return 集合对象
     */
    @Override
    public List<FpT1UploadStatusDTO> queryByList(FpT1UploadStatusDTO bean) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("iccid", CryptKeyHelper.encrypt(bean.getIccid()));
        queryWrapper.eq("order_id", bean.getOrderId());
        queryWrapper.eq(StringUtils.isNotBlank(bean.getTenantNo()), "tenant_no", bean.getTenantNo());
        queryWrapper.orderByDesc("create_time");
        List<FpT1UploadStatusPO> record = this.list(queryWrapper);
        return FpT1UploadStatusConverter.INSTANCE.poListToDtoList(record);
    }

    /**
     * 分页查询
     *
     * @param bean 筛选条件
     * @return 查询结果
     */
    @Override
    public PageResult<FpT1UploadStatusDTO> queryByPage(FpT1UploadStatusDTO bean) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");

        Page<FpT1UploadStatusPO> page =
                this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
        return PageHelper.convert(page, FpT1UploadStatusDTO.class);
    }

    /**
     * 新增数据
     *
     * @param bean 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public FpT1UploadStatusDTO insert(FpT1UploadStatusDTO bean) {
        FpT1UploadStatusPO fpT1UploadStatusPO = FpT1UploadStatusConverter.INSTANCE.dtoToPo(bean);
//	   fpT1UploadStatusPO.setUuid(CuscStringUtils.generateUuid());
        this.save(fpT1UploadStatusPO);
        bean.setUuid(fpT1UploadStatusPO.getUuid());
        return bean;
    }

    /**
     * 修改数据
     *
     * @param bean 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public FpT1UploadStatusDTO update(FpT1UploadStatusDTO bean) {
        FpT1UploadStatusPO fpT1UploadStatusPO = this.getPoByUuid(bean.getUuid());
        if (fpT1UploadStatusPO == null) {
            return null;
        }
        FpT1UploadStatusPO tmpBean = FpT1UploadStatusConverter.INSTANCE.dtoToPo(bean);
        tmpBean.setId(fpT1UploadStatusPO.getId());
        this.updateById(tmpBean);
        return bean;
    }

    @Override
    @Transactional
    public boolean clearDataByIccid(FpT1UploadStatusDTO bean) {
        baseMapper.clearDataByIccid(bean);
        return true;
    }

    @Override
    public boolean clearFlowDataByIccid(FpT1UploadStatusDTO bean) {
        baseMapper.clearFlowDataByIccid(bean);
        return true;
    }

    /**
     * 通过主键删除数据
     *
     * @param bean 实例对象
     * @return 是否成功
     */
    @Override
    @Transactional
    public boolean deleteById(FpT1UploadStatusDTO bean) {
        FpT1UploadStatusPO fpT1UploadStatusPO = this.getPoByUuid(bean.getUuid());
        if (fpT1UploadStatusPO == null) {
            return false;
        }
        return this.removeById(fpT1UploadStatusPO.getId());
    }

    @Override
    @Transactional
    public FpT1UploadStatusDTO insertOrReset(FpT1UploadStatusDTO bean) {
        //String lockKey = RedisConstant.T1_UPLOAD_STATUS_LOCK + bean.getIccid() + "_" + bean.getOrderId();
        //try {
        //    Boolean lock = cacheFactory.getLockService().lock(lockKey, RedisConstant.T1_UPLOAD_STATUS_LOCK_EXPIRE);
        //    if (!lock) {
        //        return null;
        //    }
        //} catch (CacheException e) {
        //    log.error("insertOrReset 加锁失败 ： ", e);
        //}
        FpT1UploadStatusDTO queryBean = new FpT1UploadStatusDTO();
        queryBean.setIccid(bean.getIccid());
        queryBean.setOrderId(bean.getOrderId());
        queryBean.setTenantNo(bean.getTenantNo());
        List<FpT1UploadStatusDTO> t1UploadStatusList = queryByList(bean);
        FpT1UploadStatusDTO ret;
        if (CollectionUtils.isEmpty(t1UploadStatusList)) {
            bean.setUuid(CuscStringUtils.generateUuid());
            ret = insert(bean);
        } else {
            ret = bean;
            ret.setUuid(t1UploadStatusList.get(0).getUuid());
            clearDataByIccid(ret);
        }
        //unlockKey(lockKey);
        return ret;
    }

    @Override
    public FpT1UploadStatusDTO insertOrResetFlow(FpT1UploadStatusDTO bean) {
        FpT1UploadStatusDTO queryBean = new FpT1UploadStatusDTO();
        queryBean.setIccid(bean.getIccid());
        queryBean.setOrderId(bean.getOrderId());
        queryBean.setTenantNo(bean.getTenantNo());
        List<FpT1UploadStatusDTO> t1UploadStatusList = queryByList(bean);
        FpT1UploadStatusDTO ret;
        if (CollectionUtils.isEmpty(t1UploadStatusList)) {
            bean.setUuid(CuscStringUtils.generateUuid());
            ret = insert(bean);
        } else {
            ret = bean;
            ret.setUuid(t1UploadStatusList.get(0).getUuid());
            clearFlowDataByIccid(ret);
        }
        return ret;
    }

    @Override
    public FpT1UploadStatusDTO getByIccidAndOrderId(String iccid, String orderId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("iccid", CryptKeyHelper.encrypt(iccid));
        queryWrapper.eq("order_id", orderId);
        queryWrapper.orderByDesc("create_time");
        List<FpT1UploadStatusPO> record = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(record)) {
            return null;
        }
        return FpT1UploadStatusConverter.INSTANCE.poToDto(record.get(0));
    }

    @Override
    public FpT1UploadStatusDTO getByRequestId(String requestId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("request_id", requestId);
        queryWrapper.orderByDesc("create_time");
        List<FpT1UploadStatusPO> record = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(record)) {
            return null;
        }
        return FpT1UploadStatusConverter.INSTANCE.poToDto(record.get(0));
    }

    @Override
    public List<FpT1UploadStatusDTO> queryByRequestIdList(List<String> requestIdList) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("request_id", requestIdList);
        queryWrapper.eq("user_status",1);
        queryWrapper.eq("file_status",1);
        queryWrapper.ne("report_completion",1);
        queryWrapper.orderByDesc("create_time");
        List<FpT1UploadStatusPO> record = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(record)) {
            return null;
        }
        return FpT1UploadStatusConverter.INSTANCE.poListToDtoList(record);
    }

    /**
     * 通过UUID查询单条数据
     *
     * @param uuid
     * @return 实例对象
     */
    private FpT1UploadStatusPO getPoByUuid(String uuid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("uuid", uuid);
        return this.getOne(queryWrapper);
    }

    /**
     * 释放redis锁
     *
     * @param lockKey key
     */
    private void unlockKey(String lockKey) {
        try {
            cacheFactory.getLockService().unLock(lockKey);
        } catch (CacheException e) {
            log.error("Failed to unlock " + lockKey + " ", e);
        }
    }
}
