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

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.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.order.vo.IotInspectOrderDetailPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.order.vo.IotInspectOrderDetailRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.order.vo.IotInspectOrderDetailSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.stat.DeptUtil;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectOrderDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectOrderDetailDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotcountdata.IotCountDataDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.inspect.IotInspectOrderDetailService;
import cn.iocoder.yudao.module.pms.service.inspect.IotInspectOrderService;
import cn.iocoder.yudao.module.pms.service.inspect.IotInspectOrderServiceImpl;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
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.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
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-order-detail")
@Validated
public class IotInspectOrderDetailController {

    @Resource
    private IotInspectOrderDetailService iotInspectOrderDetailService;
    @Autowired
    private IotInspectOrderServiceImpl iotInspectOrderServiceImpl;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private IotInspectOrderService iotInspectOrderService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private DeptUtil deptUtil;

    @PostMapping("/create")
    @Operation(summary = "创建巡检工单巡检明细")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-order-detail:create')")
    public CommonResult<Long> createIotInspectOrderDetail(@Valid @RequestBody IotInspectOrderDetailSaveReqVO createReqVO) {
        return success(iotInspectOrderDetailService.createIotInspectOrderDetail(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新巡检工单巡检明细")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-order-detail:update')")
    public CommonResult<Boolean> updateIotInspectOrderDetail(@Valid @RequestBody IotInspectOrderDetailSaveReqVO updateReqVO) {
        iotInspectOrderDetailService.updateIotInspectOrderDetail(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除巡检工单巡检明细")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-order-detail:delete')")
    public CommonResult<Boolean> deleteIotInspectOrderDetail(@RequestParam("id") Long id) {
        iotInspectOrderDetailService.deleteIotInspectOrderDetail(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得巡检工单巡检明细")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-order-detail:query')")
    public CommonResult<IotInspectOrderDetailRespVO> getIotInspectOrderDetail(@RequestParam("id") Long id) {
        IotInspectOrderDetailDO iotInspectOrderDetail = iotInspectOrderDetailService.getIotInspectOrderDetail(id);
        return success(BeanUtils.toBean(iotInspectOrderDetail, IotInspectOrderDetailRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得巡检工单巡检明细分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-order-detail:query')")
    public CommonResult<PageResult<IotInspectOrderDetailRespVO>> getIotInspectOrderDetailPage(@Valid IotInspectOrderDetailPageReqVO pageReqVO) {
        PageResult<IotInspectOrderDetailDO> pageResult = iotInspectOrderDetailService.getIotInspectOrderDetailPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotInspectOrderDetailRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出巡检工单巡检明细 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-order-detail:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotInspectOrderDetailExcel(@Valid IotInspectOrderDetailPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotInspectOrderDetailDO> list = iotInspectOrderDetailService.getIotInspectOrderDetailPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "巡检工单巡检明细.xls", "数据", IotInspectOrderDetailRespVO.class,
                        BeanUtils.toBean(list, IotInspectOrderDetailRespVO.class));
    }


    @GetMapping("/status")
    @Operation(summary = "获得巡检项状态数量")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:query')")
    public CommonResult<ImmutableList> getIotInspectItemStatus(IotCountDataDO vo) {
        String companyCode;
        Set<Long> ids = new HashSet<>();
        if (Objects.isNull(vo.getDeptId())){
            Long loginUserDeptId = SecurityFrameworkUtils.getLoginUserDeptId();
            companyCode = deptUtil.getCompanyCode(loginUserDeptId);
            ids = deptUtil.getDeptIds(companyCode);
        } else {
            companyCode = deptUtil.getCompanyCode(vo.getDeptId());
            ids = deptService.getChildDeptIdListFromCache(vo.getDeptId());
            ids.add(vo.getDeptId());
        }
        List<IotInspectOrderDetailDO> all = iotInspectOrderDetailService.getListStat(vo, ids);
        long need = all.stream().filter(e -> Objects.isNull(e.getIfNormal())).count();
        long normal = all.stream().filter(e -> Objects.nonNull(e.getIfNormal())&&e.getIfNormal()).count();
        long exception = all.stream().filter(e -> Objects.nonNull(e.getIfNormal())&&!e.getIfNormal()).count();
        ImmutableMap<String, ? extends Serializable> map = ImmutableMap.of("name", "待填写", "value", need);
        ImmutableMap<String, ? extends Serializable> map1 = ImmutableMap.of("name", "正常", "value", normal);
        ImmutableMap<String, ? extends Serializable> map2 = ImmutableMap.of("name", "异常", "value", exception);
        return success(ImmutableList.of(map,map1,map2));
    }

    @GetMapping("/report/status")
    @Operation(summary = "获得报表的异常点数量")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-inspect-item:query')")
    public CommonResult<ImmutableMap<String, ? extends Serializable>> getIotInspectItemStatusReport(IotCountDataDO vo) {
        Set<Long> ids;
        if (Objects.isNull(vo.getDeptId())){
            Long loginUserDeptId = SecurityFrameworkUtils.getLoginUserDeptId();
            String companyCode = deptUtil.getCompanyCode(loginUserDeptId);
            ids = deptUtil.getDeptIds(companyCode);
        } else {
            ids = deptService.getChildDeptIdListFromCache(vo.getDeptId());
            ids.add(vo.getDeptId());
        }
        Long exceptionReport = iotInspectOrderDetailService.selectExceptionReport(vo, ids);
        ImmutableMap<String, ? extends Serializable> map2 = ImmutableMap.of("name", "异常", "value", exceptionReport);
        return success(map2);
    }

    @GetMapping("/item")
    public CommonResult<PageResult<IotInspectOrderDetailRespVO>> getItemStatus(IotInspectOrderDetailPageReqVO pageReqVO){

        PageResult<IotInspectOrderDetailDO> deviceStatus = iotInspectOrderDetailService.getOrderDetailItem(pageReqVO);
        List<IotInspectOrderDetailRespVO> collect = deviceStatus.getList().stream().map(e -> {
            IotInspectOrderDetailRespVO iotInspectOrderDetailRespVO = new IotInspectOrderDetailRespVO();
            BeanUtils.copyProperties(e, iotInspectOrderDetailRespVO);

            if (Objects.nonNull(e.getDeviceId())) {
                IotDeviceDO iotDevice = iotDeviceService.getIotDevice(e.getDeviceId());
                if (Objects.nonNull(iotDevice)) {
                    iotInspectOrderDetailRespVO.setDeviceCode(iotDevice.getDeviceCode());
                    iotInspectOrderDetailRespVO.setDeviceName(iotDevice.getDeviceName());
                }
            }
            if (Objects.nonNull(e.getOrderId())) {
                IotInspectOrderDO iotInspectOrder = iotInspectOrderService.getIotInspectOrder(e.getOrderId());
                if (Objects.nonNull(iotInspectOrder)) {
                    iotInspectOrderDetailRespVO.setOrderName(iotInspectOrder.getInspectOrderTitle());
                    iotInspectOrderDetailRespVO.setCharge(iotInspectOrder.getChargeName());
                }
            }

            return iotInspectOrderDetailRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, deviceStatus.getTotal()));
    }
}
