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

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.information.vo.IotInformationDbRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.item.vo.IotInspectItemPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.item.vo.IotInspectItemRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.item.vo.IotInspectItemSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotProductClassifyDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectItemDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.IotProductClassifyService;
import cn.iocoder.yudao.module.pms.service.inspect.IotInspectItemService;
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 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.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

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-item")
@Validated
public class IotInspectItemController {

    @Resource
    private IotInspectItemService iotInspectItemService;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private IotProductClassifyService iotProductClassifyService;
    @Autowired
    private DeptApi deptApi;

    @PostMapping("/create")
    @Operation(summary = "创建巡检项")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:create')")
    public CommonResult<Long> createIotInspectItem(@Valid @RequestBody IotInspectItemSaveReqVO createReqVO) {
        return success(iotInspectItemService.createIotInspectItem(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新巡检项")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:update')")
    public CommonResult<Boolean> updateIotInspectItem(@Valid @RequestBody IotInspectItemSaveReqVO updateReqVO) {
        iotInspectItemService.updateIotInspectItem(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得巡检项")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:query')")
    public CommonResult<IotInspectItemRespVO> getIotInspectItem(@RequestParam("id") Long id) {
        IotInspectItemDO iotInspectItem = iotInspectItemService.getIotInspectItem(id);
        return success(BeanUtils.toBean(iotInspectItem, IotInspectItemRespVO.class));
    }


    @GetMapping("/page")
    @Operation(summary = "获得巡检项分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:query')")
    public CommonResult<PageResult<IotInspectItemRespVO>> getIotInspectItemPage(@Valid IotInspectItemPageReqVO pageReqVO) {
        PageResult<IotInspectItemDO> pageResult = iotInspectItemService.getIotInspectItemPage(pageReqVO);
        pageResult.getList().forEach(item->{
            if (Objects.nonNull(item.getCreator())) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(item.getCreator()));
                if (Objects.nonNull(user)) {
                    item.setCreateName(user.getNickname());
                }
            }
        });
        return success(BeanUtils.toBean(pageResult, IotInspectItemRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出巡检项 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotInspectItemExcel(@Valid IotInspectItemPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotInspectItemDO> list = iotInspectItemService.getIotInspectItemPage(pageReqVO).getList();
        List<IotInspectItemRespVO> bean = BeanUtils.toBean(list, IotInspectItemRespVO.class);
        List<AdminUserRespDTO> allUser = adminUserApi.getAllUser();
        List<DeptRespDTO> deptList = deptApi.getDeptList();
        bean.forEach(e ->{
            IotProductClassifyDO iotProductClassify = iotProductClassifyService.getIotProductClassify(e.getDeviceClassify());
            if (Objects.nonNull(iotProductClassify)) {
                e.setDeviceClassifyName(iotProductClassify.getName());
            }
            allUser.stream().filter(f -> String.valueOf(f.getId()).equals(e.getCreator())).findFirst().ifPresent(f -> {
                e.setCreateName(f.getNickname());
            });
            deptList.stream().filter(f -> f.getId().equals(e.getDeptId())).findFirst().ifPresent(f -> {
                e.setDeptName(f.getName());
            });
        });
        // 导出 Excel
        ExcelUtils.write(response, "巡检项.xls", "数据", IotInspectItemRespVO.class,
                        BeanUtils.toBean(bean, IotInspectItemRespVO.class));
    }

    @GetMapping("/init/item")
    @PermitAll
    public void initCode(){
        IotInspectItemPageReqVO iotInspectItemPageReqVO = new IotInspectItemPageReqVO();
        iotInspectItemPageReqVO.setPageNo(1);
        iotInspectItemPageReqVO.setPageSize(2000);
        PageResult<IotInspectItemDO> iotInspectItemPage = iotInspectItemService.getIotInspectItemPage(iotInspectItemPageReqVO);
        List<IotInspectItemDO> list = iotInspectItemPage.getList();
        list.stream().filter(e-> Objects.nonNull(e.getDeviceId())).forEach(f->{
            IotDeviceDO iotDevice = iotDeviceService.getIotDevice(f.getDeviceId());
            if (Objects.nonNull(iotDevice)) {
                f.setDeviceCode(iotDevice.getDeviceCode());
                IotInspectItemSaveReqVO bean = BeanUtils.toBean(f, IotInspectItemSaveReqVO.class);
                iotInspectItemService.updateIotInspectItem(bean);

            }
        });
    }
}
