package com.fs.third.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.CluesUtils;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.entity.SysDictData;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;

import com.fs.common.utils.DateUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.crm.domain.CrmCustomerThird;
import com.fs.crm.param.CrmLineCustomerImportParam;
import com.fs.crm.param.CrmThirdFeiyuCluesSearchParam;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.crm.service.ICrmCustomerThirdService;
import com.fs.crm.vo.CrmCustomerListVO;
import com.fs.framework.web.service.TokenService;
import com.fs.system.service.ISysDictTypeService;
import com.fs.third.http.HttpUtils;
import com.fs.third.param.FeiyuCluesParam;
import com.fs.third.param.FeiyuImportCluesParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/third/feiyu")
public class FeiyuCustomerController extends BaseController {

    public static String  appId="1770748979316843";
    public static String  appSecret="106c17623dd0eaba37dab935b9839c698c0876d1";

    public static String open_api_url_prefix = "https://ad.oceanengine.com/open_api/";
    public static String uri = "oauth2/access_token/";

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICrmCustomerThirdService crmCustomerThirdService;

    @Autowired
    private ICrmCustomerService crmCustomerService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @PostMapping(value = "/oauthCallback")
    public R oauthCallback(@RequestBody JSONObject param)
    {
        String authCode=param.getString("authCode");
        Long id=param.getLong("thirdId");
        CrmCustomerThird crmCustomerThird=crmCustomerThirdService.selectCrmCustomerThirdById(id);
        String refresh_token=redisCache.getCacheObject("token-feiyu:refresh"+crmCustomerThird.getId());
        if(StringUtils.isEmpty(refresh_token)) {
            return getAccessTokenAct(crmCustomerThird,authCode);
        }
        return getAccessToken(crmCustomerThird,authCode);
    }

    public R getAccessToken(CrmCustomerThird crmCustomerThird, String authCode){
        if(StringUtils.isEmpty(crmCustomerThird.getRefreshToken())){
            return getAccessTokenAct(crmCustomerThird,authCode);
        }
        String access_token=redisCache.getCacheObject("token-feiyu:access"+crmCustomerThird.getId());
        String refresh_token=redisCache.getCacheObject("token-feiyu:refresh"+crmCustomerThird.getId());
        if(StringUtils.isEmpty(refresh_token)){  //refreshToken失效
            throw new CustomException("refreshToken已失效，请重新授权",501);
        }else{
            if(StringUtils.isEmpty(access_token)){
                if(StringUtils.isEmpty(crmCustomerThird.getAccessToken())){
                    return getAccessTokenAct(crmCustomerThird,authCode);
                }else{
                    return refreshTokenAct(crmCustomerThird,refresh_token);
                }
            }else{
                if(StringUtils.isNotEmpty(authCode)) {  //点击授权操作并获取AccessToken
                    getAdvertisers(crmCustomerThird);
                }
                return R.ok().put("thirds",crmCustomerThird);
            }
        }
    }


    public String getAccessToken(CrmCustomerThird crmCustomerThird){
         R accessToken=getAccessToken(crmCustomerThird,"");
         crmCustomerThird= (CrmCustomerThird) accessToken.get("thirds");
         return crmCustomerThird.getAccessToken();
    }


