package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.bean.result.SysCustomResult;
import com.qmth.sop.business.entity.SysCustom;
import com.qmth.sop.business.entity.SysCustomAddr;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBCrm;
import com.qmth.sop.business.mapper.SysCustomMapper;
import com.qmth.sop.business.service.SysCustomAddrService;
import com.qmth.sop.business.service.SysCustomService;
import com.qmth.sop.business.service.SysLevelRoleService;
import com.qmth.sop.business.service.TBCrmService;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.FieldUniqueEnum;
import com.qmth.sop.common.enums.ProductTypeEnum;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 客户表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-02 11:55:19
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class SysCustomServiceImpl extends ServiceImpl<SysCustomMapper, SysCustom> implements SysCustomService {
    @Resource
    SysLevelRoleService sysLevelRoleService;

    @Resource
    SysCustomAddrService sysCustomAddrService;

    @Resource
    TBCrmService tbCrmService;

    /**
     * 查询列表
     *
     * @param iPage
     * @return
     */
    @Override
    public IPage<SysCustomResult> query(Page<Map> iPage, ProductTypeEnum type, Long managerId, String name, Long levelId) {
        IPage<SysCustomResult> sysCustomResultIPage = this.baseMapper.query(iPage, Objects.nonNull(type) ? type.name() : null, Objects.nonNull(managerId) ? managerId : null, name, Objects.nonNull(levelId) ? levelId : null);
        sysCustomResultIPage.getRecords().forEach(e -> {
            if(e.getLevelId()!=null) {
                e.setRoleList(sysLevelRoleService.getList(e.getLevelId()));
            }
            e.setAddrList(sysCustomAddrService.list(new QueryWrapper<SysCustomAddr>().lambda().eq(SysCustomAddr::getCustomId,e.getId())));
        });
        return  sysCustomResultIPage;
    }


    /**
     * 新增修改客户表
     *
     * @param sysCustom
     */
    @Override
    @Transactional
    public boolean saveCustom(SysCustomResult sysCustom) {
        try {
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            if (Objects.isNull(sysCustom.getId())) {// 新增
                sysCustom.insertInfo(sysUser.getId());
            } else { // 修改
                sysCustom.updateInfo(sysUser.getId());
                sysCustomAddrService.remove(new QueryWrapper<SysCustomAddr>().lambda().eq(SysCustomAddr::getCustomId,sysCustom.getId()));
            }
            sysCustom.getAddrList().forEach(e->{
                e.setCustomId(sysCustom.getId());
                sysCustomAddrService.saveOrUpdate(e);
            });
            if(Objects.isNull(sysCustom.getLevelId())) {
                return saveOrUpdate(sysCustom,new LambdaUpdateWrapper<SysCustom>().set(SysCustom::getLevelId,null).eq(SysCustom::getId,sysCustom.getId()));
            }
            return saveOrUpdate(sysCustom);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3).replaceAll("'", "");
                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return false;

    }


    @Override
    @Transactional
    public void delete(Long id) {
        List<TBCrm> list = tbCrmService.list(new LambdaQueryWrapper<TBCrm>().eq(TBCrm::getCustomId, id));
        if(!list.isEmpty()) {
            throw ExceptionResultEnum.ERROR.exception("该客户下已有业务，不能删除");
        }
        this.removeById(id);
    }



}