package cn.ezhizao.project.business.company.service.impl;

import cn.ezhizao.common.constant.HttpStatus;
import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.common.utils.bean.BeanUtils;
import cn.ezhizao.common.utils.bean.BeanValidators;
import cn.ezhizao.project.business.channel.domain.BizChannel;
import cn.ezhizao.project.business.channel.mapper.BizChannelMapper;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.domain.vo.ExportZero;
import cn.ezhizao.project.business.company.mapper.BizCompanyMapper;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.companyContactor.domain.BizCompanyContactor;
import cn.ezhizao.project.business.companyContactor.mapper.BizCompanyContactorMapper;
import cn.ezhizao.project.business.companyFollow.domain.BizCompanyFollowDetail;
import cn.ezhizao.project.business.companyFollow.mapper.BizCompanyFollowDetailMapper;
import cn.ezhizao.project.business.settings.domain.BizSource;
import cn.ezhizao.project.business.settings.mapper.BizSourceMapper;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * companyService业务层处理
 *
 * @author ezhizao
 * @date 2023-10-16
 */
@Service
public class BizCompanyServiceImpl  extends ServiceImpl<BizCompanyMapper, BizCompany> implements IBizCompanyService
{
    @Resource
    private BizCompanyMapper bizCompanyMapper;
    @Resource
    private BizCompanyFollowDetailMapper bizCompanyFollowDetailMapper;
    @Resource
    private BizCompanyContactorMapper bizCompanyContactorMapper;
    @Resource
    private BizSourceMapper bizSourceMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private Validator validator;
    @Resource
    private BizChannelMapper bizChannelMapper;

    @Override
    public BizCompany getById(Long id) {
        BizCompany company = super.getById(id);
        if (company != null) {
            BizCompanyFollowDetail condition = new BizCompanyFollowDetail();
            condition.setCompanyId(id);
            List<BizCompanyFollowDetail> followDetails = bizCompanyFollowDetailMapper.getList(condition);
            BizCompanyContactor contactorCondition = new BizCompanyContactor();
            contactorCondition.setCompanyId(id);
            List<BizCompanyContactor> contactors = bizCompanyContactorMapper.getList(contactorCondition);
            company.setContactors(contactors);
            company.setFollowDetails(followDetails);
        }

        return company;
    }

    /**
     * 查询company列表
     *
     * @param bizCompany company
     * @return company
     */
    @Override
    public List<BizCompany> getList(BizCompany bizCompany)
    {
        return bizCompanyMapper.getList(bizCompany);
    }

    /**
     * 物理删除
     * @param bizCompany
     * @return 删除结果
     */
    @Override
    public int physicalDelete(BizCompany bizCompany){ return bizCompanyMapper.physicalDelete(bizCompany); }

