package com.zt.plat.module.qms.business.config.controller.admin;

import com.zt.plat.module.qms.business.config.controller.vo.MaterialAssayStandardDetailRespVO;
import com.zt.plat.module.qms.business.config.controller.vo.MaterialAssayStandardPageReqVO;
import com.zt.plat.module.qms.business.config.controller.vo.MaterialAssayStandardRespVO;
import com.zt.plat.module.qms.business.config.controller.vo.MaterialAssayStandardSaveReqVO;
import com.zt.plat.module.qms.business.config.dal.dataobject.MaterialAssayStandardExtendDO;
import com.zt.plat.module.qms.business.config.dal.mapper.MaterialAssayStandardMapper;
import com.zt.plat.module.qms.business.config.service.MaterialAssayStandardDetailService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;

import static com.zt.plat.framework.common.pojo.CommonResult.success;

import com.zt.plat.framework.excel.core.util.ExcelUtils;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;

import com.zt.plat.module.qms.business.config.dal.dataobject.MaterialAssayStandardDO;
import com.zt.plat.module.qms.business.config.service.MaterialAssayStandardService;

@Tag(name = "管理后台 - 检测标准")
@RestController
@RequestMapping("/qms/material-assay-standard")
@Validated
@DeptDataPermissionIgnore(enable = "true")
public class MaterialAssayStandardController implements BusinessControllerMarker {


    @Resource private MaterialAssayStandardService materialAssayStandardService;
    @Resource private MaterialAssayStandardDetailService materialAssayStandardDetailService;

    @PostMapping("/createTempData")
    @Operation(summary = "创建检测标准临时数据")
    //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:create')")
    public CommonResult<MaterialAssayStandardRespVO> createTempData() {
        MaterialAssayStandardSaveReqVO vo = new MaterialAssayStandardSaveReqVO();
        vo.setRemark(MaterialAssayStandardMapper.tempDataKey);
        MaterialAssayStandardRespVO retVo = materialAssayStandardService.createMaterialAssayStandard(vo);
        retVo.setRemark("");
        return success(retVo);
    }


    @PostMapping("/create")
    @Operation(summary = "创建检测标准")
    //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:create')")
    public CommonResult<MaterialAssayStandardRespVO> createMaterialAssayStandard(@Valid @RequestBody MaterialAssayStandardSaveReqVO createReqVO) {
        return success(materialAssayStandardService.createMaterialAssayStandard(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新检测标准")
    //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:update')")
    public CommonResult<Boolean> updateMaterialAssayStandard(@Valid @RequestBody MaterialAssayStandardSaveReqVO updateReqVO) {
        Long id = updateReqVO.getId();
        MaterialAssayStandardDO entity = materialAssayStandardService.getMaterialAssayStandard(id);
        if("tempDataKey".equals(entity.getRemark()))
            updateReqVO.setRemark("");
        materialAssayStandardService.updateMaterialAssayStandard(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除检测标准")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:delete')")
    public CommonResult<Boolean> deleteMaterialAssayStandard(@RequestParam("id") Long id) {
        materialAssayStandardService.deleteMaterialAssayStandard(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除检测标准")
                //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:delete')")
    public CommonResult<Boolean> deleteMaterialAssayStandardList(@RequestBody BatchDeleteReqVO req) {
        materialAssayStandardService.deleteMaterialAssayStandardListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得检测标准")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:query')")
    public CommonResult<MaterialAssayStandardRespVO> getMaterialAssayStandard(@RequestParam("id") Long id) {
        MaterialAssayStandardDO materialAssayStandard = materialAssayStandardService.getMaterialAssayStandard(id);
        return success(BeanUtils.toBean(materialAssayStandard, MaterialAssayStandardRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得检测标准分页")
    public CommonResult<PageResult<MaterialAssayStandardRespVO>> getMaterialAssayStandardPage(@Valid MaterialAssayStandardPageReqVO pageReqVO) {
        PageResult<MaterialAssayStandardDO> pageResult = materialAssayStandardService.getMaterialAssayStandardPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MaterialAssayStandardRespVO.class));
    }

    @GetMapping("/pageWithDetail")
    @Operation(summary = "获得检测标准分页(含明细列表)")
    public CommonResult<PageResult<MaterialAssayStandardRespVO>> pageWithDetail(@Valid MaterialAssayStandardPageReqVO pageReqVO) {
        PageResult<MaterialAssayStandardExtendDO> pageResult = materialAssayStandardService.getMaterialAssayStandardPageWithExtend(pageReqVO);
        List<MaterialAssayStandardExtendDO> standardDOList = pageResult.getList();
        if(pageResult.getTotal() == 0 || standardDOList == null || standardDOList.isEmpty())
            return success(BeanUtils.toBean(pageResult, MaterialAssayStandardRespVO.class));

        List<Long> standardIdList = standardDOList.stream().map(MaterialAssayStandardDO::getId).toList();
        List<MaterialAssayStandardDetailRespVO> detailListAll = materialAssayStandardDetailService.getByStandardIdList(standardIdList);

        CommonResult<PageResult<MaterialAssayStandardRespVO>> result = success(BeanUtils.toBean(pageResult, MaterialAssayStandardRespVO.class));
        List<MaterialAssayStandardRespVO> list = result.getData().getList();
        for(MaterialAssayStandardRespVO standard : list) {
            Long standardId = standard.getId();
            List<MaterialAssayStandardDetailRespVO> detailList = detailListAll.stream().filter(detail ->
                    detail.getMaterialAssayStandardId() != null && detail.getMaterialAssayStandardId().equals(standardId)).toList();
            standard.setDetailList(detailList);
        }
        return result;
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出检测标准 Excel")
    //@PreAuthorize("@ss.hasPermission('qms:material-assay-standard:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMaterialAssayStandardExcel(@Valid MaterialAssayStandardPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MaterialAssayStandardDO> list = materialAssayStandardService.getMaterialAssayStandardPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "检测标准.xls", "数据", MaterialAssayStandardRespVO.class,
                        BeanUtils.toBean(list, MaterialAssayStandardRespVO.class));
    }

}