    public R getAccessTokenAct(CrmCustomerThird crmCustomerThird, String authCode){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("app_id",crmCustomerThird.getAppId());
            jsonObject.put("secret",crmCustomerThird.getAppSecret());
            jsonObject.put("grant_type","auth_code");
            jsonObject.put("auth_code",authCode);
            String paramStr=jsonObject.toJSONString();
            String postStr = HttpUtils.doPost(open_api_url_prefix+"oauth2/access_token/",paramStr);
            JSONObject obj = JSONObject.parseObject(postStr);
            Integer code= obj.getInteger("code");
            String message=obj.getString("message");
            if(code==0){
                JSONObject data = obj.getJSONObject("data");
                //对于短期token，access_token有效期为1天，refresh_token有效期30天，超出有效期token将失效。 当access_token超时后，可以使用refresh-token（通过/oauth2/refresh_token/接口） 刷新，每次刷新都会产生新的access_token和refresh_token，同时重置二者的有效期。
                String access_token=data.getString("access_token");
                String refresh_token=data.getString("refresh_token");
                Integer expires_in=data.getInteger("expires_in");
                Integer refresh_token_expires_in=data.getInteger("refresh_token_expires_in");
                redisCache.setCacheObject("token-feiyu:access"+crmCustomerThird.getId(),access_token,expires_in-300, TimeUnit.SECONDS);
                redisCache.setCacheObject("token-feiyu:refresh"+crmCustomerThird.getId(),refresh_token,refresh_token_expires_in-300, TimeUnit.SECONDS);

                crmCustomerThird.setAccessToken(access_token);
                crmCustomerThird.setRefreshToken(refresh_token);
                crmCustomerThird.setAccessStatus(1);
                crmCustomerThird.setRefreshStatus(1);
                crmCustomerThird.setStatus(1L);//设置授权状态

                //获取授权账户信息
                postStr = HttpUtils.sendGetWithToken(open_api_url_prefix+"2/user/info/","",getAccessToken(crmCustomerThird));
                obj = JSONObject.parseObject(postStr);
                data = obj.getJSONObject("data");
                String display_name= data.getString("display_name");
                //String email= data.getString("email");
                crmCustomerThird.setAccount(display_name);

                crmCustomerThirdService.updateCrmCustomerThird(crmCustomerThird);
                if(StringUtils.isEmpty(crmCustomerThird.getAdvertiserIds())){
                    getAdvertisers(crmCustomerThird);
                }
                return R.ok().put("thirds",crmCustomerThird);
            }else{
                throw new CustomException(message,500);
            }
        }
        catch (Exception e) {
            throw new CustomException("系统异常,请联系管理员",500);
        }
    }


    public R refreshTokenAct(CrmCustomerThird crmCustomerThird, String refreshToken){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("app_id",crmCustomerThird.getAppId());
            jsonObject.put("secret",crmCustomerThird.getAppSecret());
            jsonObject.put("grant_type","refresh_token");
            jsonObject.put("refresh_token",refreshToken);
            String paramStr=jsonObject.toJSONString();
            String postStr = HttpUtils.doPost(open_api_url_prefix+"oauth2/refresh_token/",paramStr);
            JSONObject obj = JSONObject.parseObject(postStr);
            Integer code= obj.getInteger("code");
            String message=obj.getString("message");
            if(code==0){
                JSONObject data = obj.getJSONObject("data");
                String access_token=data.getString("access_token");
                String refresh_token=data.getString("refresh_token");
                Integer expires_in=data.getInteger("expires_in");
                Integer refresh_token_expires_in=data.getInteger("refresh_token_expires_in");
                crmCustomerThird.setAccessToken(access_token);
                crmCustomerThird.setRefreshToken(refresh_token);
                crmCustomerThird.setAccessStatus(1);
                crmCustomerThird.setRefreshStatus(1);
                //提前5分钟设置过期
                redisCache.setCacheObject("token-feiyu:access"+crmCustomerThird.getId(),access_token,expires_in-300, TimeUnit.SECONDS);
                redisCache.setCacheObject("token-feiyu:refresh"+crmCustomerThird.getId(),refresh_token,refresh_token_expires_in-300, TimeUnit.SECONDS);
                crmCustomerThirdService.updateCrmCustomerThird(crmCustomerThird);
                return R.ok().put("thirds",crmCustomerThird);

            }else{
                throw new CustomException(message,500);
            }

        }
        catch (Exception e) {
            throw new CustomException("程序异常,请联系管理员",500);
        }
    }

    @PostMapping("/getAdvertisers")
    public R getAdvertisers(@RequestBody CrmCustomerThird crmCustomerThird){
        try {

            String paramStr= "app_id=" + crmCustomerThird.getAppId() + "&secret="+crmCustomerThird.getAppSecret()+"&access_token="+getAccessToken(crmCustomerThird);
            String postStr = HttpUtils.sendGet(open_api_url_prefix+"oauth2/advertiser/get/",paramStr);
            JSONObject obj = JSONObject.parseObject(postStr);
            Integer code= obj.getInteger("code");
            String message=obj.getString("message");
            List<Long> advIds=new ArrayList<>();
            List<String> advNames=new ArrayList<>();
            if(code==0){
                crmCustomerThird.setAdvertiserIds("");
                crmCustomerThird.setAdvertiserNames("");
                JSONObject data = obj.getJSONObject("data");
                JSONArray list=data.getJSONArray("list");
                for(int i =0;i<list.size();i++){
                    JSONObject jsonObj = (JSONObject)list.get(i); //obj为JSONObject数据
                    Integer advertiser_role = jsonObj.getInteger("advertiser_role"); //1-普通广告主，2-纵横组织账户，3-一级代理商，4-二级代理商，6-星图账号
                    if(advertiser_role==2){
                        getOrgAdvertisers(crmCustomerThird,jsonObj.getLong("advertiser_id"));
                    }else{
                        advIds.add(jsonObj.getLong("advertiser_id"));
                        advNames.add(jsonObj.getString("advertiser_name"));
                        crmCustomerThird=getMutileAdsCrm(crmCustomerThird, StringUtils.join(advIds, ","), StringUtils.join(advNames, ","));
                        crmCustomerThirdService.updateCrmCustomerThird(crmCustomerThird);
                    }
                }
                return R.ok().put("thirds",crmCustomerThird);
            }else{
                throw new CustomException(message,500);
            }

        }
        catch (Exception e) {
            throw new CustomException(e.getMessage(),500);
        }
    }


    //获取纵横组织下的广告主
    public R getOrgAdvertisers(CrmCustomerThird crmCustomerThird, Long advertiserId){
        try {

            String paramStr= "advertiser_id=" + advertiserId;
            String postStr = HttpUtils.sendGetWithToken(open_api_url_prefix+"2/majordomo/advertiser/select/",paramStr,getAccessToken(crmCustomerThird));
            JSONObject obj = JSONObject.parseObject(postStr);
            Integer code= obj.getInteger("code");
            String message=obj.getString("message");
            List<Long> advIds=new ArrayList<>();
            List<String> advNames=new ArrayList<>();
            if(code==0){
                JSONObject data = obj.getJSONObject("data");
                JSONArray list=data.getJSONArray("list");
                for(int i =0;i<list.size();i++){
                    JSONObject jsonObj = (JSONObject) list.get(i); //obj 为JSONObject数据
                    advIds.add(jsonObj.getLong("advertiser_id"));
                    advNames.add(jsonObj.getString("advertiser_name"));
                }
                String advertiserIds=crmCustomerThird.getAdvertiserIds();
                String advertiserNames=crmCustomerThird.getAdvertiserNames();
                if(StringUtils.isNotEmpty(advertiserIds)){
                    advertiserIds=(advertiserIds+","+ StringUtils.join(advIds, ","));
                }else{
                    advertiserIds= StringUtils.join(advIds, ",");
                }
                if(StringUtils.isNotEmpty(advertiserNames)){
                    advertiserNames=(advertiserNames+","+ StringUtils.join(advNames, ","));
                }else{
                    advertiserNames= StringUtils.join(advNames, ",");
                }
                crmCustomerThird.setAdvertiserIds(advertiserIds);
                crmCustomerThird.setAdvertiserNames(advertiserNames);
                crmCustomerThirdService.updateCrmCustomerThird(crmCustomerThird);
                return R.ok().put("thirds",crmCustomerThird);

            }else{
                throw new CustomException(message,500);
            }

        }
        catch (Exception e) {
            throw new CustomException(e.getMessage(),500);
        }
    }

    //获取授权广告主账户下的线索客户
    @PostMapping("/getClues")
    public R getClues(@RequestBody FeiyuCluesParam crmCustomerThird){
        try {
            String paramStr= "advertiser_ids=["+crmCustomerThird.getAdvertiserIds()+"]&page="+crmCustomerThird.getPageNum()+"&page_size="+crmCustomerThird.getPageSize();
            if(StringUtils.isNotEmpty(crmCustomerThird.getStartTime())){
                paramStr+=("&start_time="+crmCustomerThird.getStartTime());
            }
            if(StringUtils.isNotEmpty(crmCustomerThird.getEndTime())){
                paramStr+=("&end_time="+crmCustomerThird.getEndTime());
            }
            paramStr=paramStr.replace(" ", "%20");
            String postStr = HttpUtils.sendGetWithToken(open_api_url_prefix+"2/tools/clue/get/", paramStr,getAccessToken(crmCustomerThird));
            JSONObject obj = JSONObject.parseObject(postStr);
            Integer code= obj.getInteger("code");
            String message=obj.getString("message");
            List<Long> advIds=new ArrayList<>();
            List<String> advNames=new ArrayList<>();
            if(code==0){
                JSONObject data = obj.getJSONObject("data");
                JSONArray list=data.getJSONArray("list");
                for(int i =0;i<list.size();i++){

                    JSONObject jsonObj = (JSONObject) list.get(i); //obj 为JSONObject数据
                    advIds.add(jsonObj.getLong("advertiser_id"));
                    advNames.add(jsonObj.getString("advertiser_name"));

                    CrmThirdFeiyuCluesSearchParam crmFeiyuCluesSearchParam=new CrmThirdFeiyuCluesSearchParam();
                    crmFeiyuCluesSearchParam.setClueId(jsonObj.getString("clue_id"));
                    crmFeiyuCluesSearchParam.setMobile(jsonObj.getString("telephone"));
                    crmFeiyuCluesSearchParam.setThirdAccount(crmCustomerThird.getAccount());
                    if(crmCustomerService.checkCrmThirdFeiyuClue(crmFeiyuCluesSearchParam)>0){
                        jsonObj.put("has_import",1);
                    }else{
                        jsonObj.put("has_import",0);
                    }
                }
                CrmCustomerListVO crmCustomerListVO = new CrmCustomerListVO();
//              CrmCustomer crmParam=new CrmCustomer();
//              crmParam.setTrafficSource("字节-抖音");
//              List<CrmCustomerListVO>  crmListVO = crmCustomerService.selectCrmCustomerListVO(crmParam);
//              if(crmListVO.size()>0){
//                  crmCustomerListVO=crmListVO.get(0);
//              }
                return R.ok().put("data",data).put("crm",crmCustomerListVO);

            }else{
                throw new CustomException(message,500);
            }
        }
        catch (Exception e) {
            throw new CustomException(e.getMessage(),500);
        }
    }

    /**
     * 导入飞鱼平台线索客户
     */
