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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
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.iotprojectinfo.vo.IotProjectInfoPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotprojectinfo.vo.IotProjectInfoRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotprojectinfo.vo.IotProjectSaveVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotprojectinfo.IotProjectInfoDO;
import cn.iocoder.yudao.module.pms.service.iotprojectinfo.IotProjectInfoService;
import cn.iocoder.yudao.module.pms.service.iotprojecttask.IotProjectTaskService;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
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.*;

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-project-info")
@Validated
public class IotProjectInfoController {

    @Resource
    private IotProjectInfoService iotProjectInfoService;
    @Resource
    private IotProjectTaskService iotProjectTaskService;
    @Resource
    private DeptService deptService;
    @Resource
    private DictDataService dictDataService;

    @PostMapping("/create")
    @Operation(summary = "创建项目信息")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:create')")
    public CommonResult<Long> createIotProjectInfo(@RequestBody IotProjectSaveVO createReqVO) {
        Long id = iotProjectInfoService.createIotProjectInfo(createReqVO.getProjectData());
        /*List<IotProjectTaskSaveReqVO> taskList = createReqVO.getTaskList();
        for (IotProjectTaskSaveReqVO saveReqVO:taskList) {
            saveReqVO.setProjectId(id);
        }
        Boolean a = iotProjectTaskService.createIotProjectTaskList(taskList);*/
        return success(id);
    }

    @PutMapping("/update")
    @Operation(summary = "更新项目信息")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:update')")
    public CommonResult<Boolean> updateIotProjectInfo(@RequestBody IotProjectSaveVO updateReqVO) {
        iotProjectInfoService.updateIotProjectInfo(updateReqVO.getProjectData());
        //iotProjectTaskService.updateIotProjectTaskList(updateReqVO.getTaskList());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除项目信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:delete')")
    public CommonResult<Boolean> deleteIotProjectInfo(@RequestParam("id") Long id) {
        iotProjectInfoService.deleteIotProjectInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得项目信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:query')")
    public CommonResult<IotProjectInfoRespVO> getIotProjectInfo(@RequestParam("id") Long id) {
        IotProjectInfoDO iotProjectInfo = iotProjectInfoService.getIotProjectInfo(id);
        return success(BeanUtils.toBean(iotProjectInfo, IotProjectInfoRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得项目信息分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:query')")
    public CommonResult<PageResult<IotProjectInfoRespVO>> getIotProjectInfoPage(@Valid IotProjectInfoPageReqVO pageReqVO) {

        Set<Long> idList = new HashSet<>();
        /* if(Objects.nonNull(pageReqVO.getDeptId())){
            idList =  deptService.getChildDeptIdListFromCache(pageReqVO.getDeptId());
            idList.add(pageReqVO.getDeptId());
        } */

        PageResult<IotProjectInfoDO> pageResult = iotProjectInfoService.getIotProjectInfoPage1(pageReqVO, idList);
        return success(BeanUtils.toBean(pageResult, IotProjectInfoRespVO.class));
    }

    @GetMapping("/projectList")
    @Operation(summary = "根据用户获得项目信息")
    @Parameter(name = "deptId", description = "登录人组织ID", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:query')")
    public CommonResult<List<IotProjectInfoRespVO>> getProjectList(@RequestParam("deptId") Long deptId) {
        List<IotProjectInfoDO> pageResult = iotProjectInfoService.projectList();
        return success(BeanUtils.toBean(pageResult, IotProjectInfoRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出项目信息列表 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotProjectInfoExcel(@Valid IotProjectInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        Set<Long> idList = new HashSet<>();

        List<IotProjectInfoDO> projectInfos = iotProjectInfoService.getIotProjectInfoPage1(pageReqVO, idList).getList();
        // 设置 结算方式
        List<IotProjectInfoRespVO> projects = BeanUtils.toBean(projectInfos, IotProjectInfoRespVO.class);
        // key施工状态数据字典value   value施工状态数据字典label
        Map<String, String> methodPair = new HashMap<>();
        // 施工状态 字典数据
        List<DictDataDO> methodData = dictDataService.getDictDataListByDictType("rq_iot_project_settlement_method");
        if (CollUtil.isNotEmpty(methodData)) {
            methodData.forEach(data -> {
                methodPair.put(data.getValue(), data.getLabel());
            });
        }
        if (CollUtil.isNotEmpty(projects)) {
            projects.forEach(project -> {
                if (methodPair.containsKey(project.getPayment())) {
                    project.setPaymentStr(methodPair.get(project.getPayment()));
                }
                // 创建时间 格式化 全
                if (ObjUtil.isNotEmpty(project.getCreateTime())) {
                    project.setCreateTimeStr(LocalDateTimeUtil.format(project.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
                }
                // 创建时间 格式化 yyyy-MM-dd
                if (ObjUtil.isNotEmpty(project.getStartTime())) {
                    project.setStartTimeStr(LocalDateTimeUtil.format(project.getStartTime(), DatePattern.NORM_DATE_PATTERN));
                }
                // 创建时间 格式化 yyyy-MM-dd
                if (ObjUtil.isNotEmpty(project.getEndTime())) {
                    project.setEndTimeStr(LocalDateTimeUtil.format(project.getEndTime(), DatePattern.NORM_DATE_PATTERN));
                }
            });
        }
        // 导出 Excel
        ExcelUtils.write(response, "项目信息列表.xls", "项目信息列表", IotProjectInfoRespVO.class,
                projects);
    }

}