package com.fs.company.controller;

import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.ServletUtils;
import com.fs.company.param.CompanyDomainParam;
import com.fs.company.vo.CompanyDomainExportTemplateVo;
import com.fs.company.vo.CompanyDomainVo;
import com.fs.framework.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.company.domain.CompanyDomain;
import com.fs.company.service.ICompanyDomainService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 域名管路Controller
 *
 * @author fs
 * @date 2025-06-16
 */
@RestController
@RequestMapping("/company/companyDomain")
public class CompanyDomainController extends BaseController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICompanyDomainService companyDomainService;

    // 允许的文件扩展名
    private static final String[] ALLOWED_EXCEL_EXTENSIONS = {".xlsx", ".xls"};
    // 最大文件大小（5MB）
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    /**
     * 查询域名管路列表
     */
    @PreAuthorize("@ss.hasPermi('company:companyDomain:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyDomainParam companyDomain) {
        startPage();
        List<CompanyDomainVo> list = companyDomainService.selectCompanyDomainList(companyDomain);
        return getDataTable(list);
    }

    /**
     * 导出域名管路列表
     */
    @PreAuthorize("@ss.hasPermi('company:companyDomain:export')")
    @Log(title = "域名管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CompanyDomainParam companyDomain) {
        List<CompanyDomainVo> list = companyDomainService.selectCompanyDomainList(companyDomain);
        ExcelUtil<CompanyDomainVo> util = new ExcelUtil<CompanyDomainVo>(CompanyDomainVo.class);
        return util.exportExcel(list, "域名管路数据");
    }

    /**
     * 获取域名管路详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:companyDomain:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(companyDomainService.selectCompanyDomainById(id));
    }

    /**
     * 新增域名管路
     */
    @PreAuthorize("@ss.hasPermi('company:companyDomain:add')")
    @Log(title = "域名管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CompanyDomain companyDomain) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyDomain.setCreateBy(loginUser.getUser().getUserId().toString());
        return toAjax(companyDomainService.insertCompanyDomain(companyDomain));
    }

    /**
     * 修改域名管路
     */
    @PreAuthorize("@ss.hasPermi('company:companyDomain:edit')")
    @Log(title = "域名管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CompanyDomain companyDomain) {
        if (ObjectUtil.isEmpty(companyDomain.getId())) {
            throw new ServiceException("修改关键信息不能为空！");
        }
        return toAjax(companyDomainService.updateCompanyDomain(companyDomain));
    }

    /**
     * 删除域名管路
     */
    @PreAuthorize("@ss.hasPermi('company:companyDomain:remove')")
    @Log(title = "域名管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        if (ObjectUtil.isEmpty(ids)) {
            throw new ServiceException("删除关键信息不能为空！");
        }
        return toAjax(companyDomainService.deleteCompanyDomainByIds(ids));
    }

    /**
     * 域名批量绑定
     **/
    @PreAuthorize("@ss.hasPermi('company:companyDomain:domainBatchBinding')")
    @PostMapping("/domainBatchBinding")
    public R domainBatchBinding(@RequestBody CompanyDomainParam param) {
        if (ObjectUtil.isEmpty(param.getDomainIds()) || param.getDomainIds().isEmpty()) {
            return R.error("绑定失败，至少有一条绑定域名信息！");
        }
        if (ObjectUtil.isEmpty(param.getCompanyIds()) || param.getCompanyIds().isEmpty()) {
            return R.error("绑定失败，至少有一条绑定公司信息！");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setUserId(loginUser.getUser().getUserId().toString());
        return companyDomainService.domainBatchBinding(param);
    }

    /**
     * 导出模板
     **/
    @GetMapping("/exportTemplate")
    public AjaxResult exportTemplate() {
        ExcelUtil<CompanyDomainExportTemplateVo> util = new ExcelUtil<>(CompanyDomainExportTemplateVo.class);
        return util.importTemplateExcel("域名导入模板");
    }

    @Log(title = "域名导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importDomainData")
    public R importDomainData(MultipartFile file) {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return R.error("上传的文件不能为空");
        }

        // 2. 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return R.error("文件大小不能超过5MB");
        }

        // 3. 检查文件扩展名
        String fileName = file.getOriginalFilename();
        if (fileName == null || !isValidExcelFile(fileName)) {
            return R.error("请上传Excel文件（.xlsx或.xls格式）");
        }
        CompanyDomainParam param = new CompanyDomainParam();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setUserId(loginUser.getUser().getUserId().toString());
        ExcelUtil<CompanyDomainExportTemplateVo> util = new ExcelUtil<>(CompanyDomainExportTemplateVo.class);
        try {
            List<CompanyDomainExportTemplateVo> companyDomainList = util.importExcel(file.getInputStream());
            return companyDomainService.importDomainData(param, companyDomainList);
        } catch (Exception e) {
            e.getStackTrace();
            return R.error("导入失败！");
        }
    }

    // 检查文件是否为有效的Excel文件
    private boolean isValidExcelFile(String fileName) {
        for (String ext : ALLOWED_EXCEL_EXTENSIONS) {
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
}
