package cn.iocoder.yudao.module.system.controller.admin.saporg;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
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.system.controller.admin.saporg.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.saporg.SapOrgDO;
import cn.iocoder.yudao.module.system.service.saporg.SapOrgService;
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.Collections;
import java.util.Comparator;
import java.util.List;

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

@Tag(name = "管理后台 - SAP中的组织主数据(工厂 成本中心)")
@RestController
@RequestMapping("/system/sap-org")
@Validated
public class SapOrgController {

    @Resource
    private SapOrgService sapOrgService;

    @PostMapping("/create")
    @Operation(summary = "创建SAP中的组织主数据(工厂 成本中心)")
    @PreAuthorize("@ss.hasPermission('system:sap-org:create')")
    public CommonResult<Long> createSapOrg(@Valid @RequestBody SapOrgSaveReqVO createReqVO) {
        return success(sapOrgService.createSapOrg(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新SAP中的组织主数据(工厂 成本中心)")
    @PreAuthorize("@ss.hasPermission('system:sap-org:update')")
    public CommonResult<Boolean> updateSapOrg(@Valid @RequestBody SapOrgSaveReqVO updateReqVO) {
        sapOrgService.updateSapOrg(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除SAP中的组织主数据(工厂 成本中心)")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:sap-org:delete')")
    public CommonResult<Boolean> deleteSapOrg(@RequestParam("id") Long id) {
        sapOrgService.deleteSapOrg(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得SAP中的组织主数据(工厂 成本中心)")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:sap-org:query')")
    public CommonResult<SapOrgRespVO> getSapOrg(@RequestParam("id") Long id) {
        SapOrgDO sapOrg = sapOrgService.getSapOrg(id);
        return success(BeanUtils.toBean(sapOrg, SapOrgRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得SAP中的组织主数据(工厂 成本中心)分页")
    @PreAuthorize("@ss.hasPermission('system:sap-org:query')")
    public CommonResult<PageResult<SapOrgRespVO>> getSapOrgPage(@Valid SapOrgPageReqVO pageReqVO) {
        PageResult<SapOrgDO> pageResult = sapOrgService.getSapOrgPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, SapOrgRespVO.class));
    }

    @GetMapping(value = {"/list-all-simple", "simple-list"})
    @Parameter(name = "type", description = "类型", required = true, example = "1工厂 2成本中心 3库存地点")
    @Operation(summary = "获取SAP工厂/成本中心/库存地点全列表", description = "只包含被开启的数据，主要用于前端的下拉选项")
    public CommonResult<List<SapOrgSimpleRespVO>> getSimpleSapOrgList(@RequestParam("type") Integer type) {
        // 获得SAP工厂/成本中心/库存地点列表，只要开启状态的
        List<SapOrgDO> list = sapOrgService.getSapOrgList(null, type, Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 排序后，返回给前端
        list.sort(Comparator.comparing(SapOrgDO::getSort));
        return success(BeanUtils.toBean(list, SapOrgSimpleRespVO.class));
    }

    @GetMapping(value ="filteredSimpleSapOrgList")
    @Parameter(name = "type", description = "类型", required = true, example = "1工厂 2成本中心 3库存地点")
    @Parameter(name = "deptId", description = "部门id", required = true, example = "225")
    @Operation(summary = "根据部门过滤 SAP工厂/成本中心/库存地点全列表", description = "只包含被开启的数据，主要用于前端的下拉选项")
    public CommonResult<List<SapOrgSimpleRespVO>> filteredSimpleSapOrgList(@RequestParam("type") Integer type, @RequestParam("deptId") Long deptId) {
        // 获得SAP工厂/成本中心/库存地点列表，只要开启状态的
        List<SapOrgDO> list = sapOrgService.filteredSapOrgList(deptId, type, Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 排序后，返回给前端
        list.sort(Comparator.comparing(SapOrgDO::getSort));
        return success(buildSapOrgs(list));
    }

    @PostMapping("/selectedSimpleList")
    @Operation(summary = "根据已经选择的SAP工厂 查询下属的成本中心/库存地点全列表", description = "只包含被开启的数据，主要用于前端的下拉选项")
    public CommonResult<List<SapOrgSimpleRespVO>> selectedSimpleList(@RequestBody SapOrgSimpleReqVO reqVO) {
        // 获得SAP工厂/成本中心/库存地点列表，只要开启状态的
        List<SapOrgDO> list = sapOrgService.getSelectedList(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(SapOrgDO::getSort));
        return success(buildSapOrgs(list));
    }

    /**
     * 设置sap组织返回信息
     * @param sapOrgs
     * @return
     */
    private List<SapOrgSimpleRespVO> buildSapOrgs(List<SapOrgDO> sapOrgs) {
        // 拼接 工厂-成本中心  工厂-库存地点
        if (CollUtil.isEmpty(sapOrgs)) {
            return Collections.emptyList();
        }
        return BeanUtils.toBean(sapOrgs, SapOrgSimpleRespVO.class, (sapOrgVO) -> {
            String factoryName = sapOrgVO.getFactoryName();
            String costCenterName = sapOrgVO.getCostCenterName();
            String storageLocationName = sapOrgVO.getStorageLocationName();
            if (StrUtil.isNotBlank(costCenterName)) {
                sapOrgVO.setCostCenterName(StrUtil.join("-", factoryName, costCenterName));
            }
            if (StrUtil.isNotBlank(storageLocationName)) {
                sapOrgVO.setStorageLocationName(StrUtil.join("-", factoryName, storageLocationName));
            }
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出SAP中的组织主数据(工厂 成本中心) Excel")
    @PreAuthorize("@ss.hasPermission('system:sap-org:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSapOrgExcel(@Valid SapOrgPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SapOrgDO> list = sapOrgService.getSapOrgPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "SAP中的组织主数据(工厂 成本中心).xls", "数据", SapOrgRespVO.class,
                        BeanUtils.toBean(list, SapOrgRespVO.class));
    }

}