package cn.iocoder.yudao.module.pms.controller.admin.failure;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.pms.controller.admin.failure.vo.IotFailureReportPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.failure.vo.IotFailureReportProcessVO;
import cn.iocoder.yudao.module.pms.controller.admin.failure.vo.IotFailureReportRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.failure.vo.IotFailureReportSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceperson.vo.IotDevicePersonRelationSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintain.vo.IotMaintainSaveVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotDeviceRespVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.failure.IotFailureReportDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.failure.IotFailureReportService;
import cn.iocoder.yudao.module.pms.service.iotdeviceperson.IotDevicePersonService;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 故障上报")
@RestController
@RequestMapping("/rq/iot-failure-report")
@Validated
public class IotFailureReportController {

    @Resource
    private IotFailureReportService iotFailureReportService;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private BpmProcessInstanceApi bpmProcessInstanceApi;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private IotDevicePersonService iotDevicePersonService;
    @Autowired
    private DictDataService dictDataService;

    @PostMapping("/create")
    @Operation(summary = "创建故障上报")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:create')")
    public CommonResult<Long> createIotFailureReport(@Valid @RequestBody IotFailureReportSaveReqVO createReqVO) {
        return success(iotFailureReportService.createIotFailureReport(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新故障上报")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:update')")
    public CommonResult<Boolean> updateIotFailureReport(@Valid @RequestBody IotFailureReportSaveReqVO updateReqVO) {
        iotFailureReportService.updateIotFailureReport(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除故障上报")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:delete')")
    public CommonResult<Boolean> deleteIotFailureReport(@RequestParam("id") Long id) {
        iotFailureReportService.deleteIotFailureReport(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得故障上报")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:query')")
    public CommonResult<IotFailureReportRespVO> getIotFailureReport(@RequestParam("id") Long id) {
        IotFailureReportDO iotFailureReport = iotFailureReportService.getIotFailureReport(id);
        IotFailureReportRespVO bean = BeanUtils.toBean(iotFailureReport, IotFailureReportRespVO.class);
        if (Objects.nonNull(bean.getApprovalId())) {
            AdminUserRespDTO user = adminUserApi.getUser(bean.getApprovalId());
            bean.setApprovalName(Objects.nonNull(user) ? user.getNickname() : "");
        }
        return success(bean);
    }

    @GetMapping("/page")
    @Operation(summary = "获得故障上报分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:query')")
    public CommonResult<PageResult<IotFailureReportRespVO>> getIotFailureReportPage(@Valid IotFailureReportPageReqVO pageReqVO) {
        PageResult<IotFailureReportDO> pageResult = iotFailureReportService.getIotFailureReportPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotFailureReportRespVO.class));
    }

    @GetMapping("/page/app")
    @Operation(summary = "获得故障上报分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:query')")
    public CommonResult<PageResult<IotFailureReportRespVO>> getIotFailureReportPageApp(@Valid IotFailureReportPageReqVO pageReqVO) {
        PageResult<IotFailureReportDO> pageResult = iotFailureReportService.getIotFailureReportPageApp(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotFailureReportRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出故障上报 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotFailureReportExcel(@Valid IotFailureReportPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotFailureReportDO> list = iotFailureReportService.getIotFailureReportPage(pageReqVO).getList();
        List<DictDataDO> failureStatus = dictDataService.getDictDataListByDictType("pms_failure_status");
        List<DictDataDO> failureType = dictDataService.getDictDataListByDictType("failure_type");
        List<IotFailureReportRespVO> bean = BeanUtils.toBean(list, IotFailureReportRespVO.class);
        bean.forEach(e -> {
            failureStatus.stream().filter(f -> f.getValue().equals(e.getStatus())).findFirst().ifPresent(f -> {
                e.setStatus(f.getLabel());
            });
            if (Objects.nonNull(e.getIfStop())) {
                e.setStop(e.getIfStop()?"是":"否");
            }
            if (Objects.nonNull(e.getIfDeal())) {
                e.setDeal(e.getIfDeal()?"是":"否");
            }
            if (Objects.nonNull(e.getNeedHelp())) {
                e.setIfNeedHelp(e.getNeedHelp()?"是":"否");
            }
            failureType.stream().filter(f -> f.getValue().equals(e.getFailureType())).findFirst().ifPresent(f -> {
                e.setFailureType(f.getLabel());
            });
        });
        // 导出 Excel
        ExcelUtils.write(response, "故障上报.xls", "数据", IotFailureReportRespVO.class,
                        BeanUtils.toBean(bean, IotFailureReportRespVO.class));
    }

    @PutMapping("/submitForApproval")
    @Operation(summary = "提交审核")
    @PreAuthorize("@ss.hasPermission('supplier:base:create')")
    public CommonResult<Boolean> submitForApproval(@RequestParam("id") Long id) {
        iotFailureReportService.submitForApproval(id);
        return success(true);
    }

    @PutMapping("/process-info")
    @Operation(summary = "故障上报更新流程信息")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:create')")
    public CommonResult<String> updateIotFailureReportProcess(@RequestParam("processId") String processId,@RequestParam("id")String id, @RequestParam("type") String type,
                                                            @RequestParam("assigneeUserId") String assigneeUserId,@RequestParam("trans") String trans) {
        IotFailureReportDO failureReport = iotFailureReportService.getIotFailureReport(Long.valueOf(id));
        if (Objects.isNull(failureReport)) {
            throw new ServiceException(666,"无该故障");
        }
        String deviceCompany = iotDeviceService.getDeviceCompany(failureReport.getDeviceId());
        if ("rh".equals(deviceCompany)) {
            IotFailureReportProcessVO iotFailureReportProcessVO = new IotFailureReportProcessVO();
            iotFailureReportProcessVO.setId(id);
            iotFailureReportProcessVO.setType(type);
            iotFailureReportProcessVO.setAssigneeUserId(Long.valueOf(assigneeUserId));
            iotFailureReportService.updateIotFailureReportProcess(iotFailureReportProcessVO);
            return success("完成");
        } else {
            if ("true".equals(trans)) {
                Map<String, Object> params = new HashMap<>();
                params.put("continue", "1");
                bpmProcessInstanceApi.updateProcessVariables(processId, params);
                IotFailureReportProcessVO iotFailureReportProcessVO = new IotFailureReportProcessVO();
                iotFailureReportProcessVO.setId(id);
                iotFailureReportProcessVO.setType(type);
                iotFailureReportProcessVO.setAssigneeUserId(Long.valueOf(assigneeUserId));
                iotFailureReportService.updateIotFailureReportProcess(iotFailureReportProcessVO);
            }
            return success("完成");
        }
    }

    @GetMapping("/get/approval")
    @Operation(summary = "获得故障上报")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:query')")
    public CommonResult<List<AdminUserRespDTO>> getApproval() {
        List<AdminUserRespDTO> approval = iotFailureReportService.getApproval();
        return success(approval);
    }
}
