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.BeanValidators;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.mapper.BizCompanyMapper;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

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

    @Override
    public BizCompany getById(Long id) {
        BizCompany company = super.getById(id);

        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;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BizCompany company : companyList) {
            try {
                // 验证是否存在这个客户
                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();
                    company.setTenantId(tenantId);
                    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 boolean save(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.save(company));
        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));
        return res.get();
    }
}
