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

import com.alibaba.fastjson.JSON;
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.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceInfomationPageReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceInfomationRespVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceInfomationSaveReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceInfomationWithProductVO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceInfoWithBizConfigVO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceInfomationDO;
import com.zt.plat.module.qms.resource.device.service.DeviceInfomationService;
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.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

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-infomation")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "resource.deviceinfomation")
public class DeviceInfomationController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource private DeviceInfomationService deviceInfomationService;
    @Resource private DeviceProductService deviceProductService;
    @Resource private BusinessFileService businessFileService;


    /**
     * 更新设备状态
     * 参数举例：
     *  维修：{"deviceId": "XX","bizType": "Accept","switchState": "1"}
     *  维修完成：{"deviceId": "XX","bizType": "Accept","switchState": "0"}
     *  验收：{"deviceId": "XX","bizType": "Accept","switchState": "1"}
     *  取消验收：{"deviceId": "XX","bizType": "Accept","switchState": "0"}
     *  启用：{"deviceId": "XX","bizType": "Enable","switchState": "1"}
     *  停用：{"deviceId": "XX","bizType": "Enable","switchState": "0"}
     *  降级：{"deviceId": "XX","bizType": "Demote","switchState": "1"}
     *  （降级）还原：{"deviceId": "XX","bizType": "Demote","switchState": "0"}
     *  报废：{"deviceId": "XX","bizType": "Scrap","switchState": "1"}
     *  （报废）还原：{"deviceId": "XX","bizType": "Scrap","switchState": "0"}
     * */
    @PostMapping("/updateDeviceStatus")
    @Operation(summary = "更新设备状态")
    public CommonResult<DeviceInfomationRespVO> updateDeviceStatus(@RequestBody JSONObject param) {
        return deviceInfomationService.updateDeviceStatus(param);
    }

    @PostMapping("/saveDevice")
    @Operation(summary = "创建设备-设备信息")
//    @PreAuthorize("@ss.hasPermission('resource:device-infomation:create')")
    public CommonResult<DeviceInfomationRespVO> saveDevice(@Valid @RequestBody DeviceInfomationSaveReqVO reqVO) {
        return deviceInfomationService.saveDevice(reqVO);
    }

    @PostMapping("/create")
    @Operation(summary = "创建设备-设备信息")
    @PreAuthorize("@ss.hasPermission('resource:device-infomation:create')")
    public CommonResult<DeviceInfomationRespVO> createDeviceInfomation(@Valid @RequestBody DeviceInfomationSaveReqVO createReqVO) {
        return success(deviceInfomationService.createDeviceInfomation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-设备信息")
    @PreAuthorize("@ss.hasPermission('resource:device-infomation:update')")
    public CommonResult<DeviceInfomationRespVO> updateDeviceInfomation(@Valid @RequestBody DeviceInfomationSaveReqVO updateReqVO) {
        DeviceInfomationDO entity = deviceInfomationService.updateDeviceInfomation(updateReqVO);
        return success(BeanUtils.toBean(entity, DeviceInfomationRespVO.class));
    }

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

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

    @GetMapping("/get")
    @Operation(summary = "获得设备-设备信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeviceInfomationWithProductVO> getDeviceInfomation(@RequestParam("id") Long id) {
        DeviceInfomationWithProductVO vo = deviceInfomationService.getDeviceWithProduct(id);
        String customConfig = vo.getCustomConfig();
        if(!ObjectUtils.isEmpty(customConfig)){
            try{
                vo.setCustomConfigJson(JSON.parseObject(customConfig));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return success(vo);
    }


    @GetMapping("/page")
    @Operation(summary = "获得设备-设备信息分页")
    public CommonResult<PageResult<DeviceInfomationWithProductVO>> getDeviceInfomationPage(@Valid DeviceInfomationPageReqVO pageReqVO) {
        Long productId = pageReqVO.getProductId();
        if(productId != null){
            List<Long> productIds = deviceProductService.getIdListByIdPath(productId);
            if(!productIds.isEmpty()){
                pageReqVO.setProductIds(productIds);
                pageReqVO.setProductId(null);
            }
        }
        String deviceStatus = pageReqVO.getDeviceStatus();
        if("0".equals(deviceStatus))
            deviceStatus = "{\"Enable\":\"1\"}";
        if(!ObjectUtils.isEmpty(deviceStatus))
            pageReqVO.setDeviceStatusJson(JSON.parseObject(deviceStatus));
        PageResult<DeviceInfomationWithProductVO> pageResult = deviceInfomationService.getDeviceInfomationPage(pageReqVO);

        List<DeviceInfomationWithProductVO> list = pageResult.getList();
        for(DeviceInfomationWithProductVO vo : list){
            String customConfig = vo.getCustomConfig();
            if(!ObjectUtils.isEmpty(customConfig)){
                try{
                    vo.setCustomConfigJson(JSON.parseObject(customConfig));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备-设备信息 Excel")
    @PreAuthorize("@ss.hasPermission('resource:device-infomation:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceInfomationExcel(@Valid DeviceInfomationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DeviceInfomationWithProductVO> list = deviceInfomationService.getDeviceInfomationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备-设备信息.xls", "数据", DeviceInfomationRespVO.class,
                        BeanUtils.toBean(list, DeviceInfomationRespVO.class));
    }

    @GetMapping("/test")
    @Operation(summary = "获得设备-设备信息分页")
    public CommonResult<List<DeviceInfoWithBizConfigVO>> test() {
        JSONObject params = new JSONObject();
        Long deviceId = 2010903332962000897L;
        params.put("businessType", "dailyCheck");
        params.put("deviceId", deviceId);
        List<DeviceInfoWithBizConfigVO> list = deviceInfomationService.getListNeedByRule(params);
        return success(list);
    }

}