#coding:utf-8
import requests
import redis
import json

from utils.views import decrypt_11h

def get_token(is_test=True):
    """
    韩忠玉@2024-01-18 获取汉得TOKEN
    如果redis未过期，直接从redis取；否则请求汉得服务器
    """
    clientid = 'api-tj'
    if is_test:
        sK='hand_test_auth_token'        
        pwd = r'%F7zZ8bCSD5*zFHwdr'
        url ='https://winesmptest.cofco.com/linktest/action/base/user/apilogin'
    else:
        sK='hand_production_auth_token' 
        pwd = r'hD2N4Qj6%c8)6EnfPd'
        url = 'https://winesmp.cofco.com/prod/action/base/user/apilogin'

    # 2024-01-16 redis存储汉得auth key 汉得过期时间2小时
    ex=5000 # 设置redis过期时间
    data={'e':'', 'token':'', 'status_code':200,'text':'' } 
    rd=redis.StrictRedis(connection_pool=redis.ConnectionPool(host='127.0.0.1', port=16379, db=4, password='tjredis139', decode_responses=True))        
    tk=rd.get(sK)
    if tk:
        # redis保存的token未过期
        data['token']=tk
    else:        
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        d = {"clientId": clientid, "password": pwd}            
        r = requests.post(url, d)
        result=r.text
        status=r.status_code            
        data['status_code']=status
        data['text']=result            
        if  status== 200:
            try:
                d = r.json()
                tk = d['result']
                data['token']=tk                   
                rd.set(sK,tk,ex=ex) 
            except Exception:
                data['e']='汉得返回的token结构出错'
        else:
            data['e']='汉得token服务失败'            
    return data  


def label_status(label_code,is_test):
    """
    韩忠玉@2024-01-18 查询标签在汉得系统内的状态信息
    """
    data={'e':'','status':{},'msg':''}
    d=get_token(is_test)
    tk=d['token']
    if tk:
        if is_test:    
            url="https://winesmptest.cofco.com/linktest/trml/link/asset/queryAssetStatusByTJ"
        else:    
            url="https://winesmp.cofco.com/prod/trml/link/asset/queryAssetStatusByTJ"
        headers = {
            "Authorization": "bearer " + tk,
            "Content-type": 'application/json;charset=UTF-8'
        } 
        d={"prodCodeNo": label_code}
        rr=requests.post(url, headers=headers, json=d)
        cd=rr.status_code
        if cd==200:
            a=[]
            dd=json.loads(rr.text)
            rt=dd['result']  
            if dd['success']: 
                data['status']={                    
                    'decapCode':rt['decapCode'],
                    'circulateCode':rt['circulateCode'],
                }  
                # 汉得接口，如果传的是瓶标，返回的参数里没有devanCode       
                if 'devanCode' in rt:  
                    dv=rt['devanCode']                   
                else:
                    dv='未知'
                data['status']['devanCode']=dv
                if 'decapMsg' in rt:
                    if rt['decapMsg']:
                        a.append(rt['decapMsg'])
                if 'circulateMsg' in rt:
                    if rt['circulateMsg']:
                        a.append(rt['circulateMsg'])
                if 'devanMsg' in rt: 
                    if rt['devanMsg']:
                        a.append(rt['devanMsg'])
                if a:
                    data['msg']=",".join(a)
            else:               
                data['e']=rt            
        else:
            data['e']="汉得码状态接口出错, status:"+str(cd)+",text:"+rr.text
    else:
        data['e']='汉得码状态接口获取token出错，'+d['e']        

    return data


def get_carton_redeem_info(label_code, code_type:str='', is_test=False):
    """
    用箱标调用汉德接口返回箱下盖码的兑奖信息
    """
    data = {'e': '', 'data': [], 'msg': ''}
    d = get_token(is_test)
    tk = d.get('token')
    if tk:
        if is_test:
            url = "https://winesmptest.cofco.com/linktest/trml/link/asset/queryAssetStatusByTJ"
        else:
            url = "https://winesmp.cofco.com/prod/trml/link/asset/queryAssetStatusByTJ"
        headers = {
            "Authorization": "bearer " + tk,
            "Content-type": 'application/json;charset=UTF-8'
        }
        d = {
            "prodCodeNo": label_code,
            "prodCodeType": "" if not code_type else code_type
        }
        resp = requests.post(url, headers=headers, json=d)
        cd = resp.status_code
        if cd == 200:
            a = []
            dd = json.loads(resp.text)
            rt = dd['result']
            if dd['success']:
                if rt.get('assetCodeList'):
                    data['data'] = [{**d, "bottlecap": decrypt_11h(d.get("scanCode"))} for d in rt['assetCodeList']]
            else:
                data['e'] = rt
        else:
            data['e'] = "汉得码状态接口出错, status:" + str(cd) + ",text:" + resp.text
    else:
        data['e'] = '汉得码状态接口获取token出错，' + d['e']
    
    return data


# 2024-04-22
def label_agent(label_code,is_test=False):
    """
    韩忠玉@2024-04-22 查询标签（单个标签号码）在汉得系统内分销商信息
    """
    data={'e':'','status':{},'dev':[]}
    d=get_token(is_test)
    tk=d['token']
    if tk:
        if is_test:    
            url="https://winesmptest.cofco.com/linktest/trml/link/prodCode/queryDistributionByTJ"
        else:    
            url="https://winesmp.cofco.com/prod/trml/link/prodCode/queryDistributionByTJ"
        headers = {
            "Authorization": "bearer " + tk,
            "Content-type": 'application/json;charset=UTF-8'
        }  
        rr=requests.post(url, headers=headers, json=[label_code])        
        cd=rr.status_code
        if cd==200:            
            dd=json.loads(rr.text) 
            if dd['success']:
                for d in dd['data']:
                    # 分销商
                    if 'desAcctName' in d:
                        pkg_id=0
                        pkg_name=''
                        if d['returnCodeType'] in ('C001','C005'):
                            pkg_id=3
                            pkg_name='箱标'
                        elif d['returnCodeType'] in ('C002','C003'):
                            pkg_id=1
                            pkg_name='瓶标'
                        elif d['returnCodeType'] in ('C004',):
                            pkg_id=100
                            pkg_name='瓶盖'
                        data['dev'].append({     
                            'vtype':'分销出库',
                            'company':d['dealerName'],  
                            'label':d['returnCode'], 
                            'package':{'id':pkg_id,'name':pkg_name},                              
                            'customer':d['desAcctName'],
                            'tm':d['distributorTime'][:19],                                
                        })
                    # 终端
                    if 'terminalName' in d:
                        c=d['dealerName']
                        if 'desAcctName' in d:
                            c=d['desAcctName']
                        pkg_id=0
                        pkg_name=''
                        if d['returnCodeType'] in ('C001','C005'):
                            pkg_id=3
                            pkg_name='箱标'
                        elif d['returnCodeType'] in ('C002','C003'):
                            pkg_id=1
                            pkg_name='瓶标'
                        elif d['returnCodeType'] in ('C004',):
                            pkg_id=100
                            pkg_name='瓶盖'
                        data['dev'].append({   
                            'vtype':'终端出库',
                            'company':c,  
                            'label':d['returnCode'],    
                            'package':{'id':pkg_id,'name':pkg_name},                               
                            'customer':d['terminalName'],
                            'tm':d['terminalTime'][:19]                                                                                      
                        })
    return data


