package com.yn.bftl.thirdparty.common.service;

import com.yn.bftl.common.modules.auth.entity.User;
import com.yn.bftl.common.modules.customer.entity.Customer;
import com.yn.bftl.thirdparty.common.enums.OperatorType;
import com.yn.bftl.common.common.exception.YnceError;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 客户端 Controller基类
 *
 * @author chendehuihuo
 * @date 2021/11/19 11:51
 **/
public class BaseMemberService extends Thread {

    /**
     * 客户端 token-登录令牌 在请求头中的名称
     */
    private static final String MEMBER_TOKEN_HEADER_NAME = "Member-Token";
    /**
     * 客户端 会员类型：user：B端  customer：C端
     */
    private static final String MEMBER_TYPE = "Member-Type";

    @Resource
    HttpServletRequest request;

    protected static Boolean debug;

    @Value("${spring.config.activate.on-profile}")
    private void setIsDebug(String value) {
        debug = !value.equals("prod");
    }

    /**
     * 获取请求
     *
     * @return HttpServletRequest
     */
    protected HttpServletRequest getRequest() {
        if (this.request == null) {
            // TODO：封装异常
            throw new YnceErrorException(YnceError.YNCE_100002);
        }
        return this.request;
    }

    /**
     * 获取会员类型
     *
     * @return String
     */
    protected OperatorType getMemberType() {
        return (OperatorType)request.getAttribute(MEMBER_TYPE);
    }

    /**
     * 获取B端信息
     *
     * @return
     */
    protected User getUser() {
        OperatorType member_type = getMemberType();
        if (member_type == null) {
            member_type = OperatorType.MEMBER_USER;
        }
        if (member_type == OperatorType.MEMBER_USER) {
            User user = (User) getMemberObject();
            if (user == null) {
                throw new YnceErrorException(YnceError.YNCE_201001);
            }
            return user;
        }
        throw new YnceErrorException(YnceError.YNCE_201001);
    }

    /**
     * 获取C端信息
     *
     * @return
     */
    protected Customer getCustomer() {
        OperatorType member_type = getMemberType();
        if (member_type == OperatorType.MEMBER_CUSTOMER) {
            Customer customer = (Customer) getMemberObject();
            if (customer == null) {
                throw new YnceErrorException(YnceError.YNCE_201001);
            }
            return customer;
        }
        throw new YnceErrorException(YnceError.YNCE_201001);
    }

    /**
     * 获取会员对象信息
     *
     * @return Object
     */
    protected Object getMemberObject() {
        Object object = request.getAttribute(MEMBER_TOKEN_HEADER_NAME);
        if (object == null) {
            throw new YnceErrorException(YnceError.YNCE_201001);
        }
        return object;
    }
}
