package com.aircraft.modules.system.service.impl;

import com.aircraft.base.BaseEntity;
import com.aircraft.modules.security.service.UserCacheManager;
import com.aircraft.modules.system.domain.CnCustomer;
import com.aircraft.modules.system.mapper.CnCustomerMapper;
import com.aircraft.modules.system.service.CnCustomerService;
import com.aircraft.utils.PageResult;
import com.aircraft.utils.PageUtil;
import com.aircraft.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cli
 * @since 2025-07-09
 */
@RequiredArgsConstructor
@Service
public class CnCustomerServiceImpl extends ServiceImpl<CnCustomerMapper, CnCustomer> implements CnCustomerService {

    private final UserCacheManager userCacheManager;

    @Override
    public List<CnCustomer> list(CnCustomer example) {
        return this.list(buildWrapper(example));
    }

    @Override
    public PageResult<CnCustomer> page(CnCustomer example, IPage page) {
        return PageUtil.toPage(this.page(page,buildWrapper(example)).getRecords());
    }

    @Override
    public CnCustomer findByPhone(String phone) {
        QueryWrapper<CnCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(CnCustomer::getPhone,phone)
                .eq(BaseEntity::getDelFlag,0);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public CnCustomer findByUserName(String username) {
        QueryWrapper<CnCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(CnCustomer::getUsername,username)
                .eq(BaseEntity::getDelFlag,0);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void updatePass(String username, String encryptPassword) {
        this.baseMapper.updatePass(username, encryptPassword);
        userCacheManager.cleanCustomerCache(username);
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<CnCustomer> buildWrapper(CnCustomer example) {
        String phone = example.getPhone();
        QueryWrapper<CnCustomer> wrapper     = new QueryWrapper<>();
        wrapper.lambda()
                .eq(StringUtils.isNotEmpty(phone),CnCustomer::getPhone,phone);
        return wrapper;
    }
}
