package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.mapper.MerchantClerkMapper;
import com.gxwebsoft.shop.service.MerchantClerkService;
import com.gxwebsoft.shop.entity.MerchantClerk;
import com.gxwebsoft.shop.param.MerchantClerkParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.val;
import org.springframework.stereotype.Service;

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

/**
 * 商家门店店员表Service实现
 *
 * @author 科技小王子
 * @since 2022-11-30 16:32:25
 */
@Service
public class MerchantClerkServiceImpl extends ServiceImpl<MerchantClerkMapper, MerchantClerk> implements MerchantClerkService {
    @Resource
    private UserService userService;

    @Override
    public PageResult<MerchantClerk> pageRel(MerchantClerkParam param) {
        PageParam<MerchantClerk, MerchantClerkParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<MerchantClerk> list = baseMapper.selectPageRel(page, param);
        // 查询会员的关联信息
        selectUser(list);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<MerchantClerk> listRel(MerchantClerkParam param) {
        List<MerchantClerk> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<MerchantClerk, MerchantClerkParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public MerchantClerk getByIdRel(Integer clerkId) {
        MerchantClerkParam param = new MerchantClerkParam();
        param.setClerkId(clerkId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public String getMerchantCodeByClerk(Integer loginUserId) {
      MerchantClerk merchantClerk = query().eq("user_id", loginUserId).one();
      if(merchantClerk != null){
        return merchantClerk.getMerchantCode();
      }
      return null;
    }

    /**
     * 批量查询会员的关联信息
     *
     * @param clerks 会员集合
     */
    private void selectUser(List<MerchantClerk> clerks) {
      if (clerks != null && clerks.size() > 0) {
        for (MerchantClerk clerk : clerks) {
          clerk.setUser(userService.getById(clerk.getUserId()));
        }
      }
    }
}
