from django.shortcuts import render
import hashlib
from company.models import User,Company
from product.models import Product
import json
from django.views.decorators.csrf import csrf_exempt
import datetime
from utils.views import *
from django.http import JsonResponse
from django.apps import apps
import urllib.request
import requests
from datacenter.settings import CRM_STR


# Create your views here.

sK = 'fgfdvgu$#&3t@j'

local_url = '47.107.230.103:8668'
local_url = '127.0.0.1:8000'

def import_crm(request, external_id):
    data = {"e":''}
    cn = psycopg2.connect(CRM_STR)
    cur = cn.cursor()
    cs = Company.objects.filter(external_code='crm',external_id=int(external_id))
    if not cs:
        data['e']='external_id='+external_id+"的公司不存在"
        return JsonResponse(data)
    c = cs[0]
    t = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    s = sK + t
    m2 = hashlib.md5()
    m2.update(s.encode(encoding='UTF-8'))
    key = m2.hexdigest()
    # 经销商
    s = "SELECT parentid FROM tj_crm_customerinfo where compid="+external_id+" group by parentid order by parentid"
    cur.execute(s)
    rs = cur.fetchall()
    for r in rs:
        cur.execute("select id,customername,username,passwordstring,addressinfo from tj_crm_customerinfo "+\
                "where parentid="+str(r[0])+" and compid="+external_id)
        for r0 in cur.fetchall():
            usr = r0[2]
            pwd = r0[3]
            data = {'company_id': external_id, 'address': r0[4], 'id': r0[0], 'name': r0[1], 'parent_id':r[0],
                    'time': t, 'key': key}
            data = json.dumps(data)
            url = 'http://' + local_url + '/crm/add/agent/'
            data = bytes(data, "utf8")
            headers = {'Content-Type': 'application/json'}
            rq = urllib.request.Request(url, data, headers)
            rt = urllib.request.urlopen(rq).read().decode('utf-8')
            rt = json.loads(rt)

            #print(rt)
            if rt['id']:
                u = User(username=usr,company_id=int(rt['id']),external_code='crm')
                u.set_password(pwd)
                u.save()

    # 产品
    cur.execute("SELECT id, brandname  FROM tj_crm_brandinfo where compid="+str(c.external_id))
    for r in cur.fetchall():
        data = {'company_id': external_id, 'id': r[0], 'name': r[1],'time': t, 'key': key}
        data = json.dumps(data)
        url = 'http://' + local_url + '/crm/add/product/'
        data = bytes(data, "utf8")
        headers = {'Content-Type': 'application/json'}
        rq = urllib.request.Request(url, data, headers)
        rt = urllib.request.urlopen(rq).read().decode('utf-8')
        rt = json.loads(rt)
        print(rt)
    return JsonResponse(data)


@csrf_exempt
def crm_operation(request,operation,obj):
    data = {'e': '', 'id': 0}
    k = sK
    r = json.loads(request.body)
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    if 'company_id' not in r:
        data['e']='参数缺失：company_id'
        return JsonResponse(data)
    compid=r['company_id']
    d ={
        'agent':['company','Company'],
        'product':['product','Product'],
        'store':['inventory','Storehouse'],
        'user':['company','User']
    }
    if obj not in d:
        data['e']='无效对象名'
        return JsonResponse(data)
    if operation not in ['add','edit']:
        data['e'] = '无效操作名'
        return JsonResponse(data)
    cs = Company.objects.filter(external_code='crm',external_id=int(compid))
    if not cs:
        data['e'] = "company_id："+str(compid)+"不存在"
        return JsonResponse(data)
    if 'id' not in r:
        data['e'] = "参数缺失：id"
        return JsonResponse(data)
    c = cs[0]
    m = apps.get_model(d[obj][0], d[obj][1])
    if operation=='edit':
        objs = m.objects.filter(external_code='crm',external_id=int(r['id']))
        if not objs:
            data['e']=obj+":id="+str(r['id'])+'不存在'
            return JsonResponse(data)
        o=objs[0]
        if 'address' in r:
            o.address = r['address']
        if obj!='user' and 'name' in r:
            o.name=r['name']
    else:
        if 'name' not in r:
            data['e'] = '参数缺失：name'
            return JsonResponse(data)
        if obj=='user':
            o = m(username=r['name'], external_code='crm', external_id=r['id'])
        else:
            o = m(name=r['name'], external_code='crm', external_id=r['id'])
        if obj=='agent':
            # print(o.external_code)
            if 'parent_id' in r:
                if int(r['parent_id'])==0:
                    o.parent = c
                else:
                    cs = Company.objects.filter(external_code='crm',external_id=int(r['parent_id']))
                    if cs:
                        o.parent = cs[0]
                    else:
                        data['e']='参数错误：parent_id='+str(r['parent_id'])+"的公司不存在"
                        return JsonResponse(data)

                    # 同一公司下不能有同名经销商
                    cs = Company.objects.filter(name=r['name'], parent_id=int(r['parent_id']))
                    if cs:
                        data['e'] = "数据错误：同一公司下不能添加相同名称的经销商"
                        return JsonResponse(data)
            else:
                o.parent = c
            o.category_id=8
        else:
            o.company = c
        if 'address' in r:
            o.address=r['address']

    if obj == 'user' and 'password' in  r:
        o.set_password(r['password'])

    try:
        o.save()
        data['id']=o.id
    except Exception as e:
        data['e']=str(e)
    return JsonResponse(data)

