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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

import com.openhis.administration.domain.Organization;
import com.openhis.administration.service.IOrganizationService;
import com.openhis.common.enums.*;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.R;
import com.core.common.utils.MessageUtils;
import com.openhis.administration.domain.Practitioner;
import com.openhis.administration.domain.Supplier;
import com.openhis.administration.service.IPractitionerService;
import com.openhis.administration.service.ISupplierService;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.utils.EnumUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.web.common.appservice.ICommonService;
import com.openhis.web.common.dto.LocationDto;
import com.openhis.web.departmentmanage.appservice.IDepartmentCommonService;
import com.openhis.web.departmentmanage.dto.DepartmentDto;
import com.openhis.web.departmentmanage.dto.DepartmentInitDto;
import com.openhis.web.departmentmanage.dto.DepartmentDeviceInfoDto;
import com.openhis.web.departmentmanage.dto.DepartmentSearchParam;
import com.openhis.web.departmentmanage.mapper.DepartmentCommonMapper;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyRequestService;

/**
 * 科室材料订货单
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class DepartmentCommonServiceImpl implements IDepartmentCommonService {

    @Resource
    private ISupplierService supplierService;

    @Resource
    private IPractitionerService practitionerService;

    @Resource
    private ISupplyRequestService supplyRequestService;

    @Resource
    private DepartmentCommonMapper departmentCommonMapper;
    @Resource
    private ICommonService commonServiceImpl;
    @Resource
    private IOrganizationService organizationService;

    /**
     * 初始化
     *
     * @return 初始化信息
     */
    @Override
    public DepartmentInitDto init() {
        DepartmentInitDto orderInitDto = new DepartmentInitDto();

        // 查询供应商列表
        List<Supplier> supplierList = supplierService.getList();
        // 查询经手人列表
        List<Practitioner> practitionerList = practitionerService.getList();
        // 经手人信息
        List<DepartmentInitDto.LongOption> practitionerListOption = practitionerList.stream()
            .map(practitioner -> new DepartmentInitDto.LongOption(practitioner.getId(), practitioner.getName()))
            .collect(Collectors.toList());
        // 供应商信息
        List<DepartmentInitDto.SupplierOption> supplierListOption = supplierList.stream()
            .map(supplier -> new DepartmentInitDto.SupplierOption(supplier.getId(), supplier.getName() ,supplier.getPhone()))
            .collect(Collectors.toList());
        // 审批状态
        List<DepartmentInitDto.IntegerOption> supplyStatusOption = Stream.of(SupplyStatus.values()).map(
            supplyStatus -> new DepartmentInitDto.IntegerOption(supplyStatus.getValue(), supplyStatus.getInfo()))
            .collect(Collectors.toList());

        // 包装情况
        List<DepartmentInitDto.IntegerOption> packagingConditionOption = Stream.of(PackagingCondition.values())
            .map(packagingCondition -> new DepartmentInitDto.IntegerOption(packagingCondition.getValue(),
                packagingCondition.getInfo()))
            .collect(Collectors.toList());

        // 验收结果
        List<DepartmentInitDto.IntegerOption> acceptanceResultOption = Stream.of(AcceptanceResult.values())
            .map(acceptanceResult -> new DepartmentInitDto.IntegerOption(acceptanceResult.getValue(),
                acceptanceResult.getInfo()))
            .collect(Collectors.toList());

        // 仓库列表
        List<LocationDto> warehouseList = commonServiceImpl.getWarehouseList();
        // 科室列表
        List<Organization> departmentList = organizationService.getList(OrganizationType.DEPARTMENT.getValue(), null);

        orderInitDto.setWarehouseListOptions(warehouseList).setDepartmentListOptions(departmentList)
            .setSupplierOption(supplierListOption).setPractitionerOption(practitionerListOption)
            .setSupplyStatusOptions(supplyStatusOption).setPackagingConditionOptions(packagingConditionOption)
            .setAcceptanceResultoryOptions(acceptanceResultOption);

        return orderInitDto;
    }

    /**
     * 获取物资
     *
     * @param purchaseOrderSearchParam 查询条件
     * @return 物资信息
     */
    @Override
    public R<?> getDeviceInfo(DepartmentSearchParam purchaseOrderSearchParam, Integer pageNo,
        Integer pageSize, String searchKey, HttpServletRequest request) {

        Long locationId = purchaseOrderSearchParam.getLocationId();
        purchaseOrderSearchParam.setLocationId(null);
        Long supplierId = purchaseOrderSearchParam.getSupplierId();
        purchaseOrderSearchParam.setSupplierId(null);
        // 构建查询条件
        QueryWrapper<DepartmentSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(purchaseOrderSearchParam, searchKey,
                new HashSet<>(Arrays.asList(CommonConstants.FieldName.Name, CommonConstants.FieldName.PyStr)), request);
        // 设置排序
        queryWrapper.orderByDesc(CommonConstants.FieldName.Name);

        Page<DepartmentDeviceInfoDto> medicationInfoDto = departmentCommonMapper
            .getDeviceInfo(new Page<>(pageNo, pageSize), queryWrapper, locationId, supplierId);

        for (DepartmentDeviceInfoDto item : medicationInfoDto.getRecords()) {
            List<DepartmentDeviceInfoDto.Option> unitList = new ArrayList<>();
            unitList
                .add(new DepartmentDeviceInfoDto.Option(item.getUnitCode(), item.getUnitCode_dictText()));
            unitList.add(
                new DepartmentDeviceInfoDto.Option(item.getMinUnitCode(), item.getMinUnitCode_dictText()));

            item.setUnitList(unitList);
        }

        return R.ok(medicationInfoDto);
    }

    /**
     * 单据列表
     *
     * @param purchaseOrderSearchParam 查询条件
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @param searchKey 模糊查询关键字
     * @param request 请求数据
     * @param locationFlg 仓库flg
     * @param supplyType 单据类型
     * @return 订货单据分页列表
     */
    @Override
    public R<?> getPage(DepartmentSearchParam purchaseOrderSearchParam, Integer pageNo, Integer pageSize,
        String searchKey, HttpServletRequest request,  String locationFlg,Integer supplyType) {
        //判断哪个画面使用
        if (supplyType != null) {
            purchaseOrderSearchParam.setTypeEnum(supplyType);
        }
//        if (locationForm != null) {
//            purchaseOrderSearchParam.setLocationTypeEnum(locationForm);
//        }
        String originalBusNoFlg = purchaseOrderSearchParam.getOriginalBusNoFlg();
        purchaseOrderSearchParam.setOriginalBusNoFlg(null);
        // 构建查询条件
        QueryWrapper<DepartmentSearchParam> queryWrapper =
            HisQueryUtils.buildQueryWrapper(purchaseOrderSearchParam, searchKey,
                new HashSet<>(
                    Arrays.asList(CommonConstants.FieldName.SupplyBusNo, CommonConstants.FieldName.ApplicantName)),
                request);
        // 设置排序
        queryWrapper.orderByDesc(CommonConstants.FieldName.SupplyBusNo);
        // 查询订货单分页列表
        Page<DepartmentDto> purchaseOrderDtoPage =
            departmentCommonMapper.getPage(new Page<>(pageNo, pageSize), queryWrapper,originalBusNoFlg, locationFlg);

        purchaseOrderDtoPage.getRecords().forEach(e -> {
            // 单据状态
            e.setStatusEnum_enumText(EnumUtils.getInfoByValue(SupplyStatus.class, e.getStatusEnum()));
            // 单据类型
            e.setTypeEnum_enumText(EnumUtils.getInfoByValue(SupplyType.class, e.getTypeEnum()));
        });

        return R.ok(purchaseOrderDtoPage);
    }

    /**
     * 删除单据
     *
     * @param busNo 单据号
     * @return 操作结果
     */
    @Override
    public R<?> deleteOrder(String busNo) {
        // 根据原始单据号查询信息
        List<SupplyRequest> supplyRequest = supplyRequestService.getSupplyByOriginalBusNo(busNo);
        if (!supplyRequest.isEmpty()) {
            // 将原始单据号信息的原始单据号删除
            boolean flg = supplyRequestService.updateByBusNo(supplyRequest.get(0).getBusNo());
            if (!flg) {
                R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
            }
        }

        // 删除单据
        boolean result = supplyRequestService.removeByBusNo(busNo);
        return result ? R.ok(null, MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null))
            : R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
    }

}
