package com.ruoyi.basic.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.RestResponse;
import com.ruoyi.basic.domain.SysAppIndex;
import com.ruoyi.basic.domain.YjStore;
import com.ruoyi.basic.mapper.YjStoreMapper;
import com.ruoyi.basic.service.YjAppUserService;
import com.ruoyi.basic.service.YjStoreService;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.AppLoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户表 服务实现类
 * </p>
 *
 * @author xn
 * @since 2022-09-28
 */
@Service
public class YjStoreServiceImpl extends ServiceImpl<YjStoreMapper, YjStore> implements YjStoreService {
    @Autowired
    private YjAppUserService appUserService;


    @Override
    public RestResponse storesTree(){
        Long userId = SecurityUtils.getAppLoginUser().getAppUserId();
        AppUser appUser =appUserService.getById(userId);
        if (ObjectUtil.isEmpty(appUser.getVisitStore())){
            List<YjStore> dtoList= baseMapper.getStoreList();
            dtoList.forEach(l->{
                l.setStoreName(l.getStoreName()+"（总店）");
                l.setChildList(baseMapper.getChilds(l.getId()));
            });
            return new RestResponse().setSuccess(true).setData(dtoList);
        }

        String tenantId= baseMapper.getOne(appUser.getVisitStore()).getTenantId();

        List<YjStore> list=getStoreListByTenantId(tenantId);
        List<YjStore> list1=new ArrayList<>();
//        list.forEach(l->{
//            if (l.getParentId().equals("0")){
//                l.setStoreName(l.getStoreName()+"（总店）");
//                l.setChildList(baseMapper.getChilds(l.getId()));
//            }
//        });
        YjStore store=list.stream().filter(s-> s.getParentId().equals(new Long(0))).collect(Collectors.toList()).get(0);
        list.remove(store);
        store.setChildList(list);
        list1.add(store);
        return new RestResponse().setSuccess(true).setData(list1);
    }
    @Autowired
    private RedisCache redisCache;
    @Override
    public RestResponse changeStore(Long visitStoreId){
        AppLoginUser loginUser=SecurityUtils.getAppLoginUser();
        AppUser appUser =loginUser.getAppUser();
        appUser.setVisitStore(visitStoreId);
        loginUser.setAppUser(appUser);
        //更新缓存（Redis 里的登录信息）
        Authentication auth = new UsernamePasswordAuthenticationToken(
                loginUser,
                null,
                loginUser.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(auth);
        String userKey = CacheConstants.LOGIN_APPUSER_TOKEN_KEY + loginUser.getToken();
        redisCache.setCacheObject(userKey, loginUser);

        appUserService.update(new UpdateWrapper<AppUser>()
                .eq("app_user_id",appUser.getId())
                .set("visit_store",visitStoreId));

        //返回新切换的门店信息
        YjStore yjStore= this.baseMapper.getOne(visitStoreId);
        return new RestResponse().setSuccess(true).setData(yjStore);
    }

    @Override
    public List<YjStore> getStoreListByTenantId(String tenantId){
        return baseMapper.getStoreListByTenantId(tenantId);
    }

    @Override
    public  YjStore getOne(Long id){
      return   baseMapper.getOne(id);
    }

    @Override
    public RestResponse getIndex(){

        List<SysAppIndex> appIndices=baseMapper.getAppIndex();

       return RestResponse.success().setData(appIndices);
    }
}
