package com.openhis.web.datadictionary.appservice.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.R;
import com.core.common.core.domain.entity.SysDictData;
import com.core.common.utils.*;
import com.core.common.utils.bean.BeanUtils;
import com.core.common.utils.poi.ExcelUtil;
import com.core.system.service.ISysDictTypeService;
import com.openhis.administration.domain.ChargeItemDefinition;
import com.openhis.administration.domain.Organization;
import com.openhis.administration.service.IChargeItemDefinitionService;
import com.openhis.administration.service.IOrganizationService;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.common.utils.CommonUtil;
import com.openhis.common.utils.EnumUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.sys.service.IOperationRecordService;
import com.openhis.web.datadictionary.appservice.IDiagTreatMAppService;
import com.openhis.web.datadictionary.appservice.IItemDefinitionService;
import com.openhis.web.datadictionary.dto.*;
import com.openhis.web.datadictionary.mapper.ActivityDefinitionManageMapper;
import com.openhis.workflow.domain.ActivityDefinition;
import com.openhis.workflow.domain.ServiceRequest;
import com.openhis.workflow.service.IActivityDefinitionService;
import com.openhis.workflow.service.IServiceRequestService;
import com.openhis.yb.service.YbManager;

/**
 * 诊疗实现类
 *
 * @author Wuser
 * @date 2025/3/28
 */
@Service
public class DiagTreatMAppServiceImpl implements IDiagTreatMAppService {

    @Resource
    private IActivityDefinitionService activityDefinitionService;
    @Resource
    private IChargeItemDefinitionService chargeItemDefinitionService;
    @Resource
    private IOrganizationService organizationService;
    @Resource
    private ActivityDefinitionManageMapper activityDefinitionManageMapper;
    @Resource
    private IItemDefinitionService itemDefinitionService;
    @Resource
    private ISysDictTypeService sysDictTypeService;
    @Resource
    private AssignSeqUtil assignSeqUtil;
    @Resource
    private YbManager ybService;
    @Resource
    private IOperationRecordService operationRecordService;
    @Resource
    private IServiceRequestService serviceRequestService;

    /**
     * 诊疗目录初期查询
     *
     * @return
     */
    @Override
    public R<?> getDiseaseTreatmentInit() {
        DiagnosisTreatmentInitDto diagnosisTreatmentInitDto = new DiagnosisTreatmentInitDto();
        // 获取状态
        List<DiagnosisTreatmentInitDto.statusEnumOption> statusEnumOptions = Stream.of(PublicationStatus.values())
            .map(status -> new DiagnosisTreatmentInitDto.statusEnumOption(status.getValue(), status.getInfo()))
            .collect(Collectors.toList());
        diagnosisTreatmentInitDto.setStatusFlagOptions(statusEnumOptions);
        // 获取执行科室
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Organization::getTypeEnum, OrganizationType.DEPARTMENT);
        List<Organization> organizations = organizationService.list(queryWrapper);
        List<DiagnosisTreatmentInitDto.exeOrganization> exeOrganizations = organizations.stream()
            .map(exeOrg -> new DiagnosisTreatmentInitDto.exeOrganization(exeOrg.getId(), exeOrg.getName()))
            .collect(Collectors.toList());
        diagnosisTreatmentInitDto.setExeOrganizations(exeOrganizations);

        // 获取诊目录疗分类
        List<SysDictData> diagnosisList =
            sysDictTypeService.selectDictDataByType(CommonConstants.DictName.DIAGNOSIS_CATEGORY_CODE);
        // 获取诊疗录疗分类
        List<DiagnosisTreatmentInitDto.dictCategoryCode> diagnosisCategories = diagnosisList.stream()
            .map(category -> new DiagnosisTreatmentInitDto.dictCategoryCode(category.getDictValue(),
                category.getDictLabel()))
            .collect(Collectors.toList());
        diagnosisTreatmentInitDto.setDiagnosisCategoryOptions(diagnosisCategories);

