package com.zt.plat.module.qms.resource.device.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.DeviceProductPageReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceProductRespVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceProductSaveReqVO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceConfigBusinessRuleDO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceProductDO;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.service.DeviceConfigBusinessRuleService;
import com.zt.plat.module.qms.resource.device.service.DeviceProductService;
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 java.util.stream.Collectors;

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/device-product")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "resource.deviceproduct")
public class DeviceProductController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource private DeviceProductService deviceProductService;
    @Resource private DeviceConfigBusinessRuleService deviceConfigBusinessRuleService;

    @PostMapping("/saveData")
    @Operation(summary = "保存数据")
    public CommonResult<DeviceProductRespVO> saveData(@Valid @RequestBody DeviceProductSaveReqVO createReqVO) {
        return deviceProductService.saveData(createReqVO);
    }

    @PostMapping("/saveClassify")
    @Operation(summary = "保存分类")
    public CommonResult<DeviceProductRespVO> saveClassify(@Valid @RequestBody DeviceProductSaveReqVO createReqVO) {
        return deviceProductService.saveCategory(createReqVO);
    }

    @GetMapping("/getTreeData")
    @Operation(summary = "查询分类树")
    public CommonResult<List<DeviceProductRespVO>> getTreeData() {
        List<DeviceProductDO> list = deviceProductService.getTreeData(DataTypeConstant.DATA_TYPE_CATEGORY);
        return success(BeanUtils.toBean(list, DeviceProductRespVO.class));
    }

    @GetMapping("/getProductTreeData")
    @Operation(summary = "获取分类和产品树")
    public CommonResult<List<DeviceProductRespVO>> getProductTreeData() {
        List<DeviceProductDO> list = deviceProductService.getTreeData("");
        return success(BeanUtils.toBean(list, DeviceProductRespVO.class));
    }

    @GetMapping("/getProductTreeDataWithRuleStatus")
    @Operation(summary = "获取分类和产品树_含规则配置状态")
    public CommonResult<JSONArray> getProductTreeDataWithRuleStatus() {
        List<DeviceProductDO> list = deviceProductService.getTreeData("");
        JSONArray jsonArray = new JSONArray();
        for (DeviceProductDO item : list) {
            jsonArray.add(item);
        }

        List<Long> productIdList = list.stream().filter(item -> item.getNodeType().equals(DataTypeConstant.DATA_TYPE_DATA)).map(DeviceProductDO::getId).toList();
        DeviceConfigBusinessRulePageReqVO reqVO = new DeviceConfigBusinessRulePageReqVO();
        reqVO.setProductIdList(productIdList);
        reqVO.setPageNo(1);
        reqVO.setPageSize(-1);
        String[] allDomain = {"dailyCheck","period","maintain","calibration"};
        List<DeviceConfigBusinessRuleRespVO> ruleList = deviceConfigBusinessRuleService.getDeviceConfigBusinessRulePage(reqVO).getList();
        for(DeviceProductDO 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);
    }


    @PostMapping("/create")
    @Operation(summary = "创建设备-设备大类")
    @PreAuthorize("@ss.hasPermission('resource:device-product:create')")
    public CommonResult<DeviceProductRespVO> createDeviceProduct(@Valid @RequestBody DeviceProductSaveReqVO createReqVO) {
        return success(deviceProductService.createDeviceProduct(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-设备大类")
    @PreAuthorize("@ss.hasPermission('resource:device-product:update')")
    public CommonResult<Boolean> updateDeviceProduct(@Valid @RequestBody DeviceProductSaveReqVO updateReqVO) {
        deviceProductService.updateDeviceProduct(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备-设备大类")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('resource:device-product:delete')")
    public CommonResult<Boolean> deleteDeviceProduct(@RequestParam("id") Long id) {
        deviceProductService.deleteDeviceProduct(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除设备-设备大类")
                @PreAuthorize("@ss.hasPermission('resource:device-product:delete')")
    public CommonResult<Boolean> deleteDeviceProductList(@RequestBody BatchDeleteReqVO req) {
        deviceProductService.deleteDeviceProductListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备-设备大类")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('resource:device-product:query')")
    public CommonResult<DeviceProductRespVO> getDeviceProduct(@RequestParam("id") Long id) {
        DeviceProductDO deviceProduct = deviceProductService.getDeviceProduct(id);
        return success(BeanUtils.toBean(deviceProduct, DeviceProductRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备-设备大类分页")
//    @PreAuthorize("@ss.hasPermission('resource:device-product:query')")
    public CommonResult<PageResult<DeviceProductRespVO>> getDeviceProductPage(@Valid DeviceProductPageReqVO pageReqVO) {
        PageResult<DeviceProductDO> pageResult = deviceProductService.getDeviceProductPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DeviceProductRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备-设备大类 Excel")
    @PreAuthorize("@ss.hasPermission('resource:device-product:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceProductExcel(@Valid DeviceProductPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DeviceProductDO> list = deviceProductService.getDeviceProductPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备-设备大类.xls", "数据", DeviceProductRespVO.class,
                        BeanUtils.toBean(list, DeviceProductRespVO.class));
    }

}