package com.taais.mf.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.taais.common.core.utils.MapstructUtils;
import com.taais.common.core.utils.StringUtils;
import com.taais.common.orm.core.page.PageQuery;
import com.taais.common.orm.core.page.TableDataInfo;
import com.taais.common.orm.core.service.impl.BaseServiceImpl;
import com.taais.mf.domain.Customer;
import com.taais.mf.domain.Goods;
import com.taais.mf.domain.bo.CustomerBo;
import com.taais.mf.domain.vo.CustomerVo;
import com.taais.mf.mapper.CustomerMapper;
import com.taais.mf.mapper.GoodsMapper;
import com.taais.mf.service.ICustomerService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.taais.mf.domain.table.CustomerTableDef.CUSTOMER;
import static com.taais.mf.domain.table.GoodsTableDef.GOODS;

/**
 * 客户主表Service业务层处理
 *
 * @author wgk
 * 2024-01-06
 */
@Service
public class CustomerServiceImpl extends BaseServiceImpl<CustomerMapper, Customer> implements ICustomerService {
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private GoodsMapper goodsMapper;

    @Override
    public QueryWrapper query() {
        return super.query().from(CUSTOMER);
    }

    private QueryWrapper buildQueryWrapper(CustomerBo customerBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(CUSTOMER.CUSTOMER_NAME.like(customerBo.getCustomerName()));
        queryWrapper.and(CUSTOMER.PHONENUMBER.eq(customerBo.getPhonenumber()));
        queryWrapper.and(CUSTOMER.GENDER.eq(customerBo.getGender()));

        return queryWrapper;
    }

    /**
     * 查询客户主表
     *
     * @param customerId 客户主表主键
     * @return 客户主表
     */
    @Override
    public CustomerVo selectById(Long customerId) {
        return customerMapper.selectOneWithRelationsByQueryAs(query().where(CUSTOMER.CUSTOMER_ID.eq(customerId)), CustomerVo.class);

    }

    /**
     * 查询客户主表列表
     *
     * @param customerBo 客户主表Bo
     * @return 客户主表集合
     */
    @Override
    public List<CustomerVo> selectList(CustomerBo customerBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(customerBo);
        return customerMapper.selectListWithRelationsByQueryAs(queryWrapper, CustomerVo.class);
    }

    /**
     * 分页查询客户主表列表
     *
     * @param customerBo 客户主表Bo
     * @return 分页客户主表集合
     */
    @Override
    public TableDataInfo<CustomerVo> selectPage(CustomerBo customerBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(customerBo);
        //忽略注解，本次不查询子表数据
        RelationManager.addIgnoreRelations("goodsList");
        Page<CustomerVo> page = customerMapper.paginateWithRelationsAs(PageQuery.build(), queryWrapper, CustomerVo.class);
        return TableDataInfo.build(page);
    }

    /**
     * 新增客户主表
     *
     * @param customerBo 客户主表Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Transactional
    @Override
    public boolean insert(CustomerBo customerBo) {
        Customer customer = MapstructUtils.convert(customerBo, Customer.class);

        boolean inserted = this.save(customer);//使用全局配置的雪花算法主键生成器生成ID值
        if (inserted && ObjectUtil.isNotNull(customer)) {
            return insertGoods(customer);
        }
        return false;
    }

    /**
     * 修改客户主表
     *
     * @param customerBo 客户主表Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Transactional
    @Override
    public boolean update(CustomerBo customerBo) {
        Customer customer = MapstructUtils.convert(customerBo, Customer.class);
        if (ObjectUtil.isNotNull(customer) && ObjectUtil.isNotNull(customer.getCustomerId())) {
            boolean updated = this.updateById(customer);
            if (updated) {
                QueryWrapper queryWrapper = QueryWrapper.create().from(GOODS).where(GOODS.CUSTOMER_ID.eq(customer.getCustomerId()));
                goodsMapper.deleteByQuery(queryWrapper);
                return insertGoods(customer);
            }
        }
        return false;
    }

    /**
     * 批量删除客户主表
     *
     * @param customerIds 需要删除的客户主表主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] customerIds) {
        QueryWrapper queryWrapper = QueryWrapper.create().from(GOODS).where(GOODS.CUSTOMER_ID.in(Arrays.asList(customerIds)));
        goodsMapper.deleteByQuery(queryWrapper);
        return this.removeByIds(Arrays.asList(customerIds));
    }

    /**
     * 新增商品子信息
     *
     * @param customer 客户主表对象
     */
    private boolean insertGoods(Customer customer) {
        List<Goods> goodsList = customer.getGoodsList();
        Long customerId = customer.getCustomerId();
        if (StringUtils.isNotNull(goodsList)) {
            List<Goods> list = new ArrayList<>();
            for (Goods goods : goodsList) {
                goods.setCustomerId(customerId);
                list.add(goods);
            }
            if (list.size() > 0) {
                return goodsMapper.insertBatch(list) > 0;
            }
        }
        return true;
    }
}
