package com.zhongzheng.modules.company.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.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
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.company.bo.CompanyAddBo;
import com.zhongzheng.modules.company.bo.CompanyQueryBo;
import com.zhongzheng.modules.company.bo.CompanyEditBo;
import com.zhongzheng.modules.company.domain.Company;
import com.zhongzheng.modules.company.mapper.CompanyMapper;
import com.zhongzheng.modules.company.vo.CompanyVo;
import com.zhongzheng.modules.company.service.ICompanyService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 公司管理列Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-12
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

    @Override
    public CompanyVo queryById(Long companyId){
        Company db = this.baseMapper.selectById(companyId);
        return BeanUtil.toBean(db, CompanyVo.class);
    }

    @Override
    public List<CompanyVo> queryList(CompanyQueryBo bo) {
        LambdaQueryWrapper<Company> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getCompanyName()), Company::getCompanyName, bo.getCompanyName());
        lqw.eq(StrUtil.isNotBlank(bo.getCompanyType()), Company::getCompanyType, bo.getCompanyType());
        lqw.eq(StrUtil.isNotBlank(bo.getCompanySize()), Company::getCompanySize, bo.getCompanySize());
        lqw.eq(bo.getIndustryType()!=null, Company::getIndustryType, bo.getIndustryType());
        lqw.eq(StrUtil.isNotBlank(bo.getCompanyIntroduce()), Company::getCompanyIntroduce, bo.getCompanyIntroduce());
        lqw.eq(StrUtil.isNotBlank(bo.getLogoUrl()), Company::getLogoUrl, bo.getLogoUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getLicenseUrl()), Company::getLicenseUrl, bo.getLicenseUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getSocietyCode()), Company::getSocietyCode, bo.getSocietyCode());
        lqw.eq(StrUtil.isNotBlank(bo.getProvince()), Company::getProvince, bo.getProvince());
        lqw.eq(StrUtil.isNotBlank(bo.getCity()), Company::getCity, bo.getCity());
        lqw.eq(StrUtil.isNotBlank(bo.getAddress()), Company::getAddress, bo.getAddress());
        lqw.eq(StrUtil.isNotBlank(bo.getCompanyPh()), Company::getCompanyPh, bo.getCompanyPh());
        lqw.eq(StrUtil.isNotBlank(bo.getLinkMan()), Company::getLinkMan, bo.getLinkMan());
        lqw.eq(StrUtil.isNotBlank(bo.getPostBox()), Company::getPostBox, bo.getPostBox());
        lqw.eq( Company::getStatus, 1);
        lqw.eq(bo.getTenantId()!=null,Company::getTenantId, bo.getTenantId());
        return entity2Vo(this.list(lqw));
    }

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

    @Override
    public Boolean insertByAddBo(CompanyAddBo bo) {
        Company add = BeanUtil.toBean(bo, Company.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(CompanyEditBo bo) {
        Company update = BeanUtil.toBean(bo, Company.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Company 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<Company> companyList = new ArrayList<>();
        String TenantId = ServletUtils.getRequest().getHeader("TenantId");
        Long nowTime = DateUtils.getNowTime();
        for (int i = 0; i < readAll.size(); i++) {
            Company company = new Company();
            company.setCompanyName(readAll.get(i).get(0).toString());
            company.setCompanyType(readAll.get(i).get(1).toString());
            Integer industryId = baseMapper.selectIndustry(readAll.get(i).get(2).toString());
            if (industryId == null){
                throw new RuntimeException("第"+i+1+"行存在错误，请仔细检查再上传。");
            }
            company.setIndustryType(industryId);
            company.setIndustryTypeName(readAll.get(i).get(2).toString());
            company.setCompanySize(readAll.get(i).get(3).toString());
            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.setAddress(readAll.get(i).get(8).toString());
            company.setCompanyPh(readAll.get(i).get(9).toString());
            company.setLinkMan(readAll.get(i).get(10).toString());
            company.setPostBox(readAll.get(i).get(11).toString());
            company.setTenantId(Convert.toLong(TenantId));
            company.setCreateTime(nowTime);
            company.setUpdateTime(nowTime);
            company.setStatus(1);
            companyList.add(company);
        }
        return this.saveBatch(companyList);
    }
}
