package cn.iocoder.yudao.module.mes.controller.admin.moldsubject;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldDO;
import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.vo.DeviceLedgerRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.moldsubject.vo.MoldSubjectPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.moldsubject.vo.MoldSubjectRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.moldsubject.vo.MoldSubjectSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.moldsubject.MoldSubjectDO;
import cn.iocoder.yudao.module.mes.service.moldsubject.MoldSubjectService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.excel.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 维保项目")
@RestController
@RequestMapping("/mes/mold-subject")
@Validated
public class MoldSubjectController {

    @Resource
    private MoldSubjectService moldSubjectService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DictDataApi dictDataApi;



    @PostMapping("/create")
    @Operation(summary = "创建维保项目")
    @PreAuthorize("@ss.hasPermission('mes:mold-subject:create')")
    public CommonResult<Long> createMoldSubject(@Valid @RequestBody MoldSubjectSaveReqVO createReqVO) {
        return success(moldSubjectService.createMoldSubject(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新维保项目")
    @PreAuthorize("@ss.hasPermission('mes:mold-subject:update')")
    public CommonResult<Boolean> updateMoldSubject(@Valid @RequestBody MoldSubjectSaveReqVO updateReqVO) {
        moldSubjectService.updateMoldSubject(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除维保项目")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:mold-subject:delete')")
    public CommonResult<Boolean> deleteMoldSubject(@RequestParam("ids") String ids) {

        // 将逗号分隔的字符串转换为Long类型的List
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());
        moldSubjectService.deleteMoldSubject(idList);

        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得维保项目")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-subject:query')")
    public CommonResult<MoldSubjectRespVO> getMoldSubject(@RequestParam("id") Long id) {
        MoldSubjectDO moldSubject = moldSubjectService.getMoldSubject(id);
        return success(BeanUtils.toBean(moldSubject, MoldSubjectRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得维保项目分页")
    @PreAuthorize("@ss.hasPermission('mes:mold-subject:query')")
    public CommonResult<PageResult<MoldSubjectRespVO>> getMoldSubjectPage(@Valid MoldSubjectPageReqVO pageReqVO) {
        PageResult<MoldSubjectDO> pageResult = moldSubjectService.getMoldSubjectPage(pageReqVO);
        PageResult<MoldSubjectRespVO> moldSubjectRespVOPageResult = BeanUtils.toBean(pageResult, MoldSubjectRespVO.class);
        return success(buildCreatorName(moldSubjectRespVOPageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出维保项目 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold-subject:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMoldSubjectExcel(@Valid MoldSubjectPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MoldSubjectDO> list = moldSubjectService.getMoldSubjectPage(pageReqVO).getList();

        List<MoldSubjectRespVO> moldSubjectRespVOList = BeanUtils.toBean(list, MoldSubjectRespVO.class);
        // 1. 获取字典数据
        Map<String, Map<String, String>> dictData = getDictData();

        for (MoldSubjectRespVO moldSubjectRespVO : moldSubjectRespVOList) {
            AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(moldSubjectRespVO.getCreator()));
            moldSubjectRespVO.setCreatorName("(" + user.getUsername()+ ")" + user.getNickname());

            // 转换检验方式字典值
            if (StringUtils.isNotBlank(moldSubjectRespVO.getInspectionMethod())) {
                String inspectionMethodLabel = dictData.get("Inspection_method")
                        .get(moldSubjectRespVO.getInspectionMethod());
                if (StringUtils.isNotBlank(inspectionMethodLabel)) {
                    // 可以创建一个临时字段存储，或者直接替换原字段
                    moldSubjectRespVO.setInspectionMethod(inspectionMethodLabel);
                }
            }

            // 转换值类型字典值
            if (StringUtils.isNotBlank(moldSubjectRespVO.getValueType())) {
                String valueTypeLabel = dictData.get("value_types")
                        .get(moldSubjectRespVO.getValueType());
                if (StringUtils.isNotBlank(valueTypeLabel)) {
                    moldSubjectRespVO.setValueType(valueTypeLabel);
                }
            }

        }
        // 导出 Excel
        ExcelUtils.write(response, "维保项目.xls", "数据", MoldSubjectRespVO.class,
                moldSubjectRespVOList );
    }


    private PageResult<MoldSubjectRespVO> buildCreatorName(PageResult<MoldSubjectRespVO> moldSubjectRespVOPageResult) {
        for (MoldSubjectRespVO moldSubjectRespVO : moldSubjectRespVOPageResult.getList()) {
            AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(moldSubjectRespVO.getCreator()));
            if (user!=null) {
                moldSubjectRespVO.setCreatorName("(" + user.getUsername() + ")" + user.getNickname());
            }
        }

        return moldSubjectRespVOPageResult;
    }

    /**
     * 获取字典数据
     */
    private Map<String, Map<String, String>> getDictData() {
        Map<String, Map<String, String>> dictData = new HashMap<>();

        try {
            // 获取检验方式字典
            Map<String, String> inspectionMethodDict = new HashMap<>();
            List<DictDataRespDTO> inspectionMethods = dictDataApi.getDictDataList("Inspection_method");
            for (DictDataRespDTO dict : inspectionMethods) {
                inspectionMethodDict.put(dict.getValue(), dict.getLabel());
            }
            dictData.put("Inspection_method", inspectionMethodDict);

            // 获取值类型字典
            Map<String, String> valueTypeDict = new HashMap<>();
            List<DictDataRespDTO> valueTypes = dictDataApi.getDictDataList("value_types");
            for (DictDataRespDTO dict : valueTypes) {
                valueTypeDict.put(dict.getValue(), dict.getLabel());
            }
            dictData.put("value_types", valueTypeDict);
        } catch (Exception e) {
            throw new RuntimeException("获取字典数据异常：" + e);
        }

        return dictData;
    }

    @GetMapping("/getAllList")
    @Operation(summary = "获得模具维保项目列表")
    public CommonResult<List<MoldSubjectDO>> getMoldSubjectAllList() {
        List<MoldSubjectDO> doList = moldSubjectService.getAllList();
        return success(doList);
    }

}