package cn.iocoder.yudao.module.pms.controller.admin.inspect.plan;

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.plan.vo.IotInspectPlanPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.plan.vo.IotInspectPlanRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.plan.vo.IotInspectPlanSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectPlanDO;
import cn.iocoder.yudao.module.pms.service.inspect.IotInspectPlanService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
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.controller.admin.user.vo.user.UserUpdateStatusReqVO;
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.List;
import java.util.Objects;
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-inspect-plan")
@Validated
public class IotInspectPlanController {

    @Resource
    private IotInspectPlanService iotInspectPlanService;
    @Resource
    private AdminUserApi adminUserApi;
    @Autowired
    private DeptApi deptApi;

    @PostMapping("/create")
    @Operation(summary = "创建巡检计划")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-plan:create')")
    public CommonResult<Long> createIotInspectPlan(@Valid @RequestBody IotInspectPlanSaveReqVO createReqVO) {
        return success(iotInspectPlanService.createIotInspectPlan(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新巡检计划")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-plan:update')")
    public CommonResult<Boolean> updateIotInspectPlan(@Valid @RequestBody IotInspectPlanSaveReqVO updateReqVO) {
        iotInspectPlanService.updateIotInspectPlan(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得巡检计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-plan:query')")
    public CommonResult<IotInspectPlanRespVO> getIotInspectPlan(@RequestParam("id") Long id) {
        IotInspectPlanDO iotInspectPlan = iotInspectPlanService.getIotInspectPlan(id);
        IotInspectPlanRespVO bean = BeanUtils.toBean(iotInspectPlan, IotInspectPlanRespVO.class);
//        bean.setCharges(Arrays.asList(iotInspectPlan.getCharge().split(",")));
        return success(bean);
    }

    @GetMapping("/page")
    @Operation(summary = "获得巡检计划分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-plan:query')")
    public CommonResult<PageResult<IotInspectPlanRespVO>> getIotInspectPlanPage(@Valid IotInspectPlanPageReqVO pageReqVO) {
        PageResult<IotInspectPlanDO> pageResult = iotInspectPlanService.getIotInspectPlanPage(pageReqVO);
        List<IotInspectPlanRespVO> collect = pageResult.getList().stream().map(e -> {
            IotInspectPlanRespVO iotInspectPlanRespVO = new IotInspectPlanRespVO();
            BeanUtils.copyProperties(e, iotInspectPlanRespVO);
            if (StringUtils.isNotBlank(e.getCreator())) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(e.getCreator()));
                if (Objects.nonNull(user)) {
                    iotInspectPlanRespVO.setCreateName(user.getNickname());
                    if (Objects.nonNull(user.getDeptId())) {
                        DeptRespDTO dept = deptApi.getDept(user.getDeptId());
                        iotInspectPlanRespVO.setDeptName(Objects.nonNull(dept)?dept.getName():"");
                    }
                }
            }
            return iotInspectPlanRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出巡检计划 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-plan:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotInspectPlanExcel(@Valid IotInspectPlanPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotInspectPlanDO> list = iotInspectPlanService.getIotInspectPlanPage(pageReqVO).getList();
        List<IotInspectPlanRespVO> bean = BeanUtils.toBean(list, IotInspectPlanRespVO.class);
        List<DeptRespDTO> deptList = deptApi.getDeptList();
        bean.forEach(e -> {
            deptList.stream().filter(f -> f.getId().equals(e.getDeptId())).findFirst().ifPresent(f -> {
                e.setDeptName(f.getName());
            });
        });
        // 导出 Excel
        ExcelUtils.write(response, "巡检计划.xls", "数据", IotInspectPlanRespVO.class,
                        BeanUtils.toBean(bean, IotInspectPlanRespVO.class));
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改巡检计划状态")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-plan:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        iotInspectPlanService.updateInspectPlanStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }
}
