package com.hotwj.platform.resourceManagement.company.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import com.hotwj.platform.resourceManagement.company.domain.bo.SysCompanyBo;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.translation.constant.TransConstant;
import org.dromara.common.translation.core.TranslationInterface;
import org.dromara.common.translation.core.handler.TranslationHandler;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 企业基本信息
 *
 * @author shihongwei
 * @date 2025-12-02
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/resourceManagement/company")
@Tag(name = "企业基本信息", description = "企业基本信息增删改查")
public class SysCompanyController extends BaseController {

    private final ISysCompanyService sysCompanyService;

    /**
     * 查询企业基本信息列表
     */
    //@SaCheckPermission("resourceManagement:company:list")
    @GetMapping("/list")
    @Operation(summary = "分页查询企业基本信息列表")
    public TableDataInfo<SysCompanyVo> list(SysCompanyBo bo, PageQuery pageQuery) {
        return sysCompanyService.queryPageList(bo, pageQuery);
    }

    /**
     * 根据邀请码查询企业名称
     */
    @SaIgnore
    @GetMapping("/getCompanyNameByInviteCode")
    @Operation(summary = "根据邀请码查询企业名称")
    public R<String> getCompanyNameByInviteCode(@RequestParam("companyId") Long companyId, @RequestParam("inviteCode") String inviteCode) {
        return R.ok("操作成功", sysCompanyService.checkInviteCode(companyId, inviteCode));
    }

    /**
     * 重置所有企业邀请码（管理员功能）
     */
    //@SaCheckPermission("resourceManagement:company:resetInviteCode")
    @Log(title = "重置所有企业邀请码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetAllInviteCodes")
    @Operation(summary = "重置所有企业邀请码")
    public R<Void> resetAllInviteCodes() {
        sysCompanyService.resetAllInviteCodes();
        return R.ok("重置成功，请稍后查看企业列表");
    }


    //@SaCheckPermission("resourceManagement:company:list")
    @GetMapping("/listByRegion")
    @Operation(summary = "按多个区划分页查询企业基本信息列表")
    public TableDataInfo<SysCompanyVo> listByRegion(SysCompanyBo bo,
                                                    @RequestParam(value = "regionCodes", required = false) String regionCodes,
                                                    @RequestParam(value = "ids", required = false) String ids,
                                                    PageQuery pageQuery) {
        java.util.List<String> codes = null;
        java.util.List<Long> idList = null;
        if (org.dromara.common.core.utils.StringUtils.isNotBlank(regionCodes)) {
            codes = java.util.Arrays.stream(regionCodes.split(","))
                    .map(String::trim)
                    .filter(org.dromara.common.core.utils.StringUtils::isNotBlank)
                    .distinct()
                    .toList();
            bo.setRegionCode(null);
        }
        if (org.dromara.common.core.utils.StringUtils.isNotBlank(ids)) {
            idList = java.util.Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(org.dromara.common.core.utils.StringUtils::isNotBlank)
                    .map(Long::valueOf)
                    .distinct()
                    .toList();
        }
        if ((codes != null && !codes.isEmpty()) || (idList != null && !idList.isEmpty())) {
            return sysCompanyService.queryPageListByRegionAndIds(bo, pageQuery, codes, idList);
        } else {
            return sysCompanyService.queryPageList(bo, pageQuery);
        }
    }

    /**
     * 导出企业基本信息列表
     */
    //@SaCheckPermission("resourceManagement:company:export")
    @Log(title = "企业基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "导出企业基本信息列表")
    public void export(SysCompanyBo bo,
                       @RequestParam(value = "ids", required = false) String ids,
                       HttpServletResponse response) {
        List<Long> idList = null;
        if (org.dromara.common.core.utils.StringUtils.isNotBlank(ids)) {
            idList = java.util.Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(org.dromara.common.core.utils.StringUtils::isNotBlank)
                    .map(Long::valueOf)
                    .distinct()
                    .toList();
        }
        List<SysCompanyVo> list = sysCompanyService.queryList(bo, idList);
        if (CollUtil.isNotEmpty(list)) {
            TranslationInterface<?> trans = TranslationHandler.TRANSLATION_MAPPER.get(TransConstant.REGION_CODE_TO_NAME);
            for (int i = 0; i < list.size(); i++) {
                SysCompanyVo vo = list.get(i);
                vo.setIndex(i + 1);
                if (trans != null && org.dromara.common.core.utils.StringUtils.isNotBlank(vo.getRegionCode())) {
                    String label = (String) trans.translation(vo.getRegionCode(), null);
                    vo.setRegionLabel(label);
                }
            }
        }
        ExcelUtil.exportExcel(list, "企业基本信息", SysCompanyVo.class, response);
    }

    /**
     * 获取企业基本信息详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("resourceManagement:company:query")
    @GetMapping("/{id}")
    @Operation(summary = "查询企业基本信息详情")
    public R<SysCompanyVo> getInfo(@NotNull(message = "主键不能为空")
                                   @PathVariable Long id) {
        return R.ok(sysCompanyService.queryById(id));
    }

    /**
     * 新增企业基本信息
     */
    //@SaCheckPermission("resourceManagement:company:add")
    @Log(title = "企业基本信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Operation(summary = "新增企业基本信息")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysCompanyBo bo) {
        return toAjax(sysCompanyService.insertByBo(bo));
    }

    /**
     * 修改企业基本信息
     */
    //@SaCheckPermission("resourceManagement:company:edit")
    @Log(title = "企业基本信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Operation(summary = "修改企业基本信息")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysCompanyBo bo) {
        return toAjax(sysCompanyService.updateByBo(bo));
    }

    /**
     * 删除企业基本信息
     *
     * @param ids 主键串
     */
    //@SaCheckPermission("resourceManagement:company:remove")
    @Log(title = "企业基本信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除企业基本信息")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysCompanyService.deleteWithValidByIds(List.of(ids), true));
    }
}
