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

import cn.hutool.core.collection.CollUtil;
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.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
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.maintenance.vo.IotMaintenancePlanPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintenance.vo.IotMaintenancePlanRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintenance.vo.IotMaintenancePlanSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.maintenance.vo.IotMaintenanceSaveVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.maintenance.IotMaintenancePlanDO;
import cn.iocoder.yudao.module.pms.service.maintenance.IotMaintenancePlanService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
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.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.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

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


@Tag(name = "管理后台 - 保养计划")
@RestController
@RequestMapping("/rq/iot-maintenance-plan")
@Validated
public class IotMaintenancePlanController {

    @Resource
    private IotMaintenancePlanService iotMaintenancePlanService;
    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建保养计划")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:create')")
    public CommonResult<Long> createIotMaintenancePlan(@Valid @RequestBody IotMaintenanceSaveVO createReqVO) {
        return success(iotMaintenancePlanService.createIotMaintenancePlan(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新保养计划")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:update')")
    public CommonResult<Boolean> updateIotMaintenancePlan(@Valid @RequestBody IotMaintenancePlanSaveReqVO updateReqVO) {
        iotMaintenancePlanService.updateIotMaintenancePlan(updateReqVO);
        return success(true);
    }

    @PostMapping("/updatePlan")
    @Operation(summary = "修改保养计划 主表+明细")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:update')")
    public CommonResult<Long> updatePlan(@Valid @RequestBody IotMaintenanceSaveVO updateReqVO) {
        return success(iotMaintenancePlanService.updatePlan(updateReqVO));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除保养计划")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:delete')")
    public CommonResult<Boolean> deleteIotMaintenancePlan(@RequestParam("id") Long id) {
        iotMaintenancePlanService.deleteIotMaintenancePlan(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得保养计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:query')")
    public CommonResult<IotMaintenancePlanRespVO> getIotMaintenancePlan(@RequestParam("id") Long id) {
        IotMaintenancePlanDO iotMaintenancePlan = iotMaintenancePlanService.getIotMaintenancePlan(id);
        return success(BeanUtils.toBean(iotMaintenancePlan, IotMaintenancePlanRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得保养计划分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:query')")
    public CommonResult<PageResult<IotMaintenancePlanRespVO>> getIotMaintenancePlanPage(@Valid IotMaintenancePlanPageReqVO pageReqVO) {
        PageResult<IotMaintenancePlanDO> pageResult = iotMaintenancePlanService.getIotMaintenancePlanPage(pageReqVO);
        return success(new PageResult<>(buildMaintenancePlanList(pageResult.getList()), pageResult.getTotal()));
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改保养计划状态")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:update')")
    public CommonResult<Boolean> updatePlanStatus(@Valid @RequestBody IotMaintenancePlanSaveReqVO reqVO) {
        iotMaintenancePlanService.updatePlanStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出保养计划 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-maintenance-plan:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotMaintenancePlanExcel(@Valid IotMaintenancePlanPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotMaintenancePlanDO> list = iotMaintenancePlanService.getIotMaintenancePlanPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "保养计划.xls", "数据", IotMaintenancePlanRespVO.class,
                        BeanUtils.toBean(list, IotMaintenancePlanRespVO.class));
    }

    private List<IotMaintenancePlanRespVO> buildMaintenancePlanList(List<IotMaintenancePlanDO> plans) {
        if (CollUtil.isEmpty(plans)) {
            return Collections.emptyList();
        }
        // 查询保养计划 负责人
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertListByFlatMap(plans,
                plan -> Stream.of(NumberUtils.parseLong(plan.getResponsiblePerson()))));
        // 2. 转换成 VO
        return BeanUtils.toBean(plans, IotMaintenancePlanRespVO.class, planVO -> {
            // 2.2 设置创建人、负责人名称
            MapUtils.findAndThen(userMap, NumberUtils.parseLong(planVO.getResponsiblePerson()),
                    user -> planVO.setResponsiblePersonName(user.getNickname()));
        });
    }

}
