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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialInfomationPageReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialInfomationRespVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialInfomationSaveReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.export.MaterialLedgerExportVO;
import com.zt.plat.module.qms.resource.material.controller.vo.query.MaterialInfomationQueryVO;
import com.zt.plat.module.qms.resource.material.controller.vo.resp.MaterialInfomationLedgerRespVO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialInfomationDO;
import com.zt.plat.module.qms.resource.material.service.MaterialInfomationService;
import lombok.extern.slf4j.Slf4j;
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 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.*;


@Slf4j
@Tag(name = "管理后台 - 物料实例")
@RestController
@RequestMapping("/qms/resource/material-infomation")
@Validated
@DeptDataPermissionIgnore(enable = "true")
public class MaterialInfomationController implements BusinessControllerMarker {


    @Resource
    private MaterialInfomationService materialInfomationService;

//    @PostMapping("/create")
    @Operation(summary = "创建物料实例")
    @PreAuthorize("@ss.hasPermission('qms:material-infomation:create')")
    public CommonResult<MaterialInfomationRespVO> createMaterialInfomation(@Valid @RequestBody MaterialInfomationSaveReqVO createReqVO) {
        return success(materialInfomationService.createMaterialInfomation(createReqVO));
    }

//    @PutMapping("/update")
    @Operation(summary = "更新物料实例")
    @PreAuthorize("@ss.hasPermission('qms:material-infomation:update')")
    public CommonResult<Boolean> updateMaterialInfomation(@Valid @RequestBody MaterialInfomationSaveReqVO updateReqVO) {
        materialInfomationService.updateMaterialInfomation(updateReqVO);
        return success(true);
    }

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

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

    @GetMapping("/get")
    @Operation(summary = "获得物料实例")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:material-infomation:query')")
    public CommonResult<MaterialInfomationRespVO> getMaterialInfomation(@RequestParam("id") Long id) {
        MaterialInfomationRespVO infomationRespVO = materialInfomationService.getMaterialInfomationWithPdtInfoByInfId(id);
        return success(infomationRespVO);
    }

    @GetMapping("/get-by-code")
    @Operation(summary = "根据物料编码获取物料")
//    @PreAuthorize("@ss.hasPermission('qms:material-infomation:query')")
    public CommonResult<MaterialInfomationRespVO> getMaterialInfomationWithPdtInfoByInfCode(@Valid MaterialInfomationQueryVO queryVO) {
        MaterialInfomationRespVO materialInfomation = materialInfomationService.getMaterialInfomationWithPdtInfoByInfCode(queryVO);
        return success(materialInfomation);
    }

    @GetMapping("/page")
    @Operation(summary = "获得物料实例分页")
//    @PreAuthorize("@ss.hasPermission('qms:material-infomation:query')")
    public CommonResult<PageResult<MaterialInfomationRespVO>> getMaterialInfomationPage(@Valid MaterialInfomationPageReqVO pageReqVO) {
        PageResult<MaterialInfomationRespVO> pageResult = materialInfomationService.getMaterialInfomationPageWithPdtInfo(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出物料实例 Excel")
    @PreAuthorize("@ss.hasPermission('qms:material-infomation:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMaterialInfomationExcel(@Valid MaterialInfomationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MaterialInfomationDO> list = materialInfomationService.getMaterialInfomationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "物料实例.xls", "数据", MaterialInfomationRespVO.class,
                        BeanUtils.toBean(list, MaterialInfomationRespVO.class));
    }

    @GetMapping("/inventory-ledger-page")
    @Operation(summary = "物料台账")
    public CommonResult<PageResult<MaterialInfomationLedgerRespVO>> getMaterialInventoryLedgerPage(@Valid MaterialInfomationPageReqVO pageReqVO) {
        // 暂时只获取危化品台账
        pageReqVO.setHazardous(1);
        PageResult<MaterialInfomationLedgerRespVO> pageResult = materialInfomationService.getMaterialInventoryLedgerPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-ledger")
    @Operation(summary = "导出台账")
    public void exportHazardousLedger(@Valid MaterialInfomationPageReqVO pageReqVO, HttpServletResponse response) throws IOException {

        // 暂时只获取危化品台账
        pageReqVO.setHazardous(1);
        PageResult<MaterialInfomationLedgerRespVO> pageResult = materialInfomationService.getMaterialInventoryLedgerPage(pageReqVO);

        // 导出 Excel
        List<MaterialInfomationLedgerRespVO> list = pageResult.getList();
        if (CollUtil.isEmpty(list)) {
            ExcelUtils.write(response, "物料危化品库存台账.xls", "危化品库存台账", MaterialLedgerExportVO.class,
                    BeanUtils.toBean(list, MaterialLedgerExportVO.class));
            return;
        }
        List<MaterialLedgerExportVO> exportVOS = list.stream().map(respVO -> {
            MaterialLedgerExportVO exportVO = BeanUtils.toBean(respVO, MaterialLedgerExportVO.class);
            JSONObject productCustomConfig = respVO.getProductCustomConfig();
            if (productCustomConfig == null) return exportVO;
            MaterialLedgerExportVO extraProps = productCustomConfig.get("extraProps", MaterialLedgerExportVO.class);
            if (extraProps == null) return exportVO;
            BeanUtil.copyProperties(extraProps, exportVO, CopyOptions.create().setIgnoreNullValue(true));
            return exportVO;
        }).toList();
        ExcelUtils.write(response, "物料危化品库存台账.xls", "危化品库存台账",
                MaterialLedgerExportVO.class,
                exportVOS);

    }

}