package com.zhongzheng.modules.recruit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.zhongzheng.common.core.domain.entity.SysDictData;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.recruit.bo.RecruitNeedsQueryBo;
import com.zhongzheng.modules.recruit.domain.RecruitCompanyTrade;
import com.zhongzheng.modules.recruit.domain.RecruitNeeds;
import com.zhongzheng.modules.recruit.service.IRecruitCompanyTradeService;
import com.zhongzheng.modules.recruit.service.IRecruitNeedsService;
import com.zhongzheng.modules.recruit.vo.RecruitCompanyNeedVo;
import com.zhongzheng.modules.recruit.vo.RecruitCompanyTradeVo;
import com.zhongzheng.modules.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.zhongzheng.modules.recruit.bo.RecruitCompanyAddBo;
import com.zhongzheng.modules.recruit.bo.RecruitCompanyQueryBo;
import com.zhongzheng.modules.recruit.bo.RecruitCompanyEditBo;
import com.zhongzheng.modules.recruit.domain.RecruitCompany;
import com.zhongzheng.modules.recruit.mapper.RecruitCompanyMapper;
import com.zhongzheng.modules.recruit.vo.RecruitCompanyVo;
import com.zhongzheng.modules.recruit.service.IRecruitCompanyService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司管理列Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-19
 */
@Service
public class RecruitCompanyServiceImpl extends ServiceImpl<RecruitCompanyMapper, RecruitCompany> implements IRecruitCompanyService {

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IRecruitCompanyTradeService iRecruitCompanyTradeService;

    @Autowired
    private IRecruitNeedsService iRecruitNeedsService;


    @Override
    public RecruitCompanyVo queryById(Long companyId){
        RecruitCompanyQueryBo recruitCompanyQueryBo = new RecruitCompanyQueryBo();
        recruitCompanyQueryBo.setCompanyId(companyId);
        List<RecruitCompanyVo> recruitCompanyVos = baseMapper.selectLimt(recruitCompanyQueryBo);
        return BeanUtil.toBean(recruitCompanyVos.get(0), RecruitCompanyVo.class);
    }

