package com.openhis.financial.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.common.core.redis.RedisCache;
import com.core.common.enums.DeleteFlag;
import com.core.common.utils.SecurityUtils;
import com.openhis.common.constant.YbCommonConstants;
import com.openhis.common.enums.Whether;
import com.openhis.financial.domain.Contract;
import com.openhis.financial.mapper.ContractMapper;
import com.openhis.financial.service.IContractService;

/**
 * 合同管理Service业务层处理
 *
 * @author system
 * @date 2025-02-20
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {

    @Autowired
    private RedisCache redisCache;

    /**
     *
     * @param contractNo 医保码
     * @return
     */
    @Override
    public Contract getByContractNo(String contractNo) {
        return baseMapper.selectOne(new LambdaUpdateWrapper<Contract>().eq(Contract::getBusNo, contractNo)
            .last(YbCommonConstants.sqlConst.LIMIT1));
    }

    /**
     * 查询租户合同信息分页
     *
     * @param tenantId 租户ID
     * @param pageNum 当前页
     * @param pageSize 每页多少条
     * @return 租户合同信息分页
     */
    @Override
    public IPage<Contract> getTenantContractPage(Integer tenantId, Integer pageNum, Integer pageSize) {
        return baseMapper.selectPage(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<Contract>()
            .eq(Contract::getTenantId, tenantId).eq(Contract::getDeleteFlag, DeleteFlag.NOT_DELETED.getCode()));
    }

    /**
     * 查询租户合同信息详情
     *
     * @param id ID
     * @return 租户合同信息详情
     */
    @Override
    public Contract getTenantContractDetail(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 新增租户合同信息
     *
     * @param contract 合同管理实体
     */
    @Override
    public void addTenantContract(Contract contract) {
        baseMapper.insert(contract);

    }

    /**
     * 编辑租户合同信息
     *
     * @param contract 合同管理实体
     */
    @Override
    public void editTenantContract(Contract contract) {
        baseMapper.updateById(contract);
    }

    /**
     * 删除租户合同信息
     *
     * @param id ID
     */
    @Override
    public void delTenantContract(Long id) {
        baseMapper.update(new Contract(), new LambdaUpdateWrapper<Contract>().eq(Contract::getId, id)
            .set(Contract::getDeleteFlag, DeleteFlag.DELETED.getCode()));
    }

    /**
     * 查詢合同的集合
     * 
     * @return
     */
    @Override
    public List<Contract> getContractList() {
        return baseMapper.selectList(
            new LambdaQueryWrapper<Contract>().eq(Contract::getTenantId, SecurityUtils.getLoginUser().getTenantId()));
    }

    /**
     * 查詢合同的集合
     * 
     * @return
     */
    @Override
    @Cacheable(value = "contractListCache", key = "'contractList'")
    public List<Contract> getRedisContractList() {
        return getContractList();
    }

    /**
     * 查詢合同的集合
     * 
     * @return
     */
    @Override
    public Contract getContract(String contractNo) {
        // 先从缓存中查找
        List<Contract> contractList = getRedisContractList();
        for (Contract contract : contractList) {
            if (contractNo.equals(contract.getBusNo())) {
                return contract;
            }
        }
        
        // 缓存中找不到时，直接从数据库查询，支持contractNo动态变化
        return getByContractNo(contractNo);
    }

    /**
     * 根据参保地信息找到对应的合同
     * 
     * @param insuplcAdmdvs
     * @return
     */
    @Override
    public Contract getContractByInsuplcAdmdvs(String insuplcAdmdvs) {
        List<Contract> contractList = getRedisContractList();
        for (Contract contract : contractList) {
            if (insuplcAdmdvs.equals(contract.getBusNo())) {
                return contract;
            }
        }
        if (!contractList.isEmpty()) {
            Optional<Contract> max = contractList.stream().max(Comparator.comparingInt(Contract::getSort));
            if (max.isPresent()) {
                return max.get();
            }
        }
        return null;
    }

    /**
     * 查詢合同的集合
     *
     * @return 合同集合
     */
    @Override
    public List<Contract> getContractListByYb() {
        return baseMapper.selectList(new LambdaQueryWrapper<Contract>().eq(Contract::getYbFlag, Whether.YES.getValue())
            .eq(Contract::getTenantId, SecurityUtils.getLoginUser().getTenantId()));
    }

}