package com.ruoyi.cms.service.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cms.domain.*;
import com.ruoyi.cms.domain.query.LabelQuery;
import com.ruoyi.cms.mapper.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.Company;
import com.ruoyi.common.core.domain.entity.CompanyContact;
import com.ruoyi.common.core.domain.entity.JobDTO;
import com.ruoyi.common.core.domain.model.LoginSiteUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
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;
    @Autowired
    private CompanyContactMapper companyContactMapper;
    /**
     * 查询公司
     *
     * @param companyId 公司主键
     * @return 公司
     */
    @Override
    public Company selectCompanyByCompanyId(Long companyId)
    {
        Company company = companyMapper.selectById(companyId);
        Long userId=null;
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            userId = loginUser.getUserId();
        }catch (Exception ignored){
            LoginSiteUser siteUser = SiteSecurityUtils.getLoginSiteUser();
            userId = siteUser.getUserId();
        }
        //收藏
        Long l = companyCollectionMapper.selectCount(Wrappers.<CompanyCollection>lambdaQuery().eq(CompanyCollection::getCompanyId, companyId).eq(CompanyCollection::getUserId, userId));
        company.setIsCollection(l>0?1:0);
        //联系人
        CompanyContact contact=new CompanyContact();
        contact.setCompanyId(company.getCompanyId());
        List<CompanyContact> contacts=companyContactMapper.getSelectList(contact);
        if(contacts!=null){
            company.setCompanyContactList(contacts);
        }
        //查询岗位
        Job parJob=new Job();
        parJob.setCompanyId(company.getCompanyId());
        List<Job> jobs=jobMapper.selectJobList(parJob);
        List joblist=jobs.stream().map(job -> {
            JobDTO dto = new JobDTO();
            BeanUtils.copyProperties(job, dto);
            return dto;
        }).collect(Collectors.toList());
        company.setJobList(joblist);
        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()+"，该公司已存在");
        }
        int insert =companyMapper.insert(company);
        if(insert>0){
            company.getCompanyContactList().forEach(x->{
                CompanyContact companyContact=new CompanyContact();
                BeanUtils.copyProperties(x,companyContact);
                companyContact.setCompanyId(company.getCompanyId());
                companyContactMapper.insert(companyContact);
            });
        }
        return insert;
    }

    /**
     * 修改公司
     *
     * @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()+"，该公司已存在");
        }
        int i=companyMapper.updateById(company);
        if(i>0){
            companyContactMapper.update(null,Wrappers.<CompanyContact>lambdaUpdate()
                    .eq(CompanyContact::getCompanyId, company.getCompanyId())
                    .set(CompanyContact::getDelFlag, Constants.Del_FLAG_DELETE));
            if(Objects.isNull(company.getCompanyContactList())){return i;}
            company.getCompanyContactList().forEach(x -> {
                CompanyContact companyContact = new CompanyContact();
                companyContact.setCompanyId(company.getCompanyId());
                companyContactMapper.insert(companyContact);
            });
        }
        return i;
    }


    /**
     * 批量删除公司
     *
     * @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("该公司下存在职位，不能删除");
        }
        int i=companyMapper.deleteBatchIds(Arrays.asList(companyIds));
        if(i>0){
            companyContactMapper.update(null,Wrappers.<CompanyContact>lambdaUpdate()
                    .in(CompanyContact::getCompanyId, Arrays.asList(companyIds))
                    .set(CompanyContact::getDelFlag, Constants.Del_FLAG_DELETE));
        }
        return i;
    }

    /**
     * 公司招聘的岗位数量
     * @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);
                });
    }

    @Override
    public void register(Company company) {
        Long userId = SiteSecurityUtils.getUserId();
        company.setUserId(userId);
        if(companyMapper.selectCount(Wrappers.<Company>lambdaQuery().eq(Company::getName, company.getName()).in(Company::getStatus,Arrays.asList(0,1)))>0){
            throw new ServiceException(company.getName()+"已经存在");
        }
        company.setStatus(0);
    }

    @Override
    public Company registerStatus() {
        Long userId = SiteSecurityUtils.getUserId();
        Company company = companyMapper.selectOne(Wrappers.<Company>lambdaQuery().eq(Company::getUserId, userId).orderByDesc(Company::getUpdateTime));
        return company;
    }

    @Override
    public List<Company> approvalList(Company company) {
        return companyMapper.selectList(Wrappers.<Company>lambdaQuery().eq(Company::getName, company.getName()).in(Company::getStatus, Arrays.asList(0, 1, 2)).orderByAsc(Company::getStatus).orderByDesc(Company::getCreateTime));
    }

    @Override
    public Company approval(Company company) {
        Company company1 = companyMapper.selectById(company.getCompanyId());
        if(company1==null){
            throw new ServiceException("企业不存在");
        }
        if(company1.getStatus()!=null){
            if(company1.getStatus()!=0){
                throw new ServiceException("企业已审核");
            }
        }
        companyMapper.updateById(company);
        //创建账号
        return company1;
    }

    @Override
    public Company queryCodeCompany(String code) {
        Company companyResult = companyMapper.selectOne(Wrappers.<Company>lambdaQuery().eq(Company::getCode, code).orderByDesc(Company::getUpdateTime).last("LIMIT 1"));
        if(companyResult!=null){
            CompanyContact contact=new CompanyContact();
            contact.setCompanyId(companyResult.getCompanyId());
            List<CompanyContact> contacts=companyContactMapper.getSelectList(contact);
        }
        return companyResult;
    }

    @Override
    public List<Company> selectLikeCompanyList(Company company) {
        return companyMapper.selectLikeCompanyList(company);
    }
}
