package com.ruoyi.vo;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.code.Token;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
public class RyController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private CustomerService customerService;

    @Resource
    private StoreService storeService;


    /**
     * 获取用户Id
     *
     * @return
     */
    protected UserVo getUserVo() {
        //获取当前登录用户
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            return new UserVo(-1,-1L);
        }
        String tokenStr = redisTemplate.opsForValue().get(token);
        if (StrUtil.isBlank(tokenStr)) {
            return new UserVo(-1,-1L);
        }

        //获取token前缀
        String prefix = token.split("_")[0];

        //用户类型
        Integer userType = UserEnums.valueOf(prefix).getCode();

        //用户id
        Long userId = Long.valueOf(tokenStr);

        return new UserVo(userType,userId);
    }

    /**
     * @param convertUserType 当前用户类型转换为 convertUserType类型
     * @return
     */
    protected UserVo getUserVo(Integer convertUserType) {
        UserVo userVo = new UserVo();
        //获取当前登录用户
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            userVo.setUserId(-1L);
            userVo.setUserType(-1);
            return userVo;
        }

        String userId = redisTemplate.opsForValue().get(token);
        if (StrUtil.isBlank(userId)) {
            userVo.setUserId(-1L);
            userVo.setUserType(-1);
            return userVo;
        }

        if (!token.startsWith(Token.customer) && !token.startsWith(Token.store)) {
            userVo.setUserType(-1);
        } else {
            userVo.setUserType(convertUserType);
        }
        userVo.setUserId(userId(convertUserType, userId, token));

        return userVo;
    }

    /**
     * 获取用户id
     *
     * @param convertUserType
     * @param userId
     * @param token
     * @return
     */
    private Long userId(Integer convertUserType, String userId, String token) {
        switch (convertUserType) {
            case 1:
                //当前登入token为商家，转换为 用户id
                if (token.startsWith(Token.store)) {
                    Store store = storeService.getById(Long.valueOf(userId));
                    if (store != null) {
                        return store.getCustomerId();
                    }
                }
                break;
            case 2:
                //当前登入token为商家，转换为 用户id
                if (token.startsWith(Token.customer)) {
                    Store store = storeService.getOne(new QueryWrapper<Store>().lambda()
                            .eq(Store::getCustomerId, Long.valueOf(userId))
                            .ne(Store::getDelFlag, PublicCommon.删除));
                    if (store != null) {
                        return store.getId();
                    }
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + convertUserType);
        }
        return Long.valueOf(userId);
    }


    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = pageDomain.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
    }


    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(Integer.valueOf(new PageInfo(list).getTotal() + ""));
        return rspData;
    }
    protected TableDataInfo getDataTable(Page<?> page)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getRecords());
        rspData.setTotal(Integer.valueOf(new PageInfo(page.getRecords()).getTotal() + ""));
        return rspData;
    }

}
