package com.zt.plat.module.qms.resource.material.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.zt.plat.framework.common.util.http.HttpUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialBatchPageReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialBatchRespVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialBatchSaveReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.importer.MaterialBatchImportExcelVO;
import com.zt.plat.module.qms.resource.material.controller.vo.resp.MaterialBatchImportRespVO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialBatchDO;
import com.zt.plat.module.qms.resource.material.service.MaterialBatchService;
import com.zt.plat.module.qms.resource.material.valid.AddGroup;
import com.zt.plat.module.qms.resource.material.valid.UpdateGroup;
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.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
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 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 org.springframework.web.multipart.MultipartFile;

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

@Tag(name = "管理后台 - 物料批次")
@RestController
@RequestMapping("/qms/resource/material-batch")
@Validated
@DeptDataPermissionIgnore(enable = "true")
public class MaterialBatchController implements BusinessControllerMarker {


    @Resource
    private MaterialBatchService materialBatchService;

    @PostMapping("/create")
    @Operation(summary = "创建物料批次")
//    @PreAuthorize("@ss.hasPermission('qms:material-batch:create')")
    public CommonResult<MaterialBatchRespVO> createMaterialBatch(@Validated(AddGroup.class) @RequestBody MaterialBatchSaveReqVO createReqVO) {
        return success(materialBatchService.createMaterialBatch(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新物料批次")
//    @PreAuthorize("@ss.hasPermission('qms:material-batch:update')")
    public CommonResult<Boolean> updateMaterialBatch(@Validated(UpdateGroup.class) @RequestBody MaterialBatchSaveReqVO updateReqVO) {
        materialBatchService.updateMaterialBatch(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除物料批次")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('qms:material-batch:delete')")
    public CommonResult<Boolean> deleteMaterialBatch(@RequestParam("id") Long id) {
        materialBatchService.deleteMaterialBatch(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除物料批次")
    @PreAuthorize("@ss.hasPermission('qms:material-batch:delete')")
    public CommonResult<Boolean> deleteMaterialBatchList(@RequestBody BatchDeleteReqVO req) {
        materialBatchService.deleteMaterialBatchListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得物料批次")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:material-batch:query')")
    public CommonResult<MaterialBatchRespVO> getMaterialBatch(@RequestParam("id") Long id) {
        MaterialBatchDO materialBatch = materialBatchService.getMaterialBatch(id);
        return success(BeanUtils.toBean(materialBatch, MaterialBatchRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得物料批次分页")
//    @PreAuthorize("@ss.hasPermission('qms:material-batch:query')")
    public CommonResult<PageResult<MaterialBatchRespVO>> getMaterialBatchPage(@Valid MaterialBatchPageReqVO pageReqVO) {
        PageResult<MaterialBatchRespVO> pageResult = materialBatchService.getBatchGongPageWithPdtInfo(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出物料批次 Excel")
    @PreAuthorize("@ss.hasPermission('qms:material-batch:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMaterialBatchExcel(@Valid MaterialBatchPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MaterialBatchDO> list = materialBatchService.getMaterialBatchPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "物料批次.xls", "数据", MaterialBatchRespVO.class,
                        BeanUtils.toBean(list, MaterialBatchRespVO.class));
    }

    @PostMapping("/assign-gongduan")
    @Operation(summary = "批次工段拆分")
//    @PreAuthorize("@ss.hasPermission('qms:material-batch:create')")
    public CommonResult<List<MaterialBatchRespVO>> assignMaterialBatchGongduan(@Valid @RequestBody List<MaterialBatchSaveReqVO> createReqVOs) {
        return success(materialBatchService.assignMaterialBatchGongduan(createReqVOs));
    }

    @PutMapping("/submit")
    @Operation(summary = "提交物料批次")
    @Parameter(name = "id", required = true)
    public CommonResult<Boolean> submitMaterialBatch(@RequestParam("id") Long id) {

        return success(materialBatchService.submitMaterialBatch(id));
    }

    @GetMapping("gongduan-page")
    @Operation(summary = "获取工段列表")
    @Parameter(name = "id", description = "物料批次 id", required = true, example = "1054")
    public CommonResult<List<MaterialBatchRespVO>> getMaterialBatchGongduanList(@RequestParam("id") Long id) {
        List<MaterialBatchDO> list = materialBatchService.getGongduanListByBatIds(Collections.singletonList(id));
        return success(BeanUtils.toBean(list, MaterialBatchRespVO.class));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得物料批次导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<MaterialBatchImportExcelVO> samples = Arrays.asList(
                MaterialBatchImportExcelVO.builder()
                        .productName("无水硼砂")
                        .productCode("W11174909")
                        .productSpecification("95%")
                        .supplier("供应商 1")
                        .manufacturerDate(LocalDate.parse("2026-03-15"))
                        .dueDate(LocalDate.parse("2026-08-11"))
                        .inboundQuantity(BigDecimal.valueOf(100))
                        .location("1 号货架")
                        .remark("模板数据，导入时请删除！")
                        .build(),
                MaterialBatchImportExcelVO.builder()
                        .productName("氧化钙")
                        .productCode("W10102372")
                        .productSpecification("AR")
                        .supplier("供应商 2")
                        .manufacturerDate(LocalDate.parse("2026-04-16"))
                        .dueDate(LocalDate.parse("2026-09-18"))
                        .inboundQuantity(BigDecimal.valueOf(200))
                        .location("2 号货架")
                        .remark("模板数据，导入时请删除！")
                        .build()
        );

        ExcelUtils.write(response, "物料批次导入模板.xls", "物料批次导入",
                MaterialBatchImportExcelVO.class, samples);
    }


    @PostMapping("/import")
    @Operation(summary = "导入物料批次")
    @Parameter(name = "file", description = "Excel 文件", required = true)
    public CommonResult<MaterialBatchImportRespVO> importMaterialBatch(@RequestParam("file") MultipartFile file) throws IOException {
        List<MaterialBatchImportExcelVO> importList = ExcelUtils.read(file, MaterialBatchImportExcelVO.class, 0);
        MaterialBatchImportRespVO respVO = materialBatchService.importMaterialBatchList(importList);
        return success(respVO);
    }

}