package com.yd.oss.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.oss.api.service.ApiOssFileService;
import com.yd.oss.api.service.ApiRelObjectMaterialService;
import com.yd.oss.feign.request.ApiRelObjectMaterialListAddRequest;
import com.yd.oss.feign.request.ApiRelObjectMaterialPageRequest;
import com.yd.oss.feign.request.ApiRelObjectMaterialUploadSubmitRequest;
import com.yd.oss.feign.response.ApiRelObjectMaterialPageResponse;
import com.yd.oss.service.model.RelObjectMaterial;
import com.yd.oss.service.service.IRelObjectMaterialService;
import com.yd.user.feign.client.sysdict.ApiSysDictFeignClient;
import com.yd.user.feign.request.sysdict.GetDictTypeListRequest;
import com.yd.user.feign.response.sysdict.GetDictItemListByDictTypeResponse;
import com.yd.user.feign.response.sysdict.GetDictTypeListResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApiRelObjectMaterialServiceImpl implements ApiRelObjectMaterialService {

    @Autowired
    private IRelObjectMaterialService iRelObjectMaterialService;

    @Autowired
    private ApiOssFileService apiOssFileService;

    @Autowired
    private ApiSysDictFeignClient apiSysDictFeignClient;

    /**
     * 分页列表查询-对象材料关系表信息
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiRelObjectMaterialPageResponse>> page(ApiRelObjectMaterialPageRequest request) {
        Page<ApiRelObjectMaterialPageResponse> page = new Page<>(request.getPageNo(), request.getPageSize());
        IPage<ApiRelObjectMaterialPageResponse> iPage = iRelObjectMaterialService.page(page, request);

        // 如果没有数据，直接返回
        if (iPage == null || CollectionUtils.isEmpty(iPage.getRecords())) {
            return Result.success(iPage);
        }

        // 收集需要翻译的字典编码
        Set<String> dataPersonSet = new HashSet<>();
        Set<String> dataTypeSet = new HashSet<>();
        for (ApiRelObjectMaterialPageResponse record : iPage.getRecords()) {
            if (record.getDataPerson() != null) {
                dataPersonSet.add(record.getDataPerson());
            }
            if (record.getDataType() != null) {
                dataTypeSet.add(record.getDataType());
            }
        }

        // 构建字典类型列表，批量查询
        List<String> dictTypes = new ArrayList<>();
        dictTypes.add("oss_data_person");
        dictTypes.add("oss_data_type");
        GetDictTypeListRequest dictRequest = new GetDictTypeListRequest();
        dictRequest.setTypeList(dictTypes);

        Result<List<GetDictTypeListResponse>> dictResult = apiSysDictFeignClient.getByDictTypeList(dictRequest);
        if (dictResult == null || dictResult.getCode() !=200 || CollectionUtils.isEmpty(dictResult.getData())) {
            log.warn("字典查询失败，无法翻译名称");
            return Result.success(iPage);
        }

        // 构建字典映射：dictType -> (itemValue -> itemLabel)
        Map<String, Map<String, String>> dictMapping = new HashMap<>();
        for (GetDictTypeListResponse dictTypeResp : dictResult.getData()) {
            String dictType = dictTypeResp.getDictType();
            List<GetDictItemListByDictTypeResponse> itemList = dictTypeResp.getDictItemList();
            if (CollectionUtils.isEmpty(itemList)) {
                continue;
            }
            Map<String, String> valueToLabel = itemList.stream()
                    .filter(item -> item.getStatus() == 1) // 只取启用状态
                    .collect(Collectors.toMap(
                            GetDictItemListByDictTypeResponse::getItemValue,
                            GetDictItemListByDictTypeResponse::getItemLabel,
                            (existing, replacement) -> existing
                    ));
            dictMapping.put(dictType, valueToLabel);
        }

        // 获取两个字典的映射
        Map<String, String> personMap = dictMapping.getOrDefault("oss_data_person", Collections.emptyMap());
        Map<String, String> typeMap = dictMapping.getOrDefault("oss_data_type", Collections.emptyMap());

        // 填充名称
        for (ApiRelObjectMaterialPageResponse record : iPage.getRecords()) {
            String dataPerson = record.getDataPerson();
            if (dataPerson != null) {
                record.setDataPersonName(personMap.get(dataPerson));
            }
            String dataType = record.getDataType();
            if (dataType != null) {
                record.setDataTypeName(typeMap.get(dataType));
            }
        }

        return Result.success(iPage);
    }

    /**
     * 删除-对象材料关系表信息
     * @param relObjectMaterialBizId
     * @return
     */
    @Override
    public Result del(String relObjectMaterialBizId) {
        //校验对象材料关系表信息是否存在
        Result<RelObjectMaterial> result = checkRelObjectMaterialIsExist(relObjectMaterialBizId);
        RelObjectMaterial relObjectMaterial = result.getData();
        iRelObjectMaterialService.removeById(relObjectMaterial.getId());
        return Result.success();
    }

    /**
     * 添加-单个对象和材料列表关系信息
     * @param request
     * @return
     */
    @Override
    public Result addRelObjectMaterialList(ApiRelObjectMaterialListAddRequest request) {
        //先删后新增
        iRelObjectMaterialService.delByObjectBizId(request.getObjectBizId());

        if (!CollectionUtils.isEmpty(request.getMaterialDtoList())) {
            List<RelObjectMaterial> saveList = request.getMaterialDtoList().stream().map(dto -> {
                RelObjectMaterial relObjectMaterial = new RelObjectMaterial();
                BeanUtils.copyProperties(request,relObjectMaterial);
                relObjectMaterial.setMaterialBizId(dto.getMaterialBizId());
                relObjectMaterial.setRelObjectMaterialBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getCode()));
                if (!CollectionUtils.isEmpty(dto.getFileBizIdList())) {
                    //附件不为空, 已上传
                    relObjectMaterial.setStatus("YSC");
                }else {
                    //附件为空, 未上传
                    relObjectMaterial.setStatus("WSC");
                }
                return relObjectMaterial;
            }).collect(Collectors.toList());
            iRelObjectMaterialService.saveOrUpdateBatch(saveList);

            //更新保存文件元数据列表
            apiOssFileService.updateByMaterial(saveList,request.getMaterialDtoList());
        }
        return Result.success();
    }

    /**
     * 上传-提交
     * @param request
     * @return
     */
    @Override
    public Result submit(ApiRelObjectMaterialUploadSubmitRequest request) {
        Result<RelObjectMaterial> result = checkRelObjectMaterialIsExist(request.getRelObjectMaterialBizId());
        RelObjectMaterial relObjectMaterial = result.getData();
        if (!CollectionUtils.isEmpty(request.getFileBizIdList())) {
            relObjectMaterial.setStatus("YSC");
        }else {
            relObjectMaterial.setStatus("WSC");
        }
        iRelObjectMaterialService.saveOrUpdate(relObjectMaterial);
        //更新保存文件元数据列表
        apiOssFileService.updateByMaterial(relObjectMaterial.getRelObjectMaterialBizId(),request.getFileBizIdList());
        return Result.success();
    }

    /**
     * 校验对象材料关系表信息是否存在
     * @param relObjectMaterialBizId
     * @return
     */
    public Result<RelObjectMaterial> checkRelObjectMaterialIsExist(String relObjectMaterialBizId) {
        RelObjectMaterial relObjectMaterial = iRelObjectMaterialService.queryOne(relObjectMaterialBizId);
        if (Objects.isNull(relObjectMaterial)) {
            //数据不存在
            throw new BusinessException(ResultCode.NULL_ERROR.getCode(),ResultCode.NULL_ERROR.getMessage());
        }
        return Result.success(relObjectMaterial);
    }

}