    @Override
    public List<RecruitCompanyVo> queryList(RecruitCompanyQueryBo bo) {
        List<RecruitCompanyVo> recruitCompanyVos = baseMapper.selectLimt(bo);
        for (RecruitCompanyVo companyVo : recruitCompanyVos) {
            if (companyVo.getCompanyTypeId() != null && companyVo.getCompanySizeId() != null) {
                SysDictData sysDictData = dictDataService.selectDictDataById(companyVo.getCompanyTypeId());
                SysDictData sysDictData1 = dictDataService.selectDictDataById(companyVo.getCompanySizeId());
                companyVo.setCompanyType(sysDictData.getDictLabel());
                companyVo.setCompanySize(sysDictData1.getDictLabel());
            }
        }
        return recruitCompanyVos;
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<RecruitCompanyVo> entity2Vo(Collection<RecruitCompany> collection) {
        List<RecruitCompanyVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, RecruitCompanyVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<RecruitCompany> page = (Page<RecruitCompany>)collection;
            Page<RecruitCompanyVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(RecruitCompanyAddBo bo) {
        RecruitCompany add = BeanUtil.toBean(bo, RecruitCompany.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        add.setStatus(1);
        RecruitCompanyTradeVo companyTradeVo = iRecruitCompanyTradeService.queryById(bo.getIndustryTypeId());
        add.setIndustryTypeName(companyTradeVo.getTradeName());
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(RecruitCompanyEditBo bo) {
        RecruitCompanyTradeVo companyTradeVo = iRecruitCompanyTradeService.queryById(bo.getIndustryTypeId());
        if (bo.getCompanyId() == 0){
            RecruitCompany update = BeanUtil.toBean(bo, RecruitCompany.class);
            update.setUpdateTime(DateUtils.getNowTime());
            update.setUpdateTime(DateUtils.getNowTime());
            update.setIndustryTypeName(companyTradeVo.getTradeName());
            String TenantId = ServletUtils.getRequest().getHeader("TenantId");
            update.setTenantId(Convert.toLong(TenantId));
            return baseMapper.updateSysTent(update)==1;
        }
        RecruitCompany update = BeanUtil.toBean(bo, RecruitCompany.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        update.setUpdateTime(DateUtils.getNowTime());

        update.setIndustryTypeName(companyTradeVo.getTradeName());
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(RecruitCompany entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchImport(MultipartFile file) throws IOException {
        byte [] byteArr=file.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> readAll = reader.read();
        readAll.remove(0);
        List<RecruitCompany> companyList = new ArrayList<>();
        String TenantId = ServletUtils.getRequest().getHeader("TenantId");
        Long nowTime = DateUtils.getNowTime();
        for (int i = 0; i < readAll.size(); i++) {
            RecruitCompany company = new RecruitCompany();
            if(readAll.get(i).get(0).toString().equals("****公司")){
                continue;
            }
            company.setCompanyName(readAll.get(i).get(0).toString());
            Long sysDictData = dictDataService.selectDictLabelType("company_type",readAll.get(i).get(1).toString());
            if (sysDictData == null){
                throw new RuntimeException("第"+i+1+"行公司类型存在错误，请仔细检查再上传。");
            }
            company.setCompanyTypeId(sysDictData);
            Long industryId = baseMapper.selectIndustry(readAll.get(i).get(2).toString());
            if (industryId == null){
                throw new RuntimeException("第"+i+1+"行行业类别存在错误，请仔细检查再上传。");
            }
            company.setIndustryTypeId(industryId);
            company.setIndustryTypeName(readAll.get(i).get(2).toString());
            Long sysDictLong = dictDataService.selectDictLabelType("company_size",readAll.get(i).get(3).toString());
            if (sysDictLong == null){
                throw new RuntimeException("第"+i+1+"行公司规模存在错误，请仔细检查再上传。");
            }
            company.setCompanySizeId(sysDictLong);
            company.setCompanyIntroduce(readAll.get(i).get(4).toString());
            company.setSocietyCode(readAll.get(i).get(5).toString());
            company.setProvince(readAll.get(i).get(6).toString());
            company.setCity(readAll.get(i).get(7).toString());
            company.setDistrict(readAll.get(i).get(8).toString());
            company.setAddress(readAll.get(i).get(9).toString());
            company.setCompanyPh(readAll.get(i).get(10).toString());
            company.setLinkMan(readAll.get(i).get(11).toString());
            company.setPostBox(readAll.get(i).get(12).toString());
            company.setTenantId(Convert.toLong(TenantId));
            company.setCreateTime(nowTime);
            company.setUpdateTime(nowTime);
            company.setStatus(1);
            companyList.add(company);
        }
        return this.saveBatch(companyList);
    }

    @Override
    public List<RecruitCompanyNeedVo> queryNeedsList(RecruitCompanyQueryBo bo) {
        List<RecruitCompanyVo> recruitCompanyVos = baseMapper.selectLimt(bo);


        List<RecruitCompanyNeedVo> recruitCompanyNeedVos = entityNeedsVo(recruitCompanyVos);
        for (RecruitCompanyNeedVo companyVo : recruitCompanyNeedVos) {
            if (companyVo.getCompanyTypeId() != null && companyVo.getCompanySizeId() != null) {
                SysDictData sysDictData = dictDataService.selectDictDataById(companyVo.getCompanyTypeId());
                SysDictData sysDictData1 = dictDataService.selectDictDataById(companyVo.getCompanySizeId());
                companyVo.setCompanyType(sysDictData.getDictLabel());
                companyVo.setCompanySize(sysDictData1.getDictLabel());
            }
            RecruitNeedsQueryBo recruitNeedsQueryBo = new RecruitNeedsQueryBo();
            recruitNeedsQueryBo.setCompanyId(companyVo.getCompanyId());
            List<Integer> statusList = new ArrayList<>();
            statusList.add(2);
            recruitNeedsQueryBo.setStatus(statusList);
            List<RecruitNeeds> list = iRecruitNeedsService.queryRecruitNeedsListString(recruitNeedsQueryBo);
            companyVo.setRecruitNeedsVoList(list);
        }
        return recruitCompanyNeedVos;
    }

    @Override
    public RecruitCompanyNeedVo queryNeedsId(Long companyId) {
            RecruitCompanyQueryBo recruitCompanyQueryBo = new RecruitCompanyQueryBo();
            recruitCompanyQueryBo.setCompanyId(companyId);
            List<RecruitCompanyVo> recruitCompanyVos = baseMapper.selectLimt(recruitCompanyQueryBo);
            RecruitCompanyNeedVo recruitCompanyNeedVo = BeanUtil.toBean(recruitCompanyVos.get(0), RecruitCompanyNeedVo.class);
            if (recruitCompanyNeedVo.getCompanyTypeId() != null && recruitCompanyNeedVo.getCompanySizeId() != null) {
                SysDictData sysDictData = dictDataService.selectDictDataById(recruitCompanyNeedVo.getCompanyTypeId());
                SysDictData sysDictData1 = dictDataService.selectDictDataById(recruitCompanyNeedVo.getCompanySizeId());
                recruitCompanyNeedVo.setCompanyType(sysDictData.getDictLabel());
                recruitCompanyNeedVo.setCompanySize(sysDictData1.getDictLabel());
            }
            RecruitNeedsQueryBo recruitNeedsQueryBo = new RecruitNeedsQueryBo();
            recruitNeedsQueryBo.setCompanyId(companyId);
            List<Integer> statusList = new ArrayList<>();
            statusList.add(2);
            recruitNeedsQueryBo.setStatus(statusList);
            List<RecruitNeeds> list = iRecruitNeedsService.queryRecruitNeedsListString(recruitNeedsQueryBo);
            recruitCompanyNeedVo.setRecruitNeedsVoList(list);
            return recruitCompanyNeedVo;
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<RecruitCompanyNeedVo> entityNeedsVo(Collection<RecruitCompanyVo> collection) {
        List<RecruitCompanyNeedVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, RecruitCompanyNeedVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<RecruitCompanyVo> page = (Page<RecruitCompanyVo>)collection;
            Page<RecruitCompanyNeedVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }
}