        // // 查询医疗服务项类型
        // List<SysDictData> medical_service_items =
        // iSysDictTypeService.selectDictDataByType(ActivityDefCategory.MEDICAL_SERVICE_ITEM.getCode());
        // // 获取医疗服务项List
        // List<DiagnosisTreatmentInitDto.diseaseTreatmentType> diseaseTreatmentCategoryList = medical_service_items
        // .stream().map(status -> new DiagnosisTreatmentInitDto.diseaseTreatmentType(status.getDictValue(),
        // status.getDictLabel()))
        // .toList();
        // List<DiagnosisTreatmentInitDto.diseaseTreatmentCategory> diseaseTreatmentCategories = new ArrayList<>();
        //
        // //获取目录分类
        // DiagnosisTreatmentInitDto.diseaseTreatmentCategory diseaseTreatmentCategory =
        // new DiagnosisTreatmentInitDto.diseaseTreatmentCategory(ActivityDefCategory.MEDICAL_SERVICE_ITEM.getValue(),
        // ActivityDefCategory.MEDICAL_SERVICE_ITEM.getInfo());
        // diseaseTreatmentCategory.setChildren(diseaseTreatmentCategoryList);
        // diseaseTreatmentCategories.add(diseaseTreatmentCategory);
        // diagnosisTreatmentInitDto.setDiseaseTreatmentCategoryList(diseaseTreatmentCategories);
        //
        // // 查询手术与治疗类型
        // List<SysDictData> medical_service_items2 =
        // iSysDictTypeService.selectDictDataByType(ActivityDefCategory.TREATMENT_SURGERY.getCode());
        // // 获取手术与治疗List
        // List<DiagnosisTreatmentInitDto.diseaseTreatmentType> diseaseTreatmentCategoryList2 = medical_service_items2
        // .stream().map(status -> new DiagnosisTreatmentInitDto.diseaseTreatmentType(status.getDictValue(),
        // status.getDictLabel()))
        // .collect(Collectors.toList());
        //
        // DiagnosisTreatmentInitDto.diseaseTreatmentCategory diseaseTreatmentCategory2 =
        // new DiagnosisTreatmentInitDto.diseaseTreatmentCategory(ActivityDefCategory.TREATMENT_SURGERY.getValue(),
        // ActivityDefCategory.TREATMENT_SURGERY.getInfo());
        // diseaseTreatmentCategory2.setChildren(diseaseTreatmentCategoryList2);
        // diseaseTreatmentCategories.add(diseaseTreatmentCategory2);
        //
        // diagnosisTreatmentInitDto.setDiseaseTreatmentCategoryList(diseaseTreatmentCategories);

        // 获取类型
        List<DiagnosisTreatmentInitDto.statusEnumOption> typeEnumOptions = Stream.of(ActivityType.values())
            .map(status -> new DiagnosisTreatmentInitDto.statusEnumOption(status.getValue(), status.getInfo()))
            .collect(Collectors.toList());
        diagnosisTreatmentInitDto.setTypeEnumOptions(typeEnumOptions);

        // 获取是/否 列表
        // 获取状态
        List<DiagnosisTreatmentInitDto.statusEnumOption> statusWeatherOption = Stream.of(Whether.values())
            .map(status -> new DiagnosisTreatmentInitDto.statusEnumOption(status.getValue(), status.getInfo()))
            .collect(Collectors.toList());
        diagnosisTreatmentInitDto.setStatusWeatherOption(statusWeatherOption);