    @Override
    public String importCompany(List<BizCompany> companyList, String operName, Long tenantId) {
        if (StringUtils.isNull(companyList) || companyList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        BizSource sourceCondition = new BizSource();
        sourceCondition.setTenantId(tenantId);
        List<BizSource> sources = bizSourceMapper.getList(sourceCondition);
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BizCompany company : companyList) {
            try {
                if(company.getName().equals("")||company.getName()==null){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户名称不能为空");
                    continue;
                }
                // 验证是否存在这个客户
                if(this.query().eq("name", company.getName()).eq("tenant_id", tenantId).count() > 0)
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户 " + company.getName() + " 已存在");
                } else {
                    BeanValidators.validateWithException(validator, company);
                    String sourceName = company.getSourceName();
                    String sourceCategory = company.getSourceCategoryName();
                    if(company.getLeaderName()!= null){
                        SysUser user = sysUserMapper.selectUserByUserName(company.getLeaderName());
                        if (user != null) {
                            company.setLeaderId(user.getUserId());
                        }
                    }
                    if(company.getAdviserName()!=null){
                        SysUser user = sysUserMapper.selectUserByUserName(company.getAdviserName());
                        if (user != null) {
                            company.setAdviserId(user.getUserId());
                        }
                    }
                    company.setTenantId(tenantId);
                    BizSource source = sources.stream().filter(v -> v.getTitle().equals(sourceCategory)).findFirst().orElse(null);
                    if (source != null) {
                        company.setSourceCategoryId(source.getId());
                        switch (source.getReferrerDataSource()) {
                            case "company":
                                QueryWrapper<BizCompany> companyWrapper = new QueryWrapper<>();
                                companyWrapper.eq("name", sourceName);
                                BizCompany sourceCompany = bizCompanyMapper.selectOne(companyWrapper);
                                company.setSourceId(sourceCompany.getId());
                                break;
                            case "employee":
                                SysUser sourceUser = sysUserMapper.selectUserByUserName(sourceName);
                                company.setSourceId(sourceUser.getId());
                                break;
                            case "channel":
                                QueryWrapper<BizChannel> channelWrapper = new QueryWrapper<>();
                                channelWrapper.eq("name", sourceName);
                                BizChannel sourceChannel = bizChannelMapper.selectOne(channelWrapper);
                                company.setSourceId(sourceChannel.getId());
                                break;
                            default:
                                break;
                        }
                        this.save(company);
                    } else {
                        this.save(company);
                    }
//                    else {
//                        failureNum++;
//                        failureMsg.append("<br/>" + failureNum + "、客户 " + company.getName() + " 未输入来源或来源输入错误");
//                    }
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户 " + company.getName() + " 导入成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + company.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
//        return "";
    }

    @Override
    public String importZero(List<ExportZero> companyList, long tenantId) {
        StringBuilder successMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        List<String> name = bizCompanyMapper.selectList(new LambdaQueryWrapper<BizCompany>()
                .eq(BizCompany::getTenantId, tenantId)
        ).stream().map(m ->m.getName()).collect(Collectors.toList());
        for (ExportZero zero : companyList) {
            try {
               if (!name.contains(zero.getName())){
                   throw new Exception("不存在");
               }
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + zero.getName() ;
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        List<BizCompany> bizCompanyList = companyList.stream().map(m -> {
                    BizCompany bizCompany = new BizCompany();
                    bizCompany.setName(m.getName());
                    bizCompany.setIsZero(m.getIsZero().equals("零申报") ? 1 : 0);
                    bizCompany.setTenantId(tenantId);
                    return bizCompany;
                }
        ).collect(Collectors.toList());
        List<BizCompany> list= this.list(new LambdaQueryWrapper<BizCompany>().eq(BizCompany::getTenantId, tenantId));
        for (BizCompany bizCompany : bizCompanyList) {
            for (BizCompany company : list) {
               if(bizCompany.getName().trim().equals(company.getName().trim())) {
                   bizCompany.setId(company.getId());
               }
            }
        }
        this.updateBatchById(bizCompanyList);
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！");
        }
//        successMsg.append("零申报非零申报客户导入成功");
        return successMsg.toString();
    }

    ;

    @Override
    public boolean save(BizCompany company) {
        // 判断客户名是否重复
        if(this.query().eq("name", company.getName()).eq("tenant_id",company.getTenantId()).ne("id", company.getId() == null ? 0L :company.getId()).count() > 0) throw new ServiceException("客户名称重复", HttpStatus.ERROR);
        AtomicBoolean res = new AtomicBoolean(super.save(company));
        List<BizCompanyContactor> contactors = company.getContactors();
        if (contactors != null && contactors.size() > 0) {
            contactors.forEach(l -> {
                l.setCompanyId(company.getId());
                res.set(res.get() && bizCompanyContactorMapper.insert(l) > 0);
            });
        }
        return res.get();
    }
    @Override
    public boolean updateById(BizCompany company) {
        if(this.query()
                .eq("tenant_id",company.getTenantId())
                .eq("name", company.getName())
                .ne("id", company.getId() == null ? 0L :company.getId()).count() > 0) throw new ServiceException("客户名称重复", HttpStatus.ERROR);
        AtomicBoolean res = new AtomicBoolean(super.updateById(company));
        BizCompanyContactor delCondition = new BizCompanyContactor();
        delCondition.setCompanyId(company.getId());
        bizCompanyContactorMapper.physicalDelete(delCondition);
        List<BizCompanyContactor> contactors = company.getContactors();
        contactors.forEach(l -> {
            l.setCompanyId(company.getId());
            res.set(res.get() && bizCompanyContactorMapper.insert(l) > 0);
        });
        return res.get();
    }
}
