package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.db.entity.SysUserMchStoreRela;
import com.jeequan.jeepay.service.mapper.SysUserMchStoreRelaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 操作员和商户门店关联表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2022-06-15
 */
@Service
public class SysUserMchStoreRelaService extends ServiceImpl<SysUserMchStoreRelaMapper, SysUserMchStoreRela> {

    @Autowired private MchStoreService mchStoreService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired private SysUserService sysUserService;

    /**
     * @author: xiaoyu
     * @date: 2022/10/10 16:14
     * @describe:
     */
    @Transactional(rollbackFor = Exception.class)
    public void bindStore(SysUserEntity sysUserEntity, String storeIdList) {

        MchInfo mchInfo = mchInfoService.getById(sysUserEntity.getBelongInfoId());
        if (mchInfo == null) {
            throw new BizException("商户不存在");
        }

        // 判断当前商户类型是否为M1商户
        if (!MchInfo.MCH_LEVEL_M1.equals(mchInfo.getMchLevel())) {
            throw new BizException("请先修改为M1商户");
        }

        if (!"[]".equals(storeIdList)) {
            // 门店ID
            List<String> storeIds = Arrays.asList(storeIdList.split(","));

            // 如果绑定门店ID不为空，则进行绑定
            if (CollectionUtil.isNotEmpty(storeIds)) {

                // 如果当前用户为店长类型 判断当前绑定的门店中知否已有店长用户 （一个门店只能拥有一个店长）
                if (SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType()) {
                    // 查询该用户所属店长的门店
                    List<SysUserMchStoreRela> storeRelaList = list(SysUserMchStoreRela.gw()
                            .eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId())
                            .eq(SysUserMchStoreRela::getUserType, SysUser.UEST_TYPE_DIRECTOR)
                    );

                    ArrayList<String> list = new ArrayList<>();
                    storeRelaList.forEach(item -> list.add(item.getStoreId()));

                    // 不包含已经所属店长的门店
                    List<SysUserMchStoreRela> relaList = list(SysUserMchStoreRela.gw()
                            .in(SysUserMchStoreRela::getStoreId, storeIds)
                            .notIn(CollectionUtil.isNotEmpty(list), SysUserMchStoreRela::getStoreId, list)
                            .eq(SysUserMchStoreRela::getUserType, SysUser.UEST_TYPE_DIRECTOR)
                    );

                    StringBuffer respStr = new StringBuffer();
                    respStr.append("以下门店已有店长，请检查后再绑定！");
                    if (CollectionUtil.isNotEmpty(relaList)) {
                        relaList.stream().forEach(item -> {
                            respStr.append(item.getStoreName() + "["+item.getStoreId()+"]; ");
                        });
                        // 返回不符合条件的门店信息
                        throw new BizException(respStr.toString());
                    }
                }

                // 获取门店信息列表
                List<MchStore> storeList = mchStoreService.list(MchStore.gw().in(MchStore::getStoreId, storeIds));

                // 关联关系列
                ArrayList<SysUserMchStoreRela> storeRelaList = new ArrayList<>();

                // 绑定对应门店
                storeList.stream().forEach(item ->{
                    SysUserMchStoreRela storeRela = new SysUserMchStoreRela();
                    storeRela.setSysUserId(sysUserEntity.getSysUserId());
                    storeRela.setUserType(sysUserEntity.getUserType());
                    storeRela.setStoreId(item.getStoreId());
                    storeRela.setStoreName(item.getStoreName());
                    storeRelaList.add(storeRela);
                });

                // 清除关联关系
                remove(SysUserMchStoreRela.gw().eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId()));

                // 绑定关联关系
                saveBatch(storeRelaList);
            }
        }else {
            // 清除关联关系
            remove(SysUserMchStoreRela.gw().eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId()));
        }

    }

    /**
     * 根据门店查询   超管和门店下的店长、店员
     */
    public Set<Long> selectSysUserIdsByStoreId(String mchNo, String storeId) {

        // 查询商户超管
        List<SysUserEntity> sysUserEntityList = sysUserService.list(SysUserEntity.gw()
                .in(SysUserEntity::getUserType, Arrays.asList(SysUser.UEST_TYPE_ADMIN, SysUser.UEST_TYPE_NORMAL))
                .eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.MCH)
                .eq(SysUserEntity::getBelongInfoId, mchNo)
                .eq(SysUserEntity::getState, CS.YES)
        );

        // 查询门店绑定的店长、店员
        List<SysUserMchStoreRela> relaList = this.list(SysUserMchStoreRela.gw()
                .eq(SysUserMchStoreRela::getStoreId, storeId)
                .in(SysUserMchStoreRela::getUserType, Arrays.asList(SysUser.UEST_TYPE_DIRECTOR, SysUser.UEST_TYPE_CASHIER))
        );
        if (CollUtil.isNotEmpty(relaList)) {
            List<Long> sysUserIdList = relaList.stream().map(SysUserMchStoreRela::getSysUserId).collect(Collectors.toList());

            // 添加店长、店员
            sysUserEntityList.addAll(sysUserService.list(SysUserEntity.gw()
                    .in(SysUserEntity::getSysUserId, sysUserIdList)
                    .eq(SysUserEntity::getState, CS.YES)
                    .eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.MCH)
                    .eq(SysUserEntity::getBelongInfoId, mchNo)));
        }

        return sysUserEntityList.stream().map(SysUserEntity::getSysUserId).collect(Collectors.toSet());
    }

    /**
     * 查询门店内的所有店长和收银员
     */
    public Set<Long> selectSysUserIdsByStoreIdList(List<String> storeIdList) {
        // 查询门店绑定的店长、店员
        List<SysUserMchStoreRela> relaList = this.list(SysUserMchStoreRela.gw()
                .in(SysUserMchStoreRela::getStoreId, storeIdList)
                .in(SysUserMchStoreRela::getUserType, Arrays.asList(SysUser.UEST_TYPE_DIRECTOR, SysUser.UEST_TYPE_CASHIER))
        );
        if (CollUtil.isEmpty(relaList)) {
            return null;
        }
        return relaList.stream().map(SysUserMchStoreRela::getSysUserId).collect(Collectors.toSet());
    }


}
