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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

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

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.R;
import com.core.common.utils.AssignSeqUtil;
import com.core.common.utils.DateUtils;
import com.core.common.utils.MessageUtils;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.PromptMsgConstant;
import com.openhis.common.enums.*;
import com.openhis.common.utils.EnumUtils;
import com.openhis.web.departmentmanage.appservice.IDepartmentCommonService;
import com.openhis.web.departmentmanage.appservice.IDepartmentStockInOrderService;
import com.openhis.web.departmentmanage.dto.DepartmentDetailDto;
import com.openhis.web.departmentmanage.dto.DepartmentInitDto;
import com.openhis.web.departmentmanage.mapper.DepartmentCommonMapper;
import com.openhis.web.inventorymanage.dto.ProductStocktakingInitDto;
import com.openhis.workflow.domain.SupplyRequest;
import com.openhis.workflow.service.ISupplyRequestService;

/**
 * 科室材料入库单
 *
 * @author yuxj
 * @date 2025-07-22
 */
@Service
public class DepartmentStockInOrderServiceImpl implements IDepartmentStockInOrderService {

    @Resource
    private AssignSeqUtil assignSeqUtil;
    @Resource
    private ISupplyRequestService supplyRequestService;

    @Autowired
    private IDepartmentCommonService departmentCommonService;
    @Autowired
    private DepartmentCommonMapper departmentCommonMapper;

    /**
     * 初始化
     *
     * @return 初始化信息
     */
    @Override
    public R<?> init() {

        DepartmentInitDto purchaseOrderInitDto = departmentCommonService.init();

        // 单据分类
        List<DepartmentInitDto.IntegerOption> supplyCategoryOption = new ArrayList<>();
        // supplyCategoryOption.add(new DepartmentInitDto.IntegerOption(SupplyCategory.NORMAL.getValue(),
        // SupplyCategory.NORMAL.getInfo()));

        purchaseOrderInitDto.setSupplyCategoryOptions(supplyCategoryOption);

        return R.ok(purchaseOrderInitDto);
    }

    /**
     * 入库单单据详情
     *
     * @param busNo 单据号
     * @param pageNo 当前页码
     * @param pageSize 查询条数
     * @return 入库单单据详情
     */
    @Override
    public R<?> getDetailPage(String busNo, Integer pageNo, Integer pageSize) {

        Page<DepartmentDetailDto> stockInOrderDtoDetailPage =
            departmentCommonMapper.getDetailPage(new Page<>(pageNo, pageSize), busNo);

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

        List<DepartmentDetailDto.Option> unitList;
        for (DepartmentDetailDto item : stockInOrderDtoDetailPage.getRecords()) {
            unitList = new ArrayList<>();
            unitList.add(new DepartmentDetailDto.Option(item.getMaxUnitCode(), item.getMaxUnitCode_dictText()));
            unitList.add(new DepartmentDetailDto.Option(item.getMinUnitCode(), item.getMinUnitCode_dictText()));

            item.setUnitList(unitList);
        }
        return R.ok(stockInOrderDtoDetailPage);
    }

    /**
     * 获取单据号
     *
     * @return 初始化信息
     */
    @Override
    public R<?> getBusNo() {

        ProductStocktakingInitDto initDto = new ProductStocktakingInitDto();
        // 单据号
        initDto.setBusNo(assignSeqUtil.getSeqByDay(AssignSeqEnum.DEPARTMENT_STOCKIN.getPrefix(), 4));

        return R.ok(initDto);
    }

    /**
     * 添加/编辑入库单
     *
     * @param stockInOrderDtoList 入库信息
     * @return 操作结果
     */

    @Override
    public R<?> addOrEditStockInOrder(List<DepartmentDetailDto> stockInOrderDtoList) {
        // 请求数据取得
        List<SupplyRequest> requestList = supplyRequestService.getSupplyByBusNo(stockInOrderDtoList.get(0).getBusNo());
        if (!requestList.isEmpty()) {
            // 请求id取得
            List<Long> requestIdList = requestList.stream().map(SupplyRequest::getId).collect(Collectors.toList());
            // 单据信息删除
            supplyRequestService.removeByIds(requestIdList);
        }
        // 添加原始单据号
        if (stockInOrderDtoList.get(0).getOriginalBusNo() != null) {
            // 审批单据并返回单据详情
            List<SupplyRequest> agreedList = supplyRequestService
                .addOriginalBusNo(stockInOrderDtoList.get(0).getOriginalBusNo(), stockInOrderDtoList.get(0).getBusNo());
            if (agreedList.isEmpty()) {
                return R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00007, null));
            }
        }

        List<SupplyRequest> supplyRequestList = new ArrayList<>();
        Date applyTime = DateUtils.getNowDate();
        for (DepartmentDetailDto item : stockInOrderDtoList) {
            SupplyRequest supplyRequest = new SupplyRequest().setBusNo(item.getBusNo())
                .setTypeEnum(SupplyType.DEPARTMENT_STOCKIN.getValue())
                .setStatusEnum(SupplyStatus.PENDING_REVIEW.getValue()).setCategoryEnum(item.getCategoryEnum())
                .setItemTable(CommonConstants.TableName.ADM_DEVICE_DEFINITION).setItemId(item.getItemId())
                .setUnitCode(item.getUnitCode()).setItemQuantity(item.getItemQuantity())
                .setRetailPrice(item.getRetailPrice()).setTotalRetailPrice(item.getTotalRetailPrice())
                .setStartTime(item.getStartTime()).setEndTime(item.getEndTime()).setLotNumber(item.getLotNumber())
                .setTraceNo(item.getTraceNo()).setTraceNoUnitCode(item.getTraceNoUnitCode())
                .setSupplierId(item.getSupplierId()).setReason(item.getReason())
                .setSourceTypeEnum(LocationForm.WAREHOUSE.getValue()).setSourceLocationId(item.getSourceLocationId())
                .setPurposeTypeEnum(LocationForm.DEPARTMENT.getValue())
                .setPurposeLocationId(item.getPurposeLocationId()).setApplicantId(item.getApplicantId())
                .setApplyTime(applyTime).setRemake(item.getRemake());
            supplyRequestList.add(supplyRequest);
        }
        // 更新请求表
        boolean flg = supplyRequestService.saveOrUpdateBatch(supplyRequestList);
        if (!flg) {
            return R.fail(MessageUtils.createMessage(PromptMsgConstant.Common.M00011, null));
        }

        return R.ok(MessageUtils.createMessage(PromptMsgConstant.Common.M00004, null));
    }

}
