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

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.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceperson.vo.IotDevicePersonPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceperson.vo.IotDevicePersonRelationSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceperson.vo.IotDevicePersonRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceperson.vo.IotDevicePersonSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotdeviceperson.IotDevicePersonDO;
import cn.iocoder.yudao.module.pms.service.iotdeviceperson.IotDevicePersonService;
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.ArrayList;
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("/pms/iot-device-person")
@Validated
public class IotDevicePersonController {

    @Resource
    private IotDevicePersonService iotDevicePersonService;
    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建设备负责人分配")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:create')")
    public CommonResult<Long> createIotDevicePerson(@Valid @RequestBody IotDevicePersonSaveReqVO createReqVO) {
        return success(iotDevicePersonService.createIotDevicePerson(createReqVO));
    }

    @PostMapping("/saveDevicePersons")
    @Operation(summary = "保存 设备与人员 的关联关系")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:create')")
    public CommonResult<Long> saveDevicePersonRelation(@Valid @RequestBody List<IotDevicePersonRelationSaveReqVO> reqVOS) {
        return success(iotDevicePersonService.saveDevicePersons(reqVOS));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备负责人分配")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:update')")
    public CommonResult<Boolean> updateIotDevicePerson(@Valid @RequestBody IotDevicePersonSaveReqVO updateReqVO) {
        iotDevicePersonService.updateIotDevicePerson(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备负责人分配")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:delete')")
    public CommonResult<Boolean> deleteIotDevicePerson(@RequestParam("id") Long id) {
        iotDevicePersonService.deleteIotDevicePerson(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备负责人分配")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:query')")
    public CommonResult<IotDevicePersonRespVO> getIotDevicePerson(@RequestParam("id") Long id) {
        IotDevicePersonDO iotDevicePerson = iotDevicePersonService.getIotDevicePerson(id);
        return success(BeanUtils.toBean(iotDevicePerson, IotDevicePersonRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备负责人分配分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:query')")
    public CommonResult<PageResult<IotDevicePersonRespVO>> getIotDevicePersonPage(@Valid IotDevicePersonPageReqVO pageReqVO) {
        PageResult<IotDevicePersonDO> pageResult = iotDevicePersonService.getIotDevicePersonPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotDevicePersonRespVO.class));
    }

    @GetMapping("/getPersonsByDeviceIds")
    @Operation(summary = "根据设备id集合查询设备的负责人列表")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:query')")
    public CommonResult<List<IotDevicePersonRespVO>> getPersonsByDeviceIds(@Valid IotDevicePersonPageReqVO pageReqVO) {
        List<IotDevicePersonDO> persons = iotDevicePersonService.getPersonsByDeviceIds(pageReqVO);
        return success(new ArrayList<>(buildDevicePersonList(persons)));
    }

    private List<IotDevicePersonRespVO> buildDevicePersonList(List<IotDevicePersonDO> persons) {
        if (CollUtil.isEmpty(persons)) {
            return Collections.emptyList();
        }
        // 查询设备 负责人 对应名称
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertListByFlatMap(persons,
                person -> Stream.of(person.getPersonId())));
        // 2. 转换成 VO
        return BeanUtils.toBean(persons, IotDevicePersonRespVO.class, personVO -> {
            // 2.2 设置创建人、负责人名称
            MapUtils.findAndThen(userMap, personVO.getPersonId(), user -> personVO.setPersonName(user.getNickname()));
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备负责人分配 Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotDevicePersonExcel(@Valid IotDevicePersonPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotDevicePersonDO> list = iotDevicePersonService.getIotDevicePersonPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备负责人分配.xls", "数据", IotDevicePersonRespVO.class,
                        BeanUtils.toBean(list, IotDevicePersonRespVO.class));
    }

    @GetMapping("/if/duty/{id}")
    @Operation(summary = "是否责任人")
    public CommonResult<Long> ifDuty(@PathVariable("id") Long id) {
        IotDevicePersonPageReqVO pageReqVO = new IotDevicePersonPageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        pageReqVO.setPersonId(id);
        PageResult<IotDevicePersonDO> iotDevicePersonPage = iotDevicePersonService.getIotDevicePersonPage(pageReqVO);
        if (CollUtil.isNotEmpty(iotDevicePersonPage.getList())) {
            return success(1L);
        }
        return success(-1L);
    }
}
