package cn.iocoder.yudao.module.pms.controller.admin.maintain.record;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
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.pms.controller.admin.inspect.order.vo.IotInspectOrderRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintain.record.vo.IotJdRecordPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintain.record.vo.IotJdRecordRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintain.record.vo.IotJdRecordSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectOrderDetailDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.maintain.record.IotJdRecordDO;
import cn.iocoder.yudao.module.pms.service.maintain.record.IotJdRecordService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.xingyuv.captcha.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 基地维修记录")
@RestController
@RequestMapping("/rq/iot-jd-record")
@Validated
public class IotJdRecordController {

    @Resource
    private IotJdRecordService iotJdRecordService;
    @Autowired
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建基地维修记录")
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:create')")
    public CommonResult<Long> createIotJdRecord(@Valid @RequestBody IotJdRecordSaveReqVO createReqVO) {
        return success(iotJdRecordService.createIotJdRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新基地维修记录")
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:update')")
    public CommonResult<Boolean> updateIotJdRecord(@Valid @RequestBody IotJdRecordSaveReqVO updateReqVO) {
        iotJdRecordService.updateIotJdRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除基地维修记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:delete')")
    public CommonResult<Boolean> deleteIotJdRecord(@RequestParam("id") Long id) {
        iotJdRecordService.deleteIotJdRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得基地维修记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:query')")
    public CommonResult<IotJdRecordRespVO> getIotJdRecord(@RequestParam("id") Long id) {
        IotJdRecordDO iotJdRecord = iotJdRecordService.getIotJdRecord(id);
        return success(BeanUtils.toBean(iotJdRecord, IotJdRecordRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得基地维修记录分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:query')")
    public CommonResult<PageResult<IotJdRecordRespVO>> getIotJdRecordPage(@Valid IotJdRecordPageReqVO pageReqVO) {
        PageResult<IotJdRecordDO> pageResult = iotJdRecordService.getIotJdRecordPage(pageReqVO);
        List<IotJdRecordRespVO> collect = pageResult.getList().stream().map(e -> {
            IotJdRecordRespVO iotJdRecordRespVO = new IotJdRecordRespVO();
            BeanUtils.copyProperties(e, iotJdRecordRespVO);
            if (StringUtils.isNotBlank(e.getCreator())) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(e.getCreator()));
                if (Objects.nonNull(user)) {
                    iotJdRecordRespVO.setCreateName(user.getNickname());
                }
            }
            return iotJdRecordRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出基地维修记录 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotJdRecordExcel(@Valid IotJdRecordPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotJdRecordDO> list = iotJdRecordService.getIotJdRecordPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "基地维修记录.xls", "数据", IotJdRecordRespVO.class,
                        BeanUtils.toBean(list, IotJdRecordRespVO.class));
    }


    @GetMapping("/repair")
    @Operation(summary = "获取特定维修工单的维修记录")
    @PreAuthorize("@ss.hasPermission('rq:iot-jd-record:query')")
    public CommonResult<List<IotJdRecordRespVO>> getIotJdRecordPage(Long repairId) {
        IotJdRecordPageReqVO pageReqVO = new IotJdRecordPageReqVO();
        pageReqVO.setRepairId(repairId);
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<IotJdRecordDO> iotJdRecordPage = iotJdRecordService.getIotJdRecordPage(pageReqVO);
        List<IotJdRecordRespVO> collect = iotJdRecordPage.getList().stream().map(e -> {
            IotJdRecordRespVO iotJdRecordRespVO = new IotJdRecordRespVO();
            BeanUtils.copyProperties(e, iotJdRecordRespVO);
            if (StringUtils.isNotBlank(e.getCreator())) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(e.getCreator()));
                if (Objects.nonNull(user)) {
                    iotJdRecordRespVO.setCreateName(user.getNickname());
                }
            }
            return iotJdRecordRespVO;
        }).collect(Collectors.toList());
        return success(collect.stream().sorted(Comparator.comparing(IotJdRecordRespVO::getRepairTime)).collect(Collectors.toList()));
    }


    @GetMapping("/assist/{id}")
    @Operation(summary = "获得配合维修的维修人员")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-failure-report:query')")
    public CommonResult<List<AdminUserRespDTO>> getAssistPeople(@PathVariable Long id) {
        List<AdminUserRespDTO> assist = iotJdRecordService.getAssist(id);
        return success(assist);
    }
}
