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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import com.zt.plat.framework.business.annotation.FileUploadController;
import com.zt.plat.framework.business.controller.AbstractFileUploadController;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.framework.excel.core.util.ExcelUtils;
import com.zt.plat.module.qms.core.constant.DataTypeConstant;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceConfigBusinessRulePageReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceConfigBusinessRuleRespVO;
import com.zt.plat.module.qms.resource.device.service.DeviceConfigBusinessRuleService;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialProductPageReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialProductRespVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialProductSaveReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.query.MaterialProductQueryVO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialProductDO;
import com.zt.plat.module.qms.resource.material.service.MaterialProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.zt.plat.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 物料大类")
@RestController
@RequestMapping("/qms/resource/material-product")
@Validated
@FileUploadController(source = "resource.materialproduct", codeKey = "data.fileUploadBusinessCode")
@DeptDataPermissionIgnore(enable = "true")
public class MaterialProductController extends AbstractFileUploadController implements BusinessControllerMarker{

    static {
        FileUploadController annotation = MaterialProductController.class.getAnnotation(FileUploadController.class);
        if (annotation != null) {
        setFileUploadInfo(annotation);
        }
    }

    @Resource private MaterialProductService materialProductService;
    @Resource private DeviceConfigBusinessRuleService deviceConfigBusinessRuleService;


    @PostMapping("/save-category")
    @Operation(summary = "保存分类")
//    @PreAuthorize("@ss.hasPermission('qms:material-product:create-category')")
    public CommonResult<MaterialProductRespVO> saveMaterialCategory(@Valid @RequestBody MaterialProductSaveReqVO createReqVO) {
        return success(materialProductService.saveMaterialCategory(createReqVO));
    }

    @GetMapping("/category-tree")
    @Operation(summary = "获取分类树")
    public CommonResult<List<MaterialProductRespVO>> getMaterialCategoryTree() {
        return success(materialProductService.getMaterialCategoryTree());
    }

    @PostMapping("/save-material")
    @Operation(summary = "保存物料大类")
//    @PreAuthorize("@ss.hasPermission('qms:material-product:create')")
    public CommonResult<MaterialProductRespVO> saveMaterialProduct(@Valid @RequestBody MaterialProductSaveReqVO createReqVO) {
        return success(materialProductService.saveMaterialProduct(createReqVO));
    }

    @GetMapping("/page")
    @Operation(summary = "获得物料大类分页")
//    @PreAuthorize("@ss.hasPermission('qms:material-product:query')")
    public CommonResult<PageResult<MaterialProductRespVO>> getMaterialProductPage(@Valid MaterialProductPageReqVO pageReqVO) {
        PageResult<MaterialProductDO> pageResult = materialProductService.getMaterialProductPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MaterialProductRespVO.class));
    }

    @GetMapping("/inventory-page")
    @Operation(summary = "库存管理页面物料大类分页")
    public CommonResult<PageResult<MaterialProductRespVO>> getMaterialInventoryPage(@Valid MaterialProductPageReqVO pageReqVO) {
        // 需要库存数量和预警信息
        PageResult<MaterialProductRespVO> pageResult = materialProductService.getMaterialInventoryPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("category-data")
    @Operation(summary = "获得物料分类和大类")
    public CommonResult<List<MaterialProductRespVO>> getCategoryAndData(@Valid MaterialProductQueryVO queryVO) {
        return success(materialProductService.getCategoryAndData(queryVO));
    }


//    @PutMapping("/update")
    @Operation(summary = "更新物料")
    @PreAuthorize("@ss.hasPermission('qms:material-product:update')")
    public CommonResult<Boolean> updateMaterialProduct(@Valid @RequestBody MaterialProductSaveReqVO updateReqVO) {
        materialProductService.updateMaterialProduct(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除物料分类或大类")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('qms:material-product:delete')")
    public CommonResult<Boolean> deleteMaterialProduct(@RequestParam("id") Long id) {
        materialProductService.deleteMaterialProduct(id);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得物料")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:material-product:query')")
    public CommonResult<MaterialProductRespVO> getMaterialProduct(@RequestParam("id") Long id) {
        MaterialProductRespVO materialProduct = materialProductService.getMaterialProductInfoWithFiles(id);
        return success(materialProduct);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出物料 Excel")
    @PreAuthorize("@ss.hasPermission('qms:material-product:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMaterialProductExcel(@Valid MaterialProductPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MaterialProductDO> list = materialProductService.getMaterialProductPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "物料大类.xls", "数据", MaterialProductRespVO.class,
                        BeanUtils.toBean(list, MaterialProductRespVO.class));
    }

    /*
    * 查询标准物质的分类树、业务配置状态*/
    @GetMapping("/getProductTreeDataWithRuleStatus")
    @Operation(summary = "获取分类和产品树_含规则配置状态")
    public CommonResult<JSONArray> getProductTreeDataWithRuleStatus() {
        MaterialProductPageReqVO reqVO = new MaterialProductPageReqVO();
        //查询标准物质根分类
        reqVO.setParentId(0L);
        reqVO.setStandardMaterialFlag(1);
        reqVO.setNodeType(DataTypeConstant.DATA_TYPE_CATEGORY);
        List<MaterialProductDO> rootCategoryList = materialProductService.selectListWithCustomSql(reqVO);
        if(rootCategoryList == null ||rootCategoryList.isEmpty())
            return success(new JSONArray());
        reqVO = new MaterialProductPageReqVO();
        reqVO.setRootIdList(rootCategoryList.stream().map(MaterialProductDO::getId).toList());
        List<MaterialProductDO> list = materialProductService.selectListWithCustomSql(reqVO);
        JSONArray jsonArray = new JSONArray();
        for (MaterialProductDO item : list) {
            jsonArray.add(item);
        }
        List<Long> productIdList = list.stream().filter(item -> item.getNodeType().equals(DataTypeConstant.DATA_TYPE_DATA)).map(MaterialProductDO::getId).toList();
        DeviceConfigBusinessRulePageReqVO ruleReqVO = new DeviceConfigBusinessRulePageReqVO();
        ruleReqVO.setProductIdList(productIdList);
        ruleReqVO.setPageNo(1);
        ruleReqVO.setPageSize(-1);
        String[] allDomain = {"dailyCheck","period","maintain","calibration"};
        List<DeviceConfigBusinessRuleRespVO> ruleList = deviceConfigBusinessRuleService.getDeviceConfigBusinessRulePage(ruleReqVO).getList();
        for(MaterialProductDO product: list){
            Long id = product.getId();
            JSONObject jsonObject = jsonArray.getJSONObject(jsonArray.indexOf(product));
            for(String domain: allDomain){
                jsonObject.put(domain + "_on", "0");
                jsonObject.put(domain + "_count", 0);
            }
            for(DeviceConfigBusinessRuleRespVO rule: ruleList){
                Long productId = rule.getProductId();
                String businessDomain = rule.getBusinessDomain();
                if(Objects.equals(productId, id)){
                    jsonObject.put(businessDomain + "_on", "1");
                    jsonObject.put(businessDomain + "_count", rule.getItemCount());
                }
            }
            jsonArray.set(jsonArray.indexOf(product), jsonObject);
        }
        return success(jsonArray);
    }

}