        return R.ok(diagnosisTreatmentInitDto);
    }

    /**
     * 查询诊疗目录分页列表
     *
     * @param DiagnosisTreatmentSelParam 查询条件
     * @param searchKey 查询条件-模糊查询
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @return
     */
    @Override
    public R<?> getDiseaseTreatmentPage(DiagnosisTreatmentSelParam DiagnosisTreatmentSelParam, String searchKey,
        Integer pageNo, Integer pageSize, HttpServletRequest request) {

        // 构建查询条件
        QueryWrapper<DiagnosisTreatmentDto> queryWrapper = HisQueryUtils.buildQueryWrapper(DiagnosisTreatmentSelParam,
            searchKey, new HashSet<>(Arrays.asList("bus_no", "name", "py_str", "wb_str")), request);

        // 分页查询
        IPage<DiagnosisTreatmentDto> diseaseTreatmentPage =
            activityDefinitionManageMapper.getDiseaseTreatmentPage(new Page<DiagnosisTreatmentDto>(pageNo, pageSize), queryWrapper);

        diseaseTreatmentPage.getRecords().forEach(e -> {
            // 医保标记枚举类回显赋值
            e.setYbFlag_enumText(EnumUtils.getInfoByValue(Whether.class, e.getYbFlag()));
            // 医保对码标记枚举类回显赋值
            e.setYbMatchFlag_enumText(EnumUtils.getInfoByValue(Whether.class, e.getYbMatchFlag()));
            // 类型举类回显赋值
            e.setTypeEnum_enumText(EnumUtils.getInfoByValue(ActivityType.class, e.getTypeEnum()));
            // 状态举类回显赋值
            e.setStatusEnum_enumText(EnumUtils.getInfoByValue(PublicationStatus.class, e.getStatusEnum()));
            // 划价标记
            e.setPricingFlag_enumText(EnumUtils.getInfoByValue(Whether.class, e.getPricingFlag()));
        });

        // 返回【诊疗目录列表DTO】分页
        return R.ok(diseaseTreatmentPage);
    }

    /**
     * 根据id查询诊疗详情
     *
     * @param id 诊疗ID
     * @return
     */
    @Override
    public R<?> getDiseaseTreatmentOne(Long id) {

        // 获取租户ID
        Integer tenantId = SecurityUtils.getLoginUser().getTenantId();
        // 根据ID查询【诊疗目录】
        return R.ok(activityDefinitionManageMapper.getDiseaseTreatmentOne(id, tenantId));

    }

    /**
     * 诊疗目录编辑
     *
     * @param diagnosisTreatmentUpDto 诊疗目录列表
     * @return
     */
    @Override
    public R<?> editDiseaseTreatment(DiagnosisTreatmentUpDto diagnosisTreatmentUpDto) {

        ActivityDefinition activityDefinition = new ActivityDefinition();
        BeanUtils.copyProperties(diagnosisTreatmentUpDto, activityDefinition);

        // 拼音码
        activityDefinition.setPyStr(ChineseConvertUtils.toPinyinFirstLetter(activityDefinition.getName()));
        // 五笔码
        activityDefinition.setWbStr(ChineseConvertUtils.toWBFirstLetter(activityDefinition.getName()));

        // 更新诊疗信息
        if (activityDefinitionService.updateById(activityDefinition)) {
            // 调用医保目录对照接口
            String ybSwitch = SecurityUtils.getLoginUser().getOptionJson().getString(CommonConstants.Option.YB_SWITCH); // 医保开关
            if (Whether.YES.getCode().equals(ybSwitch) && StringUtils.isNotEmpty(activityDefinition.getYbNo())) {
                R<?> r = ybService.directoryCheck(CommonConstants.TableName.WOR_ACTIVITY_DEFINITION,
                    activityDefinition.getId());
                if (200 != r.getCode()) {
                    throw new RuntimeException("医保目录对照接口异常");
                }
            }

            ChargeItemDefinition chargeItemDefinition = new ChargeItemDefinition();
            chargeItemDefinition.setYbType(diagnosisTreatmentUpDto.getYbType())
                .setTypeCode(diagnosisTreatmentUpDto.getItemTypeCode())
                .setInstanceTable(CommonConstants.TableName.WOR_ACTIVITY_DEFINITION)
                .setInstanceId(diagnosisTreatmentUpDto.getId()).setPrice(diagnosisTreatmentUpDto.getRetailPrice())
                .setChargeName(diagnosisTreatmentUpDto.getName());
            // 插入操作记录
            operationRecordService.addEntityOperationRecord(DbOpType.UPDATE.getCode(),
                CommonConstants.TableName.WOR_ACTIVITY_DEFINITION, activityDefinition);

            // 更新价格表
            boolean upItemDef = itemDefinitionService.updateItem(chargeItemDefinition);
            // 更新子表,修改零售价,条件:单位
            boolean upItemDetail1 = itemDefinitionService.updateItemDetail(chargeItemDefinition,
                diagnosisTreatmentUpDto.getRetailPrice(), ConditionCode.UNIT.getCode());
            // 更新子表,修改最高零售价,条件:限制
            boolean upItemDetail2 = itemDefinitionService.updateItemDetail(chargeItemDefinition,
                diagnosisTreatmentUpDto.getMaximumRetailPrice(), ConditionCode.LIMIT.getCode());

            // 更新价格表
            return upItemDef && upItemDetail1 && upItemDetail2
                ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00002, new Object[] {"诊疗目录"}))
                : R.fail(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));

        }
        return R.fail(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
    }

    /**
     * 诊疗目录停用
     *
     * @param ids 诊疗目录ID列表
     * @return
     */
    @Override
    public R<?> editDiseaseTreatmentStop(List<Long> ids) {

        List<ActivityDefinition> ActivityDefinitionList = new CopyOnWriteArrayList<>();

        // 取得更新值
        for (Long detail : ids) {
            ActivityDefinition ActivityDefinition = new ActivityDefinition();
            ActivityDefinition.setId(detail);
            ActivityDefinition.setStatusEnum(PublicationStatus.RETIRED.getValue());
            ActivityDefinitionList.add(ActivityDefinition);
        }
        // 插入操作记录
        operationRecordService.addIdsOperationRecord(DbOpType.STOP.getCode(),
            CommonConstants.TableName.WOR_ACTIVITY_DEFINITION, ids);
        // 更新诊疗信息
        return activityDefinitionService.updateBatchById(ActivityDefinitionList)
            ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00002, new Object[] {"诊疗目录"}))
            : R.fail(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));

    }

    /**
     * 诊疗目录启用
     *
     * @param ids 诊疗目录ID列表
     * @return
     */
    @Override
    public R<?> editDiseaseTreatmentStart(List<Long> ids) {

        List<ActivityDefinition> ActivityDefinitionList = new CopyOnWriteArrayList<>();

        // 取得更新值
        for (Long detail : ids) {
            ActivityDefinition ActivityDefinition = new ActivityDefinition();
            ActivityDefinition.setId(detail);
            ActivityDefinition.setStatusEnum(PublicationStatus.ACTIVE.getValue());
            ActivityDefinitionList.add(ActivityDefinition);
        }
        // 插入操作记录
        operationRecordService.addIdsOperationRecord(DbOpType.START.getCode(),
            CommonConstants.TableName.WOR_ACTIVITY_DEFINITION, ids);
        // 更新诊疗信息
        return activityDefinitionService.updateBatchById(ActivityDefinitionList)
            ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00002, new Object[] {"诊疗目录"}))
            : R.fail(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));

    }

    /**
     * 新增外来诊疗目录
     *
     * @param diagnosisTreatmentUpDto 诊疗目录
     * @return
     */
    @Override
    public R<?> addDiseaseTreatment(DiagnosisTreatmentUpDto diagnosisTreatmentUpDto) {

        if (diagnosisTreatmentUpDto.getOrgId() == null) {
            // 如果为空，设置当前登录所在的医院
            Long orgId = SecurityUtils.getLoginUser().getHospitalId();
            diagnosisTreatmentUpDto.setOrgId(orgId);
        }

        ActivityDefinition activityDefinition = new ActivityDefinition();
        BeanUtils.copyProperties(diagnosisTreatmentUpDto, activityDefinition);
        // 使用10位数基础采番
        String code = assignSeqUtil.getSeq(AssignSeqEnum.ACTIVITY_DEFINITION_NUM.getPrefix(), 10);
        activityDefinition.setBusNo(code);
        // 拼音码
        activityDefinition.setPyStr(ChineseConvertUtils.toPinyinFirstLetter(activityDefinition.getName()));
        // 五笔码
        activityDefinition.setWbStr(ChineseConvertUtils.toWBFirstLetter(activityDefinition.getName()));

        // 新增外来诊疗目录
        activityDefinition.setStatusEnum(PublicationStatus.ACTIVE.getValue());
        if (activityDefinitionService.addDiagnosisTreatment(activityDefinition)) {
            // 调用医保目录对照接口
            String ybSwitch = SecurityUtils.getLoginUser().getOptionJson().getString(CommonConstants.Option.YB_SWITCH); // 医保开关
            if (Whether.YES.getCode().equals(ybSwitch) && StringUtils.isNotEmpty(activityDefinition.getYbNo())) {
                R<?> r = ybService.directoryCheck(CommonConstants.TableName.WOR_ACTIVITY_DEFINITION,
                    activityDefinition.getId());
                if (200 != r.getCode()) {
                    throw new RuntimeException("医保目录对照接口异常");
                }
            }
            // 插入操作记录
            operationRecordService.addEntityOperationRecord(DbOpType.INSERT.getCode(),
                CommonConstants.TableName.WOR_ACTIVITY_DEFINITION, activityDefinition);

            ItemUpFromDirectoryDto itemUpFromDirectoryDto = new ItemUpFromDirectoryDto();
            BeanUtils.copyProperties(diagnosisTreatmentUpDto, itemUpFromDirectoryDto);
            itemUpFromDirectoryDto.setTypeCode(diagnosisTreatmentUpDto.getItemTypeCode())
                .setUnitCode(diagnosisTreatmentUpDto.getPermittedUnitCode())
                .setInstanceTable(CommonConstants.TableName.WOR_ACTIVITY_DEFINITION)
                .setEffectiveStart(DateUtils.getNowDate()).setStatusEnum(PublicationStatus.ACTIVE.getValue())
                .setConditionFlag(Whether.YES.getValue()).setChargeName(diagnosisTreatmentUpDto.getName())
                .setInstanceId(activityDefinition.getId()).setPrice(diagnosisTreatmentUpDto.getRetailPrice());

            return itemDefinitionService.addItem(itemUpFromDirectoryDto)
                ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00002, new Object[] {"诊疗目录"}))
                : R.fail(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00008, null));

        }
        return R.fail(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00008, null));

    }

    /**
     * 导入诊疗目录
     *
     * @param file 文件
     * @return 结果
     */
    @Override
    public R<?> importData(MultipartFile file) {
        // 读取文件
        R<List<DiagnosisTreatmentImportDto>> readResult =
            CommonUtil.readImportedExcelFile(file, DiagnosisTreatmentImportDto.class);
        if (R.SUCCESS != readResult.getCode()) {
            return readResult;
        }
        List<DiagnosisTreatmentImportDto> importDtoList = readResult.getData();
        // 导入信息校验
        R<?> validateResult = validateImportDtoList(importDtoList);
        if (R.SUCCESS != validateResult.getCode()) {
            return validateResult;
        }
        // 查询机构ID供后续使用
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        // 创建表数据
        for (DiagnosisTreatmentImportDto importDto : importDtoList) {
            // 创建诊疗定义
            ActivityDefinition activityDefinition = createActivityDefinitionEntity(importDto, orgId);
            activityDefinitionService.save(activityDefinition);
            // 创建费用定价和详情
            chargeItemDefinitionService.addChargeItemDefinitionAndDetail(importDto.getName(), importDto.getTypeCode(),
                importDto.getYbType(), importDto.getPermittedUnitCode(), null, importDto.getRetailPrice(),
                importDto.getMaximumRetailPrice(), orgId, CommonConstants.TableName.WOR_ACTIVITY_DEFINITION,
                activityDefinition.getId());
        }
        return R.ok(null, "导入成功！");
    }

    /**
     * 获取导入模板
     *
     * @param response 响应
     */
    @Override
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<DiagnosisTreatmentImportDto> util = new ExcelUtil<>(DiagnosisTreatmentImportDto.class);
        util.importTemplateExcel(response, "诊疗目录数据");
    }

    /**
     * 校验诊疗项目是否可以编辑
     *
     * @param activityId 诊疗ID
     * @return 校验结果
     */
    @Override
    public R<?> validateActivityEdit(Long activityId) {
        // 查询诊疗申请
        List<ServiceRequest> serviceRequestList = serviceRequestService.getServiceRequestByActivityId(activityId);
        if (!serviceRequestList.isEmpty()) {
            if (serviceRequestList.stream().anyMatch(
                serviceRequest -> RequestStatus.COMPLETED.getValue().equals(serviceRequest.getStatusEnum()))) {
                return R.ok(1,"医生开过该诊疗项目，不可编辑");
            }
        }
        return R.ok();
    }

    /**
     * 导入信息校验
     *
     * @param importDtoList 器材目录导入数据列表
     */
    private R<?> validateImportDtoList(List<DiagnosisTreatmentImportDto> importDtoList) {
        // 字段校验（必填及数值类型）
        List<String> fieldValidateMsgList = new ArrayList<>();
        for (int i = 0; i < importDtoList.size(); i++) {
            DiagnosisTreatmentImportDto importDto = importDtoList.get(i);
            importDto.setLineNumber(i + 2);
            List<String> lineValidateMsgList = new ArrayList<>();
            if (StringUtils.isEmpty(importDto.getName())) {
                lineValidateMsgList.add("诊疗名称必填");
            }
            if (StringUtils.isEmpty(importDto.getCategoryCode())) {
                lineValidateMsgList.add("目录类别必填");
            }
            if (StringUtils.isEmpty(importDto.getPermittedUnitCode())) {
                lineValidateMsgList.add("使用单位必填");
            }
            if (StringUtils.isEmpty(importDto.getYbFlag())) {
                lineValidateMsgList.add("医保标记必填");
            }
            if (StringUtils.isEmpty(importDto.getYbMatchFlag())) {
                lineValidateMsgList.add("医保对码标记必填");
            }
            if (Whether.YES.getCode().equals(importDto.getYbMatchFlag()) && StringUtils.isEmpty(importDto.getYbNo())) {
                lineValidateMsgList.add("医保对码时，医保编码必填");
            }
            if (StringUtils.isEmpty(importDto.getChrgitmLv())) {
                lineValidateMsgList.add("医保等级必填");
            }
            if (StringUtils.isEmpty(importDto.getTypeCode())) {
                lineValidateMsgList.add("财务类别必填");
            }
            if (StringUtils.isEmpty(importDto.getYbType())) {
                lineValidateMsgList.add("医保费用类别必填");
            }
            if (StringUtils.isEmpty(importDto.getRetailPriceStr())) {
                lineValidateMsgList.add("零售价必填");
            }
            BigDecimal retailPrice;
            try {
                retailPrice = new BigDecimal(importDto.getRetailPriceStr());
                importDto.setRetailPrice(retailPrice);
            } catch (Exception e) {
                lineValidateMsgList.add("零售价应为数值类型");
            }
            if (StringUtils.isEmpty(importDto.getMaximumRetailPriceStr())) {
                lineValidateMsgList.add("最高零售价必填");
            }
            BigDecimal maximumRetailPrice;
            try {
                maximumRetailPrice = new BigDecimal(importDto.getMaximumRetailPriceStr());
                importDto.setMaximumRetailPrice(maximumRetailPrice);
            } catch (Exception e) {
                lineValidateMsgList.add("最高零售价应为数值类型");
            }
            if (!lineValidateMsgList.isEmpty()) {
                fieldValidateMsgList
                    .add("■ 第" + importDto.getLineNumber() + "行：" + String.join("，", lineValidateMsgList) + "；");
            }
        }
        if (!fieldValidateMsgList.isEmpty()) {
            return R.fail("导入失败！诊疗信息填写有误：" + String.join(" ", fieldValidateMsgList));
        }
        // 重复校验（文件行重复）
        List<String> lineRepeatedValidateMsgList = new ArrayList<>();
        List<List<DiagnosisTreatmentImportDto>> importDtoGroupList = new ArrayList<>(
            importDtoList.stream().collect(Collectors.groupingBy(DiagnosisTreatmentImportDto::getName)).values());
        for (List<DiagnosisTreatmentImportDto> importDtoGroup : importDtoGroupList) {
            if (importDtoGroup.size() > 1) {
                lineRepeatedValidateMsgList.add("■ 第"
                    + importDtoGroup.stream().map(DiagnosisTreatmentImportDto::getLineNumber).sorted()
                        .map(Object::toString).collect(Collectors.joining(","))
                    + "行的【" + importDtoGroup.get(0).getName() + "】重复；");
            }
        }
        if (!lineRepeatedValidateMsgList.isEmpty()) {
            return R.fail("导入失败！文件中存在重复诊疗：" + String.join(" ", lineRepeatedValidateMsgList));
        }
        // 重复校验（文件与数据库重复）
        List<String> dbRepeatedValidateMsgList = new ArrayList<>();
        for (DiagnosisTreatmentImportDto importDto : importDtoList) {
            List<ActivityDefinition> deviceDefinitionList = activityDefinitionService.list(
                new LambdaQueryWrapper<ActivityDefinition>().eq(ActivityDefinition::getName, importDto.getName()));
            if (!deviceDefinitionList.isEmpty()) {
                dbRepeatedValidateMsgList
                    .add("■ 第" + importDto.getLineNumber() + "行的【" + importDto.getName() + "】在系统中已存在；");
            }
        }
        if (!dbRepeatedValidateMsgList.isEmpty()) {
            return R.fail("导入失败！系统中存在重复诊疗：" + String.join(" ", dbRepeatedValidateMsgList));
        }
        return R.ok();
    }

    /**
     * 创建诊疗定义实体
     *
     * @param importDto 器材目录导入Dto
     * @param orgId 机构ID
     * @return 诊疗定义实体
     */
    private ActivityDefinition createActivityDefinitionEntity(DiagnosisTreatmentImportDto importDto, Long orgId) {
        ActivityDefinition activityDefinition = new ActivityDefinition();
        activityDefinition.setBusNo(assignSeqUtil.getSeq(AssignSeqEnum.ACTIVITY_DEFINITION_NUM.getPrefix(), 10))
            .setName(importDto.getName()).setCategoryCode(importDto.getCategoryCode())
            .setPyStr(ChineseConvertUtils.toPinyinFirstLetter(importDto.getName()))
            .setWbStr(ChineseConvertUtils.toWBFirstLetter(importDto.getName()))
            .setPermittedUnitCode(importDto.getPermittedUnitCode()).setOrgId(orgId)
            .setYbFlag(CommonUtil.tryParseInt(importDto.getYbFlag())).setYbNo(importDto.getYbNo())
            .setYbMatchFlag(CommonUtil.tryParseInt(importDto.getYbMatchFlag()))
            .setStatusEnum(PublicationStatus.ACTIVE.getValue())
            .setChrgitmLv(CommonUtil.tryParseInt(importDto.getChrgitmLv()));
        return activityDefinition;
    }
}
