package cn.iocoder.yudao.module.erp.controller.admin.product;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
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.erp.controller.admin.product.vo.category.ErpProductCategoryListReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductCategoryDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductMapper;
import cn.iocoder.yudao.module.erp.framework.bean.ProductTypeEnum;
import cn.iocoder.yudao.module.erp.service.product.ErpProductCategoryService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

@Tag(name = "管理后台 - ERP 产品")
@RestController
@RequestMapping("/erp/product")
@Validated
public class ErpProductController {

    @Resource
    private ErpProductService productService;
    @Resource
    private ErpProductMapper productMapper;

    @PostMapping("/create")
    @Operation(summary = "创建产品")
    //@PreAuthorize("@ss.hasPermission('erp:product:create')")
    public CommonResult<Long> createProduct(@Valid @RequestBody ProductSaveReqVO createReqVO) {
        ErpProductPageReqVO productPageReqVO =  new ErpProductPageReqVO();
        productPageReqVO.setName(createReqVO.getName());
        productPageReqVO.setStandard(createReqVO.getStandard());
        if (productMapper.selectProductExist(productPageReqVO)) {
            return error(400,"名称+规格不能重复");
        }
        productPageReqVO =  new ErpProductPageReqVO();
        productPageReqVO.setCode(createReqVO.getBarCode());
        if (!productMapper.selectProductCodeExist(productPageReqVO).getList().isEmpty()) {
            return error(400,"编码不能重复");
        }
        return success(productService.createProduct(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新产品")
    //@PreAuthorize("@ss.hasPermission('erp:product:update')")
    public CommonResult<Boolean> updateProduct(@Valid @RequestBody ProductSaveReqVO updateReqVO) {
        ErpProductPageReqVO productPageReqVO =  new ErpProductPageReqVO();
        productPageReqVO.setName(updateReqVO.getName());
        productPageReqVO.setStandard(updateReqVO.getStandard());
        if (productMapper.selectProductExist(productPageReqVO)) {
            return error(400,"名称+规格不能重复");
        }
        productPageReqVO =  new ErpProductPageReqVO();
        productPageReqVO.setCode(updateReqVO.getBarCode());
        if (!productMapper.selectProductCodeExist(productPageReqVO).getList().isEmpty()) {
            return error(400,"编码不能重复");
        }
        productService.updateProduct(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除产品")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('erp:product:delete')")
    public CommonResult<Boolean> deleteProduct(@RequestParam("id") Long id) {
        productService.deleteProduct(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得产品")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('erp:product:query')")
    public CommonResult<ErpProductRespVO> getProduct(@RequestParam("id") Long id) {
        ErpProductDO product = productService.getProduct(id);
        return success(BeanUtils.toBean(product, ErpProductRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得产品分页")
    //@PreAuthorize("@ss.hasPermission('erp:product:query')")
    public CommonResult<PageResult<ErpProductRespVO>> getProductPage(@Valid ErpProductPageReqVO pageReqVO) {
        return success(productService.getProductVOPage(pageReqVO));
    }
    @GetMapping("/simple-list-all")
    @Operation(summary = "获得所有精简列表", description = "只包含被开启的产品，主要用于前端的下拉选项")
    public CommonResult<List<ErpProductRespVO>> getAllSimpleList() {
        List<ErpProductRespVO> list = productService.getProductVOListByStatus(CommonStatusEnum.ENABLE.getStatus());
        return success(convertList(list, product -> new ErpProductRespVO().setId(product.getId())
                .setName(product.getName()).setBarCode(product.getBarCode())
                .setCategoryId(product.getCategoryId()).setCategoryName(product.getCategoryName())
                .setUnitId(product.getUnitId()).setUnitName(product.getUnitName())
                .setPurchasePrice(product.getPurchasePrice()).setSalePrice(product.getSalePrice()).setMinPrice(product.getMinPrice())));
    }
    @GetMapping("/simple-list-product")
    @Operation(summary = "获得产品精简列表", description = "只包含被开启的产品，主要用于前端的下拉选项")
    public CommonResult<List<ErpProductRespVO>> getProductSimpleList() {
        List<ErpProductRespVO> list = productService.getProductVOListByCategory(ProductTypeEnum.PRODUCT.getTypeId());
        return success(convertList(list, product -> new ErpProductRespVO().setId(product.getId())
                .setName(product.getName()).setBarCode(product.getBarCode())
                .setCategoryId(product.getCategoryId()).setCategoryName(product.getCategoryName())
                .setUnitId(product.getUnitId()).setUnitName(product.getUnitName())
                .setPurchasePrice(product.getPurchasePrice()).setSalePrice(product.getSalePrice()).setMinPrice(product.getMinPrice())));
    }
    @GetMapping("/simple-list-item")
    @Operation(summary = "获得原料精简列表", description = "只包含被开启的原料，主要用于前端的下拉选项")
    public CommonResult<List<ErpProductRespVO>> getItemSimpleList() {
        List<ErpProductRespVO> list = productService.getProductVOListByCategory(ProductTypeEnum.ITEM.getTypeId());
        return success(convertList(list, product -> new ErpProductRespVO().setId(product.getId())
                .setName(product.getName()).setBarCode(product.getBarCode())
                .setCategoryId(product.getCategoryId()).setCategoryName(product.getCategoryName())
                .setUnitId(product.getUnitId()).setUnitName(product.getUnitName())
                .setPurchasePrice(product.getPurchasePrice()).setSalePrice(product.getSalePrice()).setMinPrice(product.getMinPrice())));
    }
    @Resource
    private ErpProductCategoryService productCategoryService;
    @GetMapping("/simple-list-order")
    @Operation(summary = "获得采购商品精简列表", description = "不包含产品，主要用于前端的下拉选项")
    public CommonResult<List<ErpProductRespVO>> getOrderSimpleList() {
        List<ErpProductCategoryDO> categoryDOList = productCategoryService.getProductCategoryList(new ErpProductCategoryListReqVO());
        List<Integer> categorys = new ArrayList<>();
        long pId = ProductTypeEnum.PRODUCT.getTypeId().longValue();
        for (ErpProductCategoryDO caDO: categoryDOList) {
            if(caDO.getId() != pId){
                categorys.add(caDO.getId().intValue());
            }
        }
        List<ErpProductDO> productDOList = productService.selectByCategorys(categorys);
        List<ErpProductRespVO> list = productService.buildProductVOList(productDOList);

        return success(convertList(list, product -> new ErpProductRespVO().setId(product.getId())
                .setName(product.getName()).setBarCode(product.getBarCode())
                .setCategoryId(product.getCategoryId()).setCategoryName(product.getCategoryName())
                .setUnitId(product.getUnitId()).setUnitName(product.getUnitName())
                .setPurchasePrice(product.getPurchasePrice()).setSalePrice(product.getSalePrice()).setMinPrice(product.getMinPrice())));
    }
    @GetMapping("/simple-list-component")
    @Operation(summary = "获得备件精简列表", description = "用于前端的下拉选项")
    public CommonResult<List<ErpProductRespVO>> getComponentSimpleList() {
        List<ErpProductRespVO> list = productService.getProductVOListByCategory(ProductTypeEnum.BEIJIAN.getTypeId());
        return success(convertList(list, product -> new ErpProductRespVO().setId(product.getId())
                .setName(product.getName()).setBarCode(product.getBarCode())
                .setCategoryId(product.getCategoryId()).setCategoryName(product.getCategoryName())
                .setUnitId(product.getUnitId()).setUnitName(product.getUnitName())
                .setPurchasePrice(product.getPurchasePrice()).setSalePrice(product.getSalePrice()).setMinPrice(product.getMinPrice())));
    }
    @GetMapping("/export-excel")
    @Operation(summary = "导出产品 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProductExcel(@Valid ErpProductPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<ErpProductRespVO> pageResult = productService.getProductVOPage(pageReqVO);
        // 导出 Excel
        ExcelUtils.write(response, "产品.xls", "数据", ErpProductRespVO.class,
                pageResult.getList());
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获取产品导入模板")
    @ApiAccessLog(operateType = EXPORT)
    public void getImportTemplate(HttpServletResponse response) throws IOException {
        // 准备模板数据
        List<ErpProductImportExcelVO> list = new ArrayList<>();
        list.add(ErpProductImportExcelVO.builder()
                .name("备件1")
                .barCode("BZ001")
                .unitName("个")
                .status(0) // 启用状态
                .standard("红色")
                .remark("测试产品")
                .expiryDay(30)
                .safetyNumber(new BigDecimal("10.00"))
                .build());
        list.add(ErpProductImportExcelVO.builder()
                .name("备件2")
                .barCode("BZ002")
                .unitName("个")
                .status(0) // 启用状态
                .standard("标准")
                .remark("备件说明")
                .expiryDay(30)
                .safetyNumber(new BigDecimal("5.00"))
                .build());
        // 输出
        ExcelUtils.write(response, "产品导入模板.xls", "数据", ErpProductImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入产品")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    public CommonResult<ErpProductImportRespVO> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        // 1. 读取 Excel 数据
        List<ErpProductImportExcelVO> list = ExcelUtils.read(file, ErpProductImportExcelVO.class);
        // 2. 调用 Service 并返回结果
        return success(productService.importProductList(list, updateSupport));
    }

}