package cn.iocoder.yudao.module.smartfactory.controller.admin.factoryinfo;

import cn.hutool.core.collection.CollUtil;
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.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.smartfactory.controller.admin.factoryinfo.vo.*;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.factoryinfo.FactoryInfoDO;
import cn.iocoder.yudao.module.smartfactory.service.factoryinfo.FactoryInfoService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 工厂信息")
@RestController
@RequestMapping("/smartfactory/factory-info")
@Validated
public class FactoryInfoController {

    @Resource
    private FactoryInfoService factoryInfoService;

    @Resource
    private DeptApi deptApi;

    @PostMapping("/create")
    @Operation(summary = "创建工厂信息")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:create')")
    public CommonResult<Long> createFactoryInfo(@Valid @RequestBody FactoryInfoSaveReqVO createReqVO) {
        return success(factoryInfoService.createFactoryInfo(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工厂信息")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:update')")
    public CommonResult<Boolean> updateFactoryInfo(@Valid @RequestBody FactoryInfoSaveReqVO updateReqVO) {
        factoryInfoService.updateFactoryInfo(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新设备-工厂状态")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:update')")
    public CommonResult<Boolean> updateCameraDevice(@Valid @RequestBody FactoryUpdateStatusReqVO updateReqVO) {

        factoryInfoService.updateFactoryStatus(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工厂信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:delete')")
    public CommonResult<Boolean> deleteFactoryInfo(@RequestParam("id") Long id) {
        factoryInfoService.deleteFactoryInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工厂信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:query')")
    public CommonResult<FactoryInfoRespVO> getFactoryInfo(@RequestParam("id") Long id) {

        FactoryInfoDO factoryInfo = factoryInfoService.getFactoryInfo(id);
        FactoryInfoRespVO respVO = BeanUtils.toBean(factoryInfo, FactoryInfoRespVO.class);

        // 获取部门信息
        DeptRespDTO respDTO = deptApi.getDeptByFactoryId(factoryInfo.getId()).getCheckedData();
        if (respDTO != null) {
            // 设置负责人信息
            respVO.setLeaderUserId(respDTO.getLeaderUserId());
        }

        return success(respVO);
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得工厂列表 | 用于前端下拉框")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:query')")
    public CommonResult<List<FactorySimpleRespVO>> getFactoryList() {

        List<FactoryInfoDO> factoryInfo = factoryInfoService.getFactoryListByType();
        return success(BeanUtils.toBean(factoryInfo, FactorySimpleRespVO.class));
    }

    @GetMapping("/simple-list-authority")
    @Operation(summary = "获得工厂列表(权限检验) | 用于前端下拉框")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:query')")
    public CommonResult<List<FactorySimpleRespVO>> getFactoryListByAuthority() {

        List<FactoryInfoDO> factoryInfo = factoryInfoService.getFactoryListByAuthority();
        return success(BeanUtils.toBean(factoryInfo, FactorySimpleRespVO.class));
    }

    @GetMapping("/get-tree")
    @Operation(summary = "获得工厂树结构")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:query')")
    public CommonResult<FactoryTreeRespVO> getFactoryTree() {

        FactoryTreeRespVO data = new FactoryTreeRespVO();
        List<FactorySimpleRespVO> info = new ArrayList<>();

        List<FactoryInfoDO> factoryInfo = factoryInfoService.getFactoryList();
        if (!CollUtil.isEmpty(factoryInfo)) {

            Map<String, List<FactoryInfoDO>> infoDOMap = factoryInfo.stream().collect(Collectors.groupingBy(FactoryInfoDO::getType));
            for (String key : infoDOMap.keySet()) {

                switch (key) {
                    case "1":
                        data = BeanUtils.toBean(infoDOMap.get(key).get(0), FactoryTreeRespVO.class);
                        break;
                    case "2":
                        info.addAll(0, BeanUtils.toBean(infoDOMap.get(key), FactorySimpleRespVO.class));
                        break;
                    case "3":
                        info.addAll(BeanUtils.toBean(infoDOMap.get(key), FactorySimpleRespVO.class));
                        break;
                }
            }
            data.setSubsidiary(info);
        }

        return success(data);
    }

    @GetMapping("/page")
    @Operation(summary = "获得工厂信息分页")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:query')")
    public CommonResult<PageResult<FactoryInfoRespVO>> getFactoryInfoPage(@Valid FactoryInfoPageReqVO pageReqVO) {
        PageResult<FactoryInfoDO> pageResult = factoryInfoService.getFactoryInfoPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, FactoryInfoRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工厂信息 Excel")
    @PreAuthorize("@ss.hasPermission('smartfactory:factory-info:export')")
    @OperateLog(type = EXPORT)
    public void exportFactoryInfoExcel(@Valid FactoryInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<FactoryInfoDO> list = factoryInfoService.getFactoryInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "工厂信息.xls", "数据", FactoryInfoRespVO.class,
                        BeanUtils.toBean(list, FactoryInfoRespVO.class));
    }
}