package com.dgtly.sync.utils;

import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.exception.BusinessException;
import com.dgtly.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

@Component
public class CustomerAccessTokenUtil {
    public enum UrlType{

        MANAGER,
        STOREGUIDE,
        FINANCE,

        MSQ,
        WQBM,
        RESELLER,
     /*   BOSSLIST,
        MANAGERLIST,
        BUSINESSLIST,*/
        WAREHOUSE,
        MANAGERLIST,
        AllRole,
        STAFF,
        BZ,
        XLS,
        HOMEDECORATION;


    }

    private static final Logger log = LoggerFactory.getLogger(CustomerAccessTokenUtil.class);

    private String accessToken;
    /**
     * 创建时间
     */
    private long createTime;

    /**
     * 过期时间单位s
     */
    private long expires;


    @Value(value = "${customer.appid:none}")
    private String appid;



    @Value(value = "${customer.appsecret:none}")
    private String appsecret;

    @Value(value = "${customer.domain:none}")
    private String domain;

    //获取token地址
    private String tokenUrl;
    //获取经销商负责人列表
    private String managerListUrl ;
    //获取经销商导购列表
    private String storeGuideListUrl ;
    //获取经销商财务人员列表(分页)
    private String financeListUrl ;
    private String MsqListUrl ;
    private String WqbmListUrl ;
    //获取经销商仓管人员列表(分页)
    private String warehouseListUrl ;
    //厨卫 获取老板列表
   /* private String bossListUrl ;*/
    //厨卫 获取经理列表
    private String managerUrl ;
    //获取经销商分销业务员人员列表(分页)
    private String resellerUrl ;
    //获取厨卫业务员人员
   // private String businessUrl ;
    //获取所有角色员列表
    private String allRoleUrl ;

    //获取经销商经销商人员列表
    private String staffUrl;

    //获取3.7经销商倍增人员
    private String bzUrl;

    //获取13.1新零售经销商人员
    private String xLSUrl;

    private String homeDecorationUrl;

    @PostConstruct
    public void init() {
        tokenUrl=domain+"/auth/jwt/v1/gettoken?appid=%s&appsecret=%s";
        //获取经销商负责人列表存在name，code
        managerListUrl =domain+"/wechatwork/diydt/v1/user/manager/list?access_token=%s";
        //获取经销商门店导购人员列表
        storeGuideListUrl =domain+"/wechatwork/diydt/v1/user/storeGuide/list?access_token=%s";
        //获取经销商财务人员列表(分页)存在name，code
        financeListUrl =domain+"/wechatwork/diydt/v2/user/finance/list?page=%s&access_token=%s";

        MsqListUrl =domain+"/wechatwork/diydt/v1/user/magic/list?page=%s&access_token=%s";

        WqbmListUrl =domain+"/api/diydt/v1/user/outwall/list?page=%s&access_token=%s";
        //获取经销商仓管人员列表(分页)存在name，code
        warehouseListUrl =domain+"/wechatwork/diydt/v2/user/warehouse/list?page=%s&access_token=%s";

       // bossListUrl =domain+"/wechatwork/chuwei/v1/user/boss/list?access_token=%s";
        managerUrl =domain+"/api/diydt/v3/user/manager/list?access_token=%s";

        //获取经销商分销业务员人员列表(分页)存在name，code
        resellerUrl =domain+"/api/diydt/v2/user/reseller/list?page=%s&access_token=%s";
      /*  businessUrl =domain+"/wechatwork/chuwei/v1/user/business/list?access_token=%s";*/
        allRoleUrl=domain+"/api/chuwei/v1/user/all/list?access_token=%s";

        staffUrl=domain+"/api/diydt/v1/user/staff/list?page=%s&access_token=%s";

        bzUrl=domain+"/api/diydt/v1/user/beizeng/list?page=%s&access_token=%s";

        xLSUrl=domain+"/api/es/v1/user/nrdistributor/list?access_token=%s";

        homeDecorationUrl=domain+"/wechatwork/diydt/v1/user/homeDecoration/list?access_token=%s";
    }

    public String getAccessToken(){

        JSONObject json;
        String url;

        try {
            //token未过期使用缓存的token
            long currentTiem = new Date().getTime();
            log.info("线程id{}",Thread.currentThread().getId());
            log.info("过期时间为{}",this.createTime+this.expires*1000);
            log.info("当前时间为{}",currentTiem);
            if(this.accessToken!=null &&(currentTiem-createTime)<(this.expires-10)*1000){
                log.info("本身的token为{}",this.accessToken);
                return this.accessToken;
            }

            log.info("开始通过接口获取经销商数据token：url==>",tokenUrl);
            String res = HttpUtils.sendSSLGet(String.format(tokenUrl,appid,appsecret));
            json = JSONObject.parseObject(res);

            log.info("结果返回==》",json);
            int code = json.getInteger("code");
            if(code==0){
                createTime = new Date().getTime();
                expires = json.getInteger("expires_in");
                accessToken=json.getString("access_token");
            }else{
                accessToken= null;
                createTime =0;
                expires = 0;
                log.error("获取经销商数据token出错，错误代码："+code+"，信息："+json.getString("msg"));
                throw new BusinessException("获取diy经销商接口报错，错误代码："+code+"，信息："+json.getString("msg"));
            }
        }catch (Exception e){
            reSetToken();
            log.error("获取token错误",e);
            throw e;
        }
        return accessToken;

    }


    public String getUrl(UrlType type,String pageNum){
        String token = getAccessToken();
        String url ="";
        switch (type) {
            case MANAGER:
                url = String.format(managerListUrl,token);
                break;
            case STOREGUIDE:
                url = String.format(storeGuideListUrl,token);
                break;
            case FINANCE:
                url = String.format(financeListUrl,pageNum,token);
                break;
            case MSQ:
                url = String.format(MsqListUrl,pageNum,token);
                break;
            case WQBM:
                url = String.format(WqbmListUrl,pageNum,token);
                break;
            case RESELLER:
                url = String.format(resellerUrl,pageNum,token);
                break;
            case WAREHOUSE:
                url = String.format(warehouseListUrl,pageNum,token);
                break;
            case MANAGERLIST:
                url = String.format(managerUrl,token);
                break;
      /*      case BOSSLIST:
                url = String.format(bossListUrl,token);
                break;
            case BUSINESSLIST:
                url = String.format(businessUrl, token);
                break;*/
            case AllRole:
                url = String.format(allRoleUrl,token);
                break;
            case STAFF:
                url = String.format(staffUrl,pageNum,token);
                break;
            case BZ:
                url = String.format(bzUrl,pageNum,token);
                break;
            case XLS:
                url = String.format(xLSUrl, token);
                break;
            case HOMEDECORATION:
                url = String.format(homeDecorationUrl, token);
        }
        return url;
    }
    public void reSetToken() {
        log.info("清除经销商token缓存");
        this.accessToken =null;
        this.expires = 0;

    }


}