//    @PreAuthorize("@ss.hasPermi('third:third:edit')")
    @Log(title = "导入飞鱼平台线索客户", businessType = BusinessType.UPDATE)
    @PutMapping("/importThird")
    public AjaxResult importThird(@RequestBody FeiyuImportCluesParam param)
    {
        List<JSONObject> crmList=param.getCrmList();
        List<CrmLineCustomerImportParam> list=new ArrayList<CrmLineCustomerImportParam>();
        for (JSONObject jsObj:crmList) {
            CrmLineCustomerImportParam crmImportParam = new CrmLineCustomerImportParam();
            crmImportParam.setRegisterDate(jsObj.getString("create_time"));
            crmImportParam.setCustomerName(jsObj.getString("name"));
            crmImportParam.setMobile(jsObj.getString("telephone"));
            List<SysDictData> listDict=dictTypeService.selectDictDataByType("crm_third_feiyu_clue_type");
            for (SysDictData data:listDict) {
                if(Integer.parseInt(data.getDictValue())==jsObj.getInteger("clue_type")){
                    crmImportParam.setRegisterType(data.getDictLabel());
                    break;
                }
            }
            if(CluesUtils.sourceMap.containsKey(param.getAccount())){
                List<SysDictData> listSource=dictTypeService.selectDictDataByType("crm_customer_source");
                for (SysDictData data:listSource) {
                    if(data.getDictLabel().contentEquals(CluesUtils.sourceMap.get(param.getAccount())) ){
                        crmImportParam.setSource(data.getDictValue());
                        break;
                    }
                }
            }
            crmImportParam.setThirdAccount(param.getAccount());
            crmImportParam.setImportType(1);  //自动
            crmImportParam.setTrafficSource("字节-抖音");
            crmImportParam.setRegisterLinkUrl(jsObj.getString("external_url"));
            crmImportParam.setAddress(jsObj.getString("location"));
            crmImportParam.setRegisterSubmitTime(jsObj.getString("create_time_detail"));
            crmImportParam.setClueId(jsObj.getString("clue_id"));
            list.add(crmImportParam);
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = crmCustomerService.importLineCustomer(list, operName);
        return AjaxResult.success(message);
    }

    //线索回调url
    @RequestMapping(value = "/clueNotify",method={RequestMethod.POST, RequestMethod.GET})
    public HashMap<String, Object> clueNotify(@RequestBody JSONObject jsObj){
        List<CrmLineCustomerImportParam> list=new ArrayList<CrmLineCustomerImportParam>();
        CrmLineCustomerImportParam crmImportParam = new CrmLineCustomerImportParam();
        String create_time=jsObj.getString("create_time");
        Long timestamp =  new Long(create_time);
        Date createTime = new Date(timestamp*1000);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String createStrings = formatter.format(createTime);
        crmImportParam.setRegisterDate(createStrings);
        crmImportParam.setRegisterSubmitTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",createTime));
        crmImportParam.setCustomerName(jsObj.getString("name"));
        crmImportParam.setMobile(jsObj.getString("telphone"));
        List<SysDictData> listDict=dictTypeService.selectDictDataByType("crm_third_feiyu_clue_type");
        for (SysDictData data:listDict) {
            if(Integer.parseInt(data.getDictValue())==jsObj.getInteger("clue_type")){
                crmImportParam.setRegisterType(data.getDictLabel());
                break;
            }
        }
        String account=jsObj.getString("account");
        if(CluesUtils.sourceMap.containsKey(account)){
            List<SysDictData> listSource=dictTypeService.selectDictDataByType("crm_customer_source");
            for (SysDictData data:listSource) {
                if(data.getDictLabel().contentEquals(CluesUtils.sourceMap.get(account)) ){
                    crmImportParam.setSource(data.getDictValue());
                    break;
                }
            }
        }
        crmImportParam.setThirdAccount(account);
        crmImportParam.setImportType(1);  //自动
        crmImportParam.setTrafficSource("字节-抖音");
        crmImportParam.setRegisterLinkUrl(jsObj.getString("external_url"));
        crmImportParam.setAddress(jsObj.getString("location"));
        crmImportParam.setClueId(jsObj.getString("id"));
        list.add(crmImportParam);
//      LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//      String operName = loginUser.getUsername();
        String message = crmCustomerService.importLineCustomer(list, "admin");
        HashMap<String,Object> returnMap=new HashMap<String,Object>(){
            {
                put("code", 0);
                put("message", "success");
            }
        };
        System.out.println(" clueId:"+crmImportParam.getClueId()+" \n" );
        return returnMap;
    }

    public CrmCustomerThird getMutileAdsCrm(CrmCustomerThird crmCustomerThird, String advIdsStr, String advNamesStr){
        String advertiserIds=crmCustomerThird.getAdvertiserIds();
        String advertiserNames=crmCustomerThird.getAdvertiserNames();
        if(StringUtils.isNotEmpty(advertiserIds)){
            advertiserIds=(advertiserIds+","+ StringUtils.join(advIdsStr, ","));
        }else{
            advertiserIds=advIdsStr;
        }
        if(StringUtils.isNotEmpty(advertiserNames)){
            advertiserNames=(advertiserNames+","+advNamesStr);
        }else{
            advertiserNames=advNamesStr;
        }
        crmCustomerThird.setAdvertiserIds(advertiserIds);
        crmCustomerThird.setAdvertiserNames(advertiserNames);
        return crmCustomerThird;
    }

}
