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

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.mes.controller.admin.deviceledger.vo.DeviceLedgerRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.dvsubject.vo.DvSubjectPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.dvsubject.vo.DvSubjectRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.dvsubject.vo.DvSubjectSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvsubject.DvSubjectDO;
import cn.iocoder.yudao.module.mes.service.dvsubject.DvSubjectService;
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/dv-subject")
@Validated
public class DvSubjectController {

    @Resource
    private DvSubjectService dvSubjectService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DictDataApi dictDataApi;



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

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

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

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

        return success(true);
    }

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

    @GetMapping("/page")
    @Operation(summary = "获得维保项目分页")
    @PreAuthorize("@ss.hasPermission('mes:dv-subject:query')")
    public CommonResult<PageResult<DvSubjectRespVO>> getDvSubjectPage(@Valid DvSubjectPageReqVO pageReqVO) {
        PageResult<DvSubjectDO> pageResult = dvSubjectService.getDvSubjectPage(pageReqVO);
        PageResult<DvSubjectRespVO> dvSubjectRespVOPageResult = BeanUtils.toBean(pageResult, DvSubjectRespVO.class);
        return success(buildCreatorName(dvSubjectRespVOPageResult));
    }

    @GetMapping("/list")
    @Operation(summary = "获得维保项目列表")
    @PreAuthorize("@ss.hasPermission('mes:dv-subject:query')")
    public CommonResult<List<DvSubjectDO>> getDvSubjectList() {
        List<DvSubjectDO> dvSubjectDOList = dvSubjectService.getDvSubjectList();
        return success(dvSubjectDOList);
    }

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

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

        for (DvSubjectRespVO dvSubjectRespVO : dvSubjectRespVOList) {
            AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(dvSubjectRespVO.getCreator()));
            dvSubjectRespVO.setCreatorName("(" + user.getUsername()+ ")" + user.getNickname());

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

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


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

        return dvSubjectRespVOPageResult;
    }

    /**
     * 获取字典数据
     */
    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;
    }

}