package com.openhis.administration.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.common.utils.DateUtils;
import com.openhis.administration.domain.ChargeItemDefDetail;
import com.openhis.administration.domain.ChargeItemDefinition;
import com.openhis.administration.domain.HealthcareService;
import com.openhis.administration.dto.ChargeItemDefDetailPriceDto;
import com.openhis.administration.mapper.ChargeItemDefinitionMapper;
import com.openhis.administration.service.IChargeItemDefDetailService;
import com.openhis.administration.service.IChargeItemDefinitionService;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.enums.ConditionCode;
import com.openhis.common.enums.DelFlag;
import com.openhis.common.enums.PublicationStatus;
import com.openhis.common.enums.Whether;

/**
 * 费用定价管理Service业务层处理
 *
 * @author system
 * @date 2025-02-20
 */
@Service
public class ChargeItemDefinitionServiceImpl extends ServiceImpl<ChargeItemDefinitionMapper, ChargeItemDefinition>
    implements IChargeItemDefinitionService {

    @Autowired
    private IChargeItemDefDetailService chargeItemDefDetailService;

    /**
     * 获取分页列表
     *
     * @param chargeItemDefinition 查询条件
     * @param pageNo 页码
     * @param pageSize 页面大小
     * @return 分页列表
     */
    @Override
    public Page<ChargeItemDefinition> getPage(ChargeItemDefinition chargeItemDefinition, Integer pageNo,
        Integer pageSize) {

        LambdaQueryWrapper<ChargeItemDefinition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChargeItemDefinition::getDeleteFlag, DelFlag.NO.getValue());

        // 拼接查询条件
        if (chargeItemDefinition.getStatusEnum() != null) {
            queryWrapper.eq(ChargeItemDefinition::getStatusEnum, chargeItemDefinition.getStatusEnum());
        }

        return baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
    }

    /**
     * 新增费用定价
     *
     * @param chargeItemDefinition 新增内容
     * @return 新增结果
     */
    @Override
    public boolean addChargeItemDefinition(ChargeItemDefinition chargeItemDefinition) {
        // 此判断是为了避免插入时主键重复
        if (chargeItemDefinition.getId() != null) {
            return false;
        } else {
            return baseMapper.insert(chargeItemDefinition) > 0;
        }
    }

    /**
     * 删除费用定价
     *
     * @param id 费用定价id
     * @return 新增结果
     */
    @Override
    public boolean deleteChargeItemDefinition(Long id) {
        if (baseMapper.selectById(id) == null) {
            return false;
        } else {
            return baseMapper.deleteById(id) > 0;
        }
    }

    /**
     * 通过服务管理新增费用定价
     *
     * @param healthcareService 服务管理
     * @param chargeItemDefinition 费用定价
     * @return 新增结果
     */
    @Override
    public boolean addChargeItemDefinitionByHealthcareService(HealthcareService healthcareService,
        ChargeItemDefinition chargeItemDefinition) {
        // 服务管理主键id
        if (healthcareService.getId() != null) {
            chargeItemDefinition.setInstanceTable(CommonConstants.TableName.ADM_HEALTHCARE_SERVICE);
            chargeItemDefinition.setInstanceId(healthcareService.getId());
            return baseMapper.insert(chargeItemDefinition) > 0;
        } else {
            return false;
        }
    }

    /**
     * 创建费用定价和详情
     * 
     * @param chargeName 名称
     * @param typeCode 财务类别
     * @param ybCode 医保类别
     * @param unitCode 包装单位
     * @param purchasePrice 购入价
     * @param retailPrice 零售价
     * @param maximumRetailPrice 最高零售价
     * @param orgId 机构ID
     * @param instanceTable 关联表
     * @param instanceId 关联ID
     */
    @Override
    public void addChargeItemDefinitionAndDetail(String chargeName, String typeCode, String ybCode, String unitCode,
        BigDecimal purchasePrice, BigDecimal retailPrice, BigDecimal maximumRetailPrice, Long orgId,
        String instanceTable, Long instanceId) {
        // 费用定价主表
        ChargeItemDefinition chargeItemDefinition = new ChargeItemDefinition().setChargeName(chargeName)
            .setStatusEnum(PublicationStatus.ACTIVE.getValue()).setOrgId(orgId).setInstanceTable(instanceTable)
            .setInstanceId(instanceId).setEffectiveStart(DateUtils.getNowDate()).setTypeCode(typeCode).setYbType(ybCode)
            .setConditionFlag(Whether.YES.getValue()).setPrice(retailPrice);
        this.save(chargeItemDefinition);
        List<ChargeItemDefDetail> chargeItemDefDetailList = new ArrayList<>();
        // 购入价子表（购入价不一定存在）
        if (purchasePrice != null) {
            ChargeItemDefDetail defDetailPurchase =
                new ChargeItemDefDetail().setDefinitionId(chargeItemDefinition.getId())
                    .setConditionCode(ConditionCode.PURCHASE.getCode()).setAmount(purchasePrice);
            chargeItemDefDetailList.add(defDetailPurchase);
        }
        // 零售价子表
        ChargeItemDefDetail defDetailRetail = new ChargeItemDefDetail().setDefinitionId(chargeItemDefinition.getId())
            .setConditionCode(ConditionCode.UNIT.getCode()).setConditionValue(unitCode).setAmount(retailPrice);
        chargeItemDefDetailList.add(defDetailRetail);
        // 最高零售价子表
        ChargeItemDefDetail defDetailMaximumRetail =
            new ChargeItemDefDetail().setDefinitionId(chargeItemDefinition.getId())
                .setConditionCode(ConditionCode.LIMIT.getCode()).setAmount(maximumRetailPrice);
        chargeItemDefDetailList.add(defDetailMaximumRetail);
        chargeItemDefDetailService.saveBatch(chargeItemDefDetailList);
    }

    @Override
    public List<ChargeItemDefinition> searchChargeItemDefinitionByMedIds(List<Long> itemIds) {
        return baseMapper.selectList(
            new LambdaQueryWrapper<ChargeItemDefinition>().in(ChargeItemDefinition::getInstanceId, itemIds));
    }

    @Override
    public ChargeItemDefinition getChargeItemDefinitionEntity(Long instanceId, String instanceTable,
        Integer statusEnum) {
        return baseMapper.selectOne(
            new LambdaQueryWrapper<ChargeItemDefinition>().eq(ChargeItemDefinition::getInstanceId, instanceId)
                .eq(ChargeItemDefinition::getInstanceTable, instanceTable)
                .eq(ChargeItemDefinition::getStatusEnum, statusEnum));
    }

    @Override
    public ChargeItemDefDetailPriceDto getMedPriceByParam(String conditionCode, Long instanceId) {
        return this.baseMapper.getMedPriceByParam(conditionCode, instanceId);
    }

    @Override
    public ChargeItemDefDetailPriceDto getDevicePriceByParam(String conditionCode, Long instanceId) {
        return this.baseMapper.getDevicePriceByParam(conditionCode,instanceId);
    }

    @Override
    public ChargeItemDefDetailPriceDto getProductPrice(Integer statusEnum, Long instanceId) {
        return this.baseMapper.getProductPrice(statusEnum, instanceId);
    }

}