package com.ruoyi.cms.service.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.ruoyi.cms.domain.*;
import com.ruoyi.cms.domain.query.LabelQuery;
import com.ruoyi.cms.mapper.*;
import com.ruoyi.cms.service.ICompanyCollectionService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.ruoyi.cms.service.ICompanyService;

/**
 * 公司Service业务层处理
 *
 * @author lishundong
 * @date 2024-09-04
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper,Company> implements ICompanyService
{
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private CompanyCollectionMapper companyCollectionMapper;
    @Autowired
    private CompanyCardMapper companyCardMapper;
    @Autowired
    private CompanyLabelMapper companyLabelMapper;
    /**
     * 查询公司
     *
     * @param companyId 公司主键
     * @return 公司
     */
    @Override
    public Company selectCompanyByCompanyId(Long companyId)
    {
        Company company = companyMapper.selectById(companyId);
        if(SecurityUtils.isLogin()){
            Long l = companyCollectionMapper.selectCount(Wrappers.<CompanyCollection>lambdaQuery().eq(CompanyCollection::getCompanyId, companyId).eq(CompanyCollection::getUserId, SecurityUtils.getUserId()));
            company.setIsCollection(l>0?1:0);
        }else {
            company.setIsCollection(0);
        }
        return company;
    }

    /**
     * 查询公司列表
     *
     * @param company 公司
     * @return 公司
     */
    @Override
    public List<Company> selectCompanyList(Company company)
    {
        return companyMapper.selectCompanyList(company);
    }

    /**
     * 新增公司
     *
     * @param company 公司
     * @return 结果
     */
    @Override
    public int insertCompany(Company company)
    {
        Long count = companyMapper.selectCount(Wrappers.<Company>lambdaQuery().eq(Company::getName, company.getName()));
        if(count>0){
            throw new ServiceException(company.getName()+"，该公司已存在");
        }
        return companyMapper.insert(company);
    }

    /**
     * 修改公司
     *
     * @param company 公司
     * @return 结果
     */
    @Override
    public int updateCompany(Company company)
    {
        Long count = companyMapper.selectCount(Wrappers.<Company>lambdaQuery().eq(Company::getName, company.getName()));
        if(count>1){
            throw new ServiceException(company.getName()+"，该公司已存在");
        }
        return companyMapper.updateById(company);
    }


    /**
     * 批量删除公司
     *
     * @param companyIds 需要删除的公司主键
     * @return 结果
     */
    @Override
    public int deleteCompanyByCompanyIds(Long[] companyIds)
    {
        Long aLong = jobMapper.selectCount(Wrappers.<Job>lambdaQuery().in(Job::getCompanyId, companyIds));
        if(aLong>0){
            throw new ServiceException("该公司下存在职位，不能删除");
        }
        return companyMapper.deleteBatchIds(Arrays.asList(companyIds));
    }

    /**
     * 公司招聘的岗位数量
     * @param companyId
     * @return
     */
    @Override
    public Integer count(Long companyId) {
        Integer result = Math.toIntExact(jobMapper.selectCount(Wrappers.<Job>lambdaQuery().eq(Job::getCompanyId, companyId)));
        return result;
    }

    @Override
    public void updateJobCountOfCompany() {
        companyMapper.updateJobCountOfCompany();
    }

    @Override
    public List<Company> label(CompanyCard companyCard,LabelQuery labelQuery) {
        List<Company> result = companyMapper.label(companyCard.getCompanyNature(),companyCard.getTarg(),labelQuery.getCompanyName());
        return result;
    }
    @Override
    public void importLabel() {
        // 获取所有公司列表
        List<Company> companyList = companyMapper.selectList(null);

        // 创建用于存储匹配结果的标签列表
        List<CompanyLabel> labelList = new ArrayList<>();

        // Excel文件路径
        String filePath = "/home/lapuda/mine_code/backend/2024财富中国500强.xlsx";

        try (InputStream is = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(is)) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历每一行（跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 获取第二列的公司名称
                Cell cell = row.getCell(1);
                if (cell == null) continue;

                String companyName = cell.getStringCellValue().trim();

                // 在公司列表中查找匹配的公司
                companyList.stream()
                        .filter(company -> companyName.equals(company.getName())) // 假设Company类有getName()方法
                        .findFirst()
                        .ifPresent(company -> {
                            // 创建标签对象
                            CompanyLabel label = new CompanyLabel();
                            label.setDictValue("1");
                            label.setCompanyId(company.getCompanyId()); // 假设Company类有getId()方法
                            labelList.add(label);
                        });
            }

            // 批量保存标签（假设有对应的service或mapper方法）
            if (!labelList.isEmpty()) {
                // 这里需要实现批量插入逻辑，例如：
                // companyLabelService.saveBatch(labelList);
                // 或者遍历保存
                for (CompanyLabel label : labelList) {
                    companyLabelMapper.insert(label);
                }
            }

        } catch (IOException e) {
            log.error("导入标签失败", e);
            throw new RuntimeException("导入标签失败", e);
        }
    }

    @Override
    public void importLabelBank() {
        List<Company> companyList = companyMapper.selectList(Wrappers.<Company>lambdaQuery().like(Company::getName, "银行"));
        companyList.forEach(company -> {
                    // 创建标签对象
                    CompanyLabel label = new CompanyLabel();
                    label.setDictValue("3");
                    label.setCompanyId(company.getCompanyId()); // 假设Company类有getId()方法
                    companyLabelMapper.insert(label);
                });
    }
}
