package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.service.CustomerService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.system.domain.SysCustomer;
import org.dromara.system.domain.bo.SysCustomerBo;
import org.dromara.system.domain.vo.SysCustomerVo;
import org.dromara.system.mapper.SysCustomerMapper;
import org.dromara.system.service.ISysCustomerService;
import org.springframework.cache.annotation.Cacheable;
import org.dromara.yingpaipay.api.erp.domain.vo.CommonErpClientVo;
import org.springframework.stereotype.Service;

import org.dromara.yingpaipay.api.erp.CommonErpClientService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 客户管理 Service业务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysCustomerServiceImpl implements ISysCustomerService, CustomerService {

    private final SysCustomerMapper baseMapper;
    private final CommonErpClientService commonErpClientService;

    /**
     * 查询客户
     */
    @Override
    public SysCustomerVo queryById(Long id) {
        SysCustomerVo vo = baseMapper.selectVoById(id);
        fillAuthClientName(vo);
        return vo;
    }

    /**
     * 分页查询客户列表
     */
    @Override
    public TableDataInfo<SysCustomerVo> queryPageList(SysCustomerBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysCustomer> lqw = buildQueryWrapper(bo);
        Page<SysCustomerVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        fillAuthClientName(result.getRecords());
        return TableDataInfo.build(result);
    }

    /**
     * 批量填充授权客户信息
     */
    private void fillAuthClientName(List<SysCustomerVo> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<String> authClientFRowIDs = list.stream()
            .map(SysCustomerVo::getAuthClientFRowID)
            .filter(StringUtils::isNotBlank)
            .distinct()
            .toList();
        if (authClientFRowIDs.isEmpty()) {
            return;
        }
        Map<String, CommonErpClientVo> infoMap = commonErpClientService.selectInfoByFRowIDs(authClientFRowIDs);
        list.forEach(vo -> {
            CommonErpClientVo erpVo = infoMap.get(vo.getAuthClientFRowID());
            if (erpVo != null) {
                vo.setAuthClientName(erpVo.getName());
                vo.setAuthClientClass(erpVo.getClientClass());
                vo.setAuthClientEnterDate(erpVo.getEnterDate());
            }
        });
    }

    /**
     * 单个填充授权客户信息
     */
    private void fillAuthClientName(SysCustomerVo vo) {
        if (vo == null || StringUtils.isBlank(vo.getAuthClientFRowID())) {
            return;
        }
        Map<String, CommonErpClientVo> infoMap = commonErpClientService.selectInfoByFRowIDs(List.of(vo.getAuthClientFRowID()));
        CommonErpClientVo erpVo = infoMap.get(vo.getAuthClientFRowID());
        if (erpVo != null) {
            vo.setAuthClientName(erpVo.getName());
            vo.setAuthClientClass(erpVo.getClientClass());
            vo.setAuthClientEnterDate(erpVo.getEnterDate());
        }
    }

    private LambdaQueryWrapper<SysCustomer> buildQueryWrapper(SysCustomerBo bo) {
        LambdaQueryWrapper<SysCustomer> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), SysCustomer::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SysCustomer::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getWechatOpenid()), SysCustomer::getWechatOpenid, bo.getWechatOpenid());
        lqw.orderByDesc(SysCustomer::getId);
        return lqw;
    }

    /**
     * 修改客户
     */
    @Override
    public Boolean updateByBo(SysCustomerBo bo) {
        SysCustomer update = MapstructUtils.convert(bo, SysCustomer.class);
        boolean result = baseMapper.updateById(update) > 0;
        if (result && bo.getId() != null) {
            CacheUtils.evict(CacheNames.SYS_CUSTOMER_NAME, bo.getId());
        }
        return result;
    }

    /**
     * 批量删除客户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public SysCustomerVo queryByWechatUnionid(String wechatUnionid) {
        return baseMapper.selectVoOne(
            Wrappers.lambdaQuery(SysCustomer.class)
                .eq(SysCustomer::getWechatUnionid, wechatUnionid)
        );
    }

    @Override
    public SysCustomerVo queryByWechatOpenid(String wechatOpenid) {
        return baseMapper.selectVoOne(
            Wrappers.lambdaQuery(SysCustomer.class)
                .eq(SysCustomer::getWechatOpenid, wechatOpenid)
        );
    }

    @Cacheable(cacheNames = CacheNames.SYS_CUSTOMER_NAME, key = "#customerId")
    @Override
    public String selectUserNameById(Long customerId) {
        SysCustomer customer = baseMapper.selectOne(
            Wrappers.lambdaQuery(SysCustomer.class)
                .select(SysCustomer::getUserName)
                .eq(SysCustomer::getId, customerId)
        );
        return customer != null ? customer.getUserName() : null;
    }
}
