from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from mall.models import *
from mall.form import *
#from sales.views import send_message
from sales.models import ConsumerAccount,Member
from company.models import Company,User
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
from decimal import Decimal
import json
import time
import random
import datetime
import hashlib
from django.conf import settings as sys_settings
from django.core.serializers import serialize
from django.shortcuts import redirect
from utils.views import send_sms
from wx.wxauth import wx_tjfw_base_oauth
from utils.views import encrypt_p,decrypt_p


# Create your views here.

#domain = 'http://192.168.0.114:8000'
domain = 'https://davis.china315net.com'

media_path = sys_settings.MEDIA_ROOT
interface_key = sys_settings.INTERFACE_KEY


# 更新用户积分接口


def update_user_points(request):
    data = {
        'e': '',
        'points': ''
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        points = request.POST.get('points', '')
        type = request.POST.get('type', '')
        if compid and uid and points and type:
            p = UserPoints.objects.filter(member_id=int(uid))
            if p:
                p = p[0]
                if type == '1':
                    p.update_user_points(int(points))
                else:
                    if p.num >= int(points):
                        p.update_user_points(-int(points))
                    else:
                        data['e'] = '积分不够扣除'
            else:
                p = UserPoints(company=int(compid),
                               member_id=int(uid), num=points)
                p.save()
            data['points'] = p.num
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 更新消费者积分 
def update_member_points_consumer(consumer_id,company_id,points,reason):
    data = {
        'e': '',
        'points': 0
    }
    consumer = ConsumerAccount.objects.filter(id=consumer_id)
    if consumer:
        consumer = consumer[0]
        member = Member.objects.filter(consumer_id=consumer_id,company_id=company_id)
        if member:
            member = member[0]
            if member.exps:
                member.exps = member.exps + points
            else:
                member.exps = points
            member.save()
        else:
            name = consumer.wx_nickname
            gender = consumer.gender
            province = ''
            city = ''
            birthday = None
            if consumer.wx_province:
                province = consumer.wx_province
            if consumer.wx_city:
                city = consumer.wx_city
            if consumer.birthday:
                birthday = consumer.birthday

            member = Member(
                consumer=consumer,
                company_id=int(company_id),
                name=name,
                gender=gender,
                remark='领取积分注册',
                province=province,
                city=city,
                birthday=birthday,
                grade_id=1,
                headImg=consumer.wx_headimgurl,
                exps=points
            )
            member.save()

        p = UserPoints.objects.filter(member_id=member.id)
        if p:
            p=p[0]
            p.update_user_points(points,reason)
        else:
            p = UserPoints(company_id=company_id,
                           member_id=member.id, num=0)
            p.save()
            p.update_user_points(points,reason)
    else:
        data['e'] = '用户不存在'
    return  data


# 更新经销商积分 
def update_member_points_agent(agent_id,points,reason):
    member = Member.objects.filter(agent_id=agent_id)
    if member:
        member = member[0]
        if member.exps:
            member.exps = member.exps + points
        else:
            member.exps = points
        member.save()
        company_id=member.company_id
    else:
        c = Company.objects.get(id=agent_id)
        name = c.name
        province = ''
        city = ''
        birthday = None
        company_id=c.ancestor_id
        member = Member(
                company_id=c.ancestor_id,
                agent_id=agent_id,
                name=name,
                remark='领取积分注册',
                province=province,
                city=city,
                birthday=birthday,
                grade_id=2,
                exps=points
        )
        member.save()

    p = UserPoints.objects.filter(member_id=member.id)
    if p:
        p=p[0]
        p.update_user_points(points,reason)
    else:
        p = UserPoints(company_id=company_id,
                           member_id=member.id, num=0)
        p.save()
        p.update_user_points(points,reason)
     

# 更新会员积分 
def update_member_points(member_id, points, reason):
    member = Member.objects.get(id=member_id)
    if member.exps:
        member.exps = member.exps + points
    else:
        member.exps = points
    member.save()
    p = UserPoints.objects.filter(member_id=member.id)
    if p:
        p=p[0]
        p.update_user_points(points,reason)
    else:
        p = UserPoints(company_id=member.company_id, member_id=member.id, num=0)
        p.save()
        p.update_user_points(points,reason)
     
# 积分商城设置页面
@login_required
def settings(request):
    company_id = request.user.company.id
    obj = Settings.objects.filter(company_id=int(company_id))
    if obj:
        obj = obj[0]
    else:
        obj = Settings(company_id=int(company_id))
        obj.save()
    if request.method == 'GET':
        form = SettingsForm(instance=obj)
    else:
        form = SettingsForm(request.POST, instance=obj)
    if form.is_valid():
        form.save()
    return render(request, 'mall/settings.html', {'setting': obj, 'form': form})


# 轮播图列表
@login_required
def banners(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['图片', '是否激活','添加时间','操作']
    data['show_add'] = True
    data['murl'] = '/mall/banners/edit/'

    for banner in Banners.objects.filter(company_id=request.user.company.id):
        flag = '否'
        if banner.is_active:
            flag = '是'
        data['data'].append([
            "<img src='" + banner.image.url +"' style='width:100px' />",
            flag,
            banner.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/mall/banners/edit/" +str(banner.id) + "/'>编辑</a>"
        ])

    return render(request, 'obj/list_obj.html', data)


# 轮播图添加或更新
@login_required
def banners_edit(request, id=None):
    if id:
        obj = Banners.objects.get(id=int(id))
    else:
        obj = Banners(company_id=request.user.company.id)
    if request.method == 'GET':
        form = BannersForm(instance=obj)
    else:
        form = BannersForm(request.POST, request.FILES, instance=obj)
    if form.is_valid():
        form.save()
    return render(request, 'mall/banners.html', {'form': form})


# 轮播图接口
@csrf_exempt
def banners_data(request):
    data = {
        'e': '',
        'banners': []
    }
    if request.method == 'POST':
        compid = request.POST.get('compid', '')
    else:
        compid = request.GET.get('compid', '')
    if compid:
        bans = Banners.objects.filter(company_id=int(compid), is_active=1)

        for b in bans:
            data['banners'].append(domain + b.image.url)
    return JsonResponse(data)


# 商品列表
@login_required
def points_product(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['商品名称', '商品图片', '总价值', '是否激活','操作']
    data['show_add'] = True
    data['murl'] = '/mall/points_product/edit/'

    for product in Points_Products.objects.filter(company_id=request.user.company.id):
        flag = '否'
        if product.is_active:
            flag = '是'
        img = ''
        if product.product_image and product.product_image.url:
            img = product.product_image.url
        data['data'].append([
            "<div class='word-wrap'>"+product.product_name+"</div>",
            "<img src='" + img + "' style='width:60px' />",
            float(product.product_cost),
            flag,
            "<a href='/mall/points_product/edit/" +str(product.id) + "/' class='btn btn-default btn-xs'>内容编辑</a>"+
            "<a href='/mall/points_product/banner/" +str(product.id) + "/' class='btn btn-default btn-xs'>轮播图</a>"
        ])
    return render(request, 'obj/list_obj.html', data)


@login_required
def points_product_banner(request, id=None):
    data = {'data': [],
            'clmns': ['图片', '是否激活','排序','上传时间','操作'],
            'e': [], 'subtt': ['积分商城', '商品管理','商品轮播管理'],
            'list': []
            }
    if id:
        if request.method == 'POST':
            banner_id = request.POST.get('banner_id', '')
            obj = None
            if banner_id:
                obj = Points_Products_Banner.objects.get(id=int(banner_id))
            else:
                obj = Points_Products_Banner(company_id=request.user.company.id, product_id=int(id))
            if obj:
                form = Points_Products_Banner_Form(request.POST, request.FILES, instance=obj)
                if form.is_valid():
                    form.save()


        banners = Points_Products_Banner.objects.filter(product_id=int(id)).order_by('sort_id')
        for b in banners:
            flag = '否'
            img_url = ''
            if b.is_active:
                flag = '是'
            if b.image:
                img_url = b.image.url
            data['data'].append([
                "<img src='" + img_url +"' style='width:100px' />",
                flag,
                b.sort_id,
                b.tm.strftime("%Y-%m-%d %H:%M:%S"),
                "<a class='btn btn-danger btn-xs' onclick='deleteData(" + str(b.id) + ")'>删除</a>"
            ])
        return render(request, 'mall/points_product_banner.html', data)
    else:
        return JsonResponse(data)


@login_required
def points_product_banner_delete(request, id=None, bid=None):
    if id and bid:
        obj = Points_Products_Banner.objects.get(id=int(bid), company_id=request.user.company.id)
        obj.delete()
        return redirect('/mall/points_product/banner/'+str(id))
    else:
        return redirect('/mall/points_product/banner/')



# 设置允许上传的文件格式
ALLOW_EXTENSIONS = ['png', 'jpg', 'jpeg']
# 判断文件后缀是否在列表中
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[-1] in ALLOW_EXTENSIONS

@csrf_exempt
def points_product_upload(request):
    data = {
        'errno': '0',
        'data': []
    }
    if request.method == 'POST' and request.user:
        # 获取post过来的文件名称，从name=file参数中获取
        ret_files = request.FILES
        comp_name = request.user.company.name
        #保存文件夹
        dirs = os.path.join(media_path,comp_name, 'product')
        if not os.path.exists(dirs):
            os.makedirs(dirs)
        for file in ret_files:
            img = request.FILES.get(file)
            file_name = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace('.', '')[-7:] + "." + img.name.split('.')[-1]
            # 保存图片
            f_url = os.path.join(media_path,comp_name, 'product', file_name)
            img_url =  "https://davis.china315net.com\\media\\"+os.path.join(comp_name, 'product', file_name)

            with open(f_url, 'wb+') as destination:
                for chunk in img.chunks():
                    destination.write(chunk)
            data['data'].insert(0,img_url)
        data['errno'] = '0'
    else:
        data['errno'] = '500'
    return JsonResponse(data)



# 商品添加或更新
@login_required
def points_product_edit(request, id=None):
    if id:
        obj = Points_Products.objects.get(id=int(id))
    else:
        obj = Points_Products(company_id=request.user.company.id)
    if request.method == 'GET':
        form = Points_Products_Form(instance=obj)
    else:
        form = Points_Products_Form(request.POST, request.FILES, instance=obj)
    if form.is_valid():
        form.save()
    return render(request, 'mall/points_product.html', {'form': form})


# 商品接口
@csrf_exempt
def points_product_data(request):
    data = {
        'e': '',
        'products': [],
        'category': []
    }
    if request.method == 'POST':
        compid = request.POST.get('compid', '')
    else:
        compid = request.GET.get('compid', '')
    if compid:
        product = Points_Products.objects.filter(
            company_id=int(compid), is_active=1)
        #settings = Settings.objects.get(company_id=int(compid))
        #exchange_rate = settings.exchange_rate

        for p in product:
            if p.product_image:
                ps = {
                    'id': p.id,
                    'name': p.product_name,
                    'img': domain + p.product_image.url,
                    'cost': p.product_cost,
                    'desc': p.product_desc,
                    'cat_id': p.cat.id
                }

                data['products'].append(ps)
        cur = connection.cursor()
        cur.execute(
            "SELECT (SELECT cat_name from mall_points_product_category b WHERE b.id = cat_id),cat_id FROM mall_points_products where company_id = " + compid + " GROUP BY cat_id")
        for r in cur.fetchall():
            ps = {
                'id': r[1],
                'name': r[0]
            }
            data['category'].append(ps)
        cur.close()
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 商品详细接口
@csrf_exempt
def points_product_detail(request):
    data = {
        'e': '',
        'content': '',
        'banners':[]
    }
    if request.method == 'POST':
        compid = request.POST.get('compid', '')
        pid = request.POST.get('pid', '')
    else:
        compid = request.GET.get('compid', '')
        pid = request.GET.get('pid', '')
    if compid and pid :
        product = Points_Products.objects.get(company_id=int(compid), id=int(pid))
        if product:
            skuid = product.skuid
            if compid == '95971' and skuid !='':
                d = requests.get('http://os.china315net.com/admin/suning/ajax/getProddetail.ashx?skuid='+skuid)
                d = d.content.decode("utf-8")
                if d: 
                    d = json.loads(d)
                    if d['msg'] == 'success':
                        introduction = d['detail']['sn_responseContent']['sn_body']['getProdDetail']['introduction']
                        data['content'] = introduction

                d = requests.get('http://os.china315net.com/admin/suning/ajax/getProdimage.ashx?skuid='+skuid)
                d = d.content.decode("utf-8")
                if d:
                    d = json.loads(d)
                    if d['msg'] == 'success':
                        image = d['image']
                        if image and len(image)>0:
                            urls = image['urls']
                            for i in range(len(urls)):
                                data['banners'].append(urls[i]['path'])
            else:
                data['content'] = product.product_content
                banners = Points_Products_Banner.objects.filter(company_id=int(compid), product_id=int(pid),is_active=True).order_by('sort_id')
                for banner in banners:
                    data['banners'].append(domain + banner.image.url)
        else:
            data['e'] = '产品不存在'
    else:
        data['e'] = '数据丢失'

    return JsonResponse(data)

# 商品评论接口
@csrf_exempt
def points_product_comment(request):
    data = {
        'e': '',
        'comments': []
    }
    if request.method == 'POST':
        compid = request.POST.get('compid', '')
        pid = request.POST.get('pid', '')
    else:
        compid = request.GET.get('compid', '')
        pid = request.GET.get('pid', '')
    if compid and pid:
        comments = Order_Comment.objects.filter(
            company_id=int(compid), is_show=1, product_id=int(pid))
        if comments:
            for c in comments:
                cs = {
                    'pid':pid,
                    'score': c.score,
                    'content': c.content,
                    'tm': c.tm.strftime("%Y-%m-%d %H:%M:%S"),
                    'nickName': c.user.name,
                    'headImg': c.user.headImg
                }
                data['comments'].append(cs)
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 地址操作
@csrf_exempt
def address_operate(request):
    data = {
        'e': '',
        'id': '',
        'list': []
    }
    if request.method == 'POST':
        etype = request.POST.get('etype', 'get')
        id = request.POST.get('id', '')
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        if uid and compid:
            if etype == 'add' or etype == 'update':
                name = request.POST.get('name', '')
                phone = request.POST.get('phone', '')
                address = request.POST.get('address', '')
                province = request.POST.get('province', '')
                city = request.POST.get('city', '')
                county = request.POST.get('county', '')
                street = request.POST.get('street', '')
                area_code = request.POST.get('area_code', '')
                address_detail = request.POST.get('address_detail', '')
                is_default = False
                if request.POST.get('is_default', '').lower() == 'true':
                    is_default = True
                if name and phone and address and province and city and county and address_detail:
                    if id:
                        p = User_Address.objects.get(id=int(id))
                    else:
                        p = User_Address()
                    p.company_id = int(compid)
                    p.user_id = int(uid)
                    p.name = name
                    p.phone = phone
                    p.address = address
                    p.province = province
                    p.city = city
                    p.county = county
                    p.street = street
                    p.area_code = area_code
                    p.address_detail = address_detail
                    p.is_default = is_default
                    #print(is_default)
                    cur = connection.cursor()
                    cur.execute(
                        "update mall_user_address set is_default = false where user_id = " + uid)
                    p.save()
                    data['id'] = p.id
                else:
                    data['e'] = '数据丢失'
            elif etype == 'setDefault':
                if id:
                    cur = connection.cursor()
                    cur.execute("update mall_user_address set is_default = false where user_id = " +
                                uid + ";update mall_user_address set is_default = true where id = " + id)
                    data['id'] = id
                else:
                    data['e'] = '数据丢失'
            elif etype == 'delete':
                if id:
                    cur = connection.cursor()
                    cur.execute(
                        "delete from mall_user_address where id = " + id + " and user_id = " + uid)
                else:
                    data['e'] = '数据丢失'
            address = User_Address.objects.filter(
                company_id=int(compid), user_id=int(uid))
            for adr in address:
                data['list'].append({
                    'id': adr.id,
                    'name': adr.name,
                    'tel': adr.phone,
                    'address': adr.address,
                    'province': adr.province,
                    'city': adr.city,
                    'county': adr.county,
                    'street': adr.street,
                    'addressDetail': adr.address_detail,
                    'areaCode': adr.area_code,
                    'isDefault': adr.is_default,
                    'tm': str(adr.tm)
                })
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 商品结账与下单


@csrf_exempt
def check_out(request):
    data = {
        'e': '',
        'order_number': ''
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        address_id = request.POST.get('address_id', '')
        product_id = request.POST.get('product_id', '')
        product_num = request.POST.get('product_num', '')
        all_cost = Decimal(request.POST.get('all_cost', '0')
                           ).quantize(Decimal('0.00'))
        remark = request.POST.get('remark', '')
        if uid and compid and address_id and product_id and product_num and all_cost:
            product = Points_Products.objects.get(
                id=int(product_id), company_id=int(compid))
            if product:
                # settings = Settings.objects.get(company_id=int(compid))
                # exchange_rate = settings.exchange_rate
                # 获取数据库内的最新价格
                real_all_cost = product.product_cost * int(product_num)
                if real_all_cost == all_cost:
                    # 用户积分
                    u_points = UserPoints.objects.filter(
                        member_id=int(uid), company_id=int(compid))
                    if u_points:
                        u_points = u_points[0]
                        u_points_num = u_points.num
                        # 判断是否有足够积分兑换
                        if u_points_num >= real_all_cost:
                            u_address = User_Address.objects.get(
                                id=int(address_id), company_id=int(compid))
                            if u_address:
                                name = u_address.name
                                phone = u_address.phone
                                address = u_address.address
                                province = u_address.province
                                city = u_address.city
                                county = u_address.county
                                street = u_address.street
                                status_id = 1
                                order_type = 1
                                order_number = str(time.strftime('%Y%m%d%H%M%S', time.localtime(
                                    time.time()))) + str(time.time()).replace('.', '')[-7:]
                                # 保存订单
                                order = Orders(
                                    company_id=int(compid),
                                    user_id=int(uid),
                                    order_number=order_number,
                                    order_type=order_type,
                                    status_id=status_id,
                                    total_cost=real_all_cost,
                                    remarks=remark,
                                    user_name=name,
                                    user_phone=phone,
                                    user_address=address,
                                    province=province,
                                    city=city,
                                    county=county,
                                    street=street
                                )
                                order.save()
                                order_id = order.id
                                # 订单详情
                                order_detail = Order_Detail(
                                    company_id=int(compid),
                                    order_id=order_id,
                                    order_number=order_number,
                                    product_id=product_id,
                                    num=product_num,
                                    product_name=product.product_name,
                                    product_image=product.product_image,
                                    product_cost=product.product_cost,
                                    product_desc=product.product_desc
                                )
                                order_detail.save()
                                # 用户剩余积分
                                reason = '兑换'+product.product_name+'*'+product_num+' 消耗'
                                u_points.update_user_points(-real_all_cost,reason)
                                u_points.save()

                                data['order_number'] = order_number
                                data['points'] = u_points.num
                            else:
                                data['e'] = '地址不存在'
                        else:
                            data['e'] = '您的积分不足'
                    else:
                        data['e'] = '用户积分不存在'
                else:
                    data['e'] = '金额发生变动，请重新进入'
            else:
                data['e'] = '商品不存在'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 订单列表
@login_required
def orders(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['商品', '状态', '总金额', '下单人', '数量', '时间','操作']

    compid = request.user.company.id
    sql_filter = "a.company_id = " + str(compid)
    if compid:
        cur = connection.cursor()
        cur.execute(
            "SELECT a.id,a.order_number,a.status_id,a.total_cost,b.product_id,b.product_cost,b.product_name,b.product_image,b.num, " +
            "(select status_name from mall_order_status where id = a.status_id) as status_name,a.tm,a.user_name " +
            "FROM mall_orders a, mall_order_detail b " +
            "where " + sql_filter + " and a.id = b.order_id order by a.id DESC")

        for r in cur.fetchall():
            data['data'].append([
                "<img src='/media/" + r[7] + "' style='width:30px' />" + r[6] ,
                r[9],
                str(r[3]),
                r[11],
                r[8],
                r[10].strftime("%Y-%m-%d %H:%M:%S"),
                "<a class='btn btn-default btn-xs' href='/mall/orders/edit/" + str(r[0]) + "/'>详情</a>"
            ])
    return render(request, 'obj/list_obj.html', data)


# 订单编辑
@login_required
def order_edit(request, id=None):
    data = {
        'e': ''
    }
    compid = request.user.company.id
    if id and compid:
        obj = Orders.objects.get(id=int(id),company_id=int(compid))
        if obj:
            products = Order_Detail.objects.filter(order_id=int(id))
            if products:
                products = products[0]
            if request.method == 'GET':
                form = Orders_Form(instance=obj)
            else:
                form = Orders_Form(request.POST, instance=obj)
            if form.is_valid():
                form.save()
            return render(request, 'mall/order.html', {'order':obj,'product':products,'domain':domain,'form': form})
        else:
            data['e'] = '数据不存在'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


@csrf_exempt
def orders_list(request):
    data = {
        'e': '',
        'list': []
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        if uid and compid:
            sql_filter = "a.id = b.order_id and a.company_id = " + compid + " and a.user_id = " + uid
            status_id = request.POST.get('status_id', '')
            if status_id:
                if status_id != '0':
                    sql_filter += ' and a.status_id = ' + status_id
            cur = connection.cursor()
            cur.execute(
                "SELECT a.id,a.order_number,a.status_id,a.total_cost,b.product_id,b.product_cost,b.product_name,b.product_image,b.num,b.product_desc, " +
                "(select status_name from mall_order_status where id = a.status_id) as status_name " +
                "FROM mall_orders a, mall_order_detail b " +
                "where " + sql_filter + " order by a.id DESC")
            for r in cur.fetchall():
                ps = {
                    'id': r[0],
                    'order_number': r[1],
                    'status_id': r[2],
                    'total_cost': r[3],
                    'product_id': r[4],
                    'product_cost': r[5],
                    'product_name': r[6],
                    'product_image': domain + '/media/' + r[7],
                    'product_num': r[8],
                    'product_desc': r[9],
                    'status_name': r[10],
                }
                data['list'].append(ps)
            cur.close()
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 订单详情
@csrf_exempt
def orders_detail(request):
    data = {
        'e': '',
        'total_cost': 0,
        'remarks': '',
        'user_name': '',
        'user_phone': '',
        'user_address': '',
        'tm': '',
        'delivery': {
            'compname': '',
            'code': '',
            'tm': ''
        },
        'shouhuo_tm': ''
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        oid = request.POST.get('oid', '')
        if uid and compid and oid:
            sql_filter = "company_id = " + compid + " and user_id = " + uid + " and id = " + oid
            cur = connection.cursor()
            cur.execute(
                "SELECT total_cost,remarks,user_name,user_phone,user_address,tm,deliver_company_name,deliver_company_code,deliver_tm,shouhuo_tm " +
                "FROM mall_orders " +
                "where " + sql_filter + "")
            d = cur.fetchone()
            if d:
                data['total_cost'] = d[0]
                data['remarks'] = d[1]
                data['user_name'] = d[2]
                data['user_phone'] = d[3]
                data['user_address'] = d[4]
                data['tm'] = d[5].strftime("%Y-%m-%d %H:%M:%S")
                data['delivery']['compname'] = d[6]
                data['delivery']['code'] = d[7]
                if d[8]:
                    data['delivery']['tm'] = d[8].strftime("%Y-%m-%d %H:%M:%S")
                if d[9]:
                    data['shouhuo_tm'] = d[9].strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['e'] = '订单不存在'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 订单收货确认
@csrf_exempt
def order_shouhuo(request):
    data = {
        'e': '',
        'id': ''
    }
    if request.method == 'POST':
        id = request.POST.get('id', '')
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        if uid and compid and id:
            cur = connection.cursor()
            cur.execute("update mall_orders set shouhuo_tm = now(),status_id = 3 where user_id = " +
                        uid + " and company_id = " + compid + " and id = " + id)
            data['id'] = id
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 订单评论
@csrf_exempt
def order_comment(request):
    data = {
        'e': '',
        'id': ''
    }
    if request.method == 'POST':
        id = request.POST.get('id', '')
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        score = request.POST.get('score', '')
        product_id = request.POST.get('product_id', '')
        content = request.POST.get('content', '')
        if uid and compid and id and score and product_id:
            obj = Order_Detail.objects.filter(order_id=int(id))
            if obj:
                obj = obj[0]

                comment = Order_Comment(
                    company_id=int(compid),
                    order_id=int(id),
                    user_id=int(uid),
                    product_id=int(product_id),
                    product_name=obj.product_name,
                    product_image=obj.product_image,
                    product_cost=obj.product_cost,
                    score=int(score),
                    content=content
                )
                comment.save()
                cur = connection.cursor()
                cur.execute("update mall_orders set status_id = 4 where user_id = " +
                        uid + " and company_id = " + compid + " and id = " + id)
                data['id'] = id
            else:
                data['e'] = '数据不存在'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 订单评论列表
@login_required
def orders_comments_list(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['商品','评论内容', '评分', '评论人', '是否显示', '时间','操作']
    compid = request.user.company.id
    if compid:
        obj = Order_Comment.objects.filter(company_id=int(compid))
        for o in obj:
            is_show = '否'
            if o.is_show:
                is_show = '是'
            data['data'].append([
                "<img src='/media/"+ o.product_image + "' style='width:30px' /> "+o.product_name,
                o.content,
                o.score,
                o.user.name,
                is_show,
                o.tm.strftime("%Y-%m-%d %H:%M:%S"),
                "<a class='btn btn-default btn-xs' href='/mall/orders/comments/edit/" + str(o.id) + "/'>详情</a>"
            ])
    return render(request, 'obj/list_obj.html', data)


# 评论编辑
@login_required
def order_comments_edit(request, id=None):
    data = {
        'e': ''
    }
    compid = request.user.company.id
    if id and compid:
        obj = Order_Comment.objects.get(id=int(id),company_id=int(compid))
        if obj:
            order = Orders.objects.get(id=int(obj.order_id),company_id=int(compid))
            products = Order_Detail.objects.filter(order_id=int(obj.order_id))
            if products:
                products = products[0]
            if request.method == 'GET':
                form = Orders_Comments_Form(instance=obj)
            else:
                form = Orders_Comments_Form(request.POST, instance=obj)
            if form.is_valid():
                form.save()
            return render(request, 'mall/comment.html', {'comment':obj,'order':order,'product':products,'domain':domain,'form': form})
        else:
            data['e'] = '数据不存在'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 订单数量
@csrf_exempt
def order_status_num(request):
    data = {
        'e': '',
        'order_status_num': {
            'dfh': '',
            'dsh': '',
            'dpj': ''
        }
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        compid = request.POST.get('compid', '')
        if uid and compid:
            cur = connection.cursor()
            cur.execute(
                "select count(*),status_id from mall_orders WHERE (status_id = 1 or status_id = 2 or status_id = 3 ) " +
                "and user_id =" + uid + " and company_id = " + compid + "GROUP BY status_id")

            for r in cur.fetchall():
                if r[1] == 1:
                    data['order_status_num']['dfh'] = r[0]
                elif r[1] == 2:
                    data['order_status_num']['dsh'] = r[0]
                elif r[1] == 3:
                    data['order_status_num']['dpj'] = r[0]
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


# 资讯发布
@login_required
def boards(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['咨询标题', '结束时间', '是否激活','操作']
    data['show_add'] = True
    data['murl'] = '/mall/boards/edit/'

    for board in Boards.objects.filter(company_id=request.user.company.id):
        flag = '否'
        if board.is_active:
            flag = '是'
        data['data'].append([
            board.subtitle,
            str(board.endtm),
            flag,
            "<a class='btn btn-default btn-xs' href='/mall/boards/edit/" +str(board.id) + "/'>编辑</a>"
        ])
    return render(request, 'obj/list_obj.html', data)


# 咨询编辑
@login_required
def boards_edit(request, id=None):
    if id:
        obj = Boards.objects.get(id=int(id))
    else:
        obj = Boards(company_id=request.user.company.id)
    if request.method == 'GET':
        form = Boards_Form(instance=obj)
    else:
        form = Boards_Form(request.POST, instance=obj)
    if form.is_valid():
        form.save()
    return render(request, 'mall/boards.html', {'form': form})


# 商品接口
@csrf_exempt
def boards_data(request):
    data = {
        'e': '',
        'boards': []
    }
    if request.method == 'POST':
        compid = request.POST.get('compid', '')
    else:
        compid = request.GET.get('compid', '')
    if compid:
        boards = Boards.objects.filter(
            company_id=int(compid), is_active=1, endtm__gte=datetime.date.today())[:5]
        for p in boards:
            ps = {
                'id': p.id,
                'subtitle': p.subtitle
            }
            data['boards'].append(ps)
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 用户信息
@csrf_exempt
def user_data(request):
    data = {
        'e': '',
        'points': 0,
        'wxNickName': '',
        'wxHeadImg': '',
        'member_id':'',
        'level':{
            'num':0,
            'name':'普通会员',
            'img':'http://tjfnew.china315net.com/xf375/images/level/1.png',
            'nextName':'已满级',
            'nextImg':'',
            'nextNum':0,
        },
        'id': ''
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        grade_id = request.POST.get('grade_id', '')
        compid = request.POST.get('compid', '')
        agent_id = request.POST.get('agent_id', '')
        member = None
        if uid and compid and grade_id:
            member = Member.objects.filter(id=int(uid),grade_id=int(grade_id))
        elif agent_id and compid and grade_id:
            member = Member.objects.filter(agent_id=int(agent_id),grade_id=int(grade_id))
        if member:
            member = member[0]
            data['id'] = encrypt_p(str(member.id))
            u_points = UserPoints.objects.filter(
                member_id=member.id, company_id=int(compid))
            if u_points:
                u_points = u_points[0]
                data['points'] = u_points.num
            else:
                u_points = UserPoints(
                    company_id=int(compid),
                    member_id=member.id,
                    num=0,
                    is_freeze=False
                )
                u_points.save()
            data['wxNickName'] = member.name
            if member.headImg:
                data['wxHeadImg'] = member.headImg
            else:
                data['wxHeadImg'] = domain+'/static/images/public/avator.png'
            data['member_id'] = member.id
            
            # 会员等级
            exps = member.exps
            cur = connection.cursor()
            cur.execute("SELECT name,photo,integral FROM sales_memberlevel WHERE integral >= "+str(exps)+" and company_id = "+compid+" ORDER BY integral limit 2")
            r = cur.fetchall()
            if r :
                if r[0]:
                    data['level']['name'] = r[0][0]
                    data['level']['num'] = exps
                    data['level']['img'] = domain+"/media/"+r[0][1]
                if r[1]:
                    data['level']['nextName'] = r[1][0]
                    data['level']['nextNum'] = r[1][2]
                    data['level']['nextImg'] = domain+"/media/"+r[1][1]
        else:
            data['e'] = '用户不存在'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)

# 用户积分明细

@csrf_exempt
def user_points_record_data(request):
    data = {
        'e': '',
        'records':[]
    }
    if request.method == 'POST':
        uid = request.POST.get('uid', '')
        grade_id = request.POST.get('grade_id', '')
        compid = request.POST.get('compid', '')
        if uid and compid and grade_id:
            member = Member.objects.filter(id=int(uid),grade_id=int(grade_id),company_id=int(compid))
            if member:
                member = member[0]
                records = UserPoints_Record.objects.filter(member_id=int(uid))

                for record in records:
                    data['records'].append({
                        'reason':record.reason,
                        'points':record.points,
                        'tm':record.tm.strftime("%Y-%m-%d %H:%M:%S")
                    })

            else:
                data['e'] = '用户不存在'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)

# 用户是否注册为会员
@csrf_exempt
def user_is_register(request):
    data = {
        'e': '',
        'isRegister': False,
        'member_id':''
    }
    if request.method == 'POST':
        company_id = request.POST.get('company_id', '')
        consumer_id = request.POST.get('consumer_id', '')
        obj = Member.objects.filter(company_id=int(company_id),consumer_id=int(consumer_id))
        if obj:
            obj = obj[0]
            if obj.phone:
                data['isRegister']=True
                data['member_id'] = obj.id
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)

# 会员注册
@csrf_exempt
def user_register(request):
    data = {
        'e': '',
        'isRegister': False,
        'member_id': ''
    }
    if request.method == 'POST':
        company_id = request.POST.get('company_id', '')
        consumer_id = request.POST.get('consumer_id', '')
        phone = request.POST.get('phone', '')
        name = request.POST.get('name', '')
        gender = request.POST.get('gender', '0')
        if company_id and consumer_id and phone:
            obj = Member.objects.filter(company_id=int(company_id), consumer_id=int(consumer_id))
            if obj:
                obj = obj[0]
                obj.phone = phone
                obj.save()
                data['isRegister'] = True
                data['member_id'] = obj.id
            else:
                consumer = ConsumerAccount.objects.filter(id=int(consumer_id))
                if consumer:
                    consumer = consumer[0]
                    if name == '':
                        name = consumer.wx_nickname
                    if gender =='':
                        gender = consumer.gender
                    province = ''
                    city = ''
                    birthday = None
                    if consumer.wx_province:
                        province = consumer.wx_province
                    if consumer.wx_city:
                        city = consumer.wx_city
                    if consumer.birthday:
                        birthday = consumer.birthday

                    member = Member(
                        consumer=consumer,
                        company_id=int(company_id),
                        name=name,
                        gender=gender,
                        remark='积分商城注册',
                        province=province,
                        city=city,
                        phone=phone,
                        birthday=birthday,
                        grade_id=1,
                        headImg=consumer.wx_headimgurl
                    )
                    member.save()

                    data['isRegister'] = True
                    data['member_id'] = member.id
                else:
                    data['e'] = '用户不存在'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)

#发送短信
@csrf_exempt
def send_code(request):
    data = {
        'e': '',
        'code': ''
    }
    if request.method == 'POST':
        company_id = request.POST.get('company_id', '')
        phone = request.POST.get('phone', '')
        if company_id and phone:
            code = ''
            codes = []
            for i in range(6):
                codes.append(str(random.randint(0, 9)))
            code = ''.join(codes)
            #code = '123456'
            text = '您的验证码是：'+code+'。请不要把验证码泄露给其他人。'
            if company_id == "19257":
                send_sms(phone,text,"茗酒荟")
            else:
                send_sms(phone,text)
            #send_message(text,phone)
            data['code'] = code
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'
    return JsonResponse(data)


#积分商城地址接口
@csrf_exempt
def mall_mobile_url(request):
    data = {
        'e':'',
        'url':''
    }
    grade_id = request.GET.get('grade_id','')
    company_id = request.GET.get('company_id','')
    if grade_id and company_id:
        if grade_id == "2":
            agent_id = request.GET.get('agent_id','')
            if agent_id:
                ts = int(time.time())
                # 加密算法
                params = company_id + '&' + grade_id + '&' + agent_id + '&' + str(ts) + '&' + interface_key;
                sign = str(hashlib.md5(params.encode('utf-8')).hexdigest()).lower()

                data['url'] = domain + '/mall/m/' + company_id + '/' + grade_id + '/?ts=' + str(
                    ts) + '&sn=' + sign + '&agent_id=' + agent_id
            else:
                data['e'] = '数据丢失'
        elif grade_id =="3":
            sales_man_id = request.GET.get('sales_man_id','')
            if sales_man_id:
                ts = int(time.time())
                # 加密算法
                params = company_id + '&' + grade_id + '&' + sales_man_id + '&' + str(ts) + '&' + interface_key;
                sign = str(hashlib.md5(params.encode('utf-8')).hexdigest()).lower()

                data['url'] = domain + '/mall/m/' + company_id + '/' + grade_id + '/?ts=' + str(
                    ts) + '&sn=' + sign + '&sales_man_id=' + sales_man_id
            else:
                data['e'] = '数据丢失'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)

#积分商城地址
def mall_mobile(request,company_id,grade_id):

    data = {
        'e':''
    }
    member = None

    def to_mall():
        response = render(request, 'mall/m/index.html')
        response.delete_cookie('mall_uid')
        if member:
            if grade_id == '1':
                if member.phone:
                    response.set_cookie('mall_uid', member.id,
                            expires=datetime.datetime.now() + datetime.timedelta(days=1))
            else:
                response.set_cookie('mall_uid', member.id,
                                    expires=datetime.datetime.now() + datetime.timedelta(days=1))
        response.set_cookie('grade_id', grade_id,
                            expires=datetime.datetime.now() + datetime.timedelta(days=1))
        response.set_cookie('wx_company_id', company_id,
                            expires=datetime.datetime.now() + datetime.timedelta(days=1))
        return response

    def checkSign(id):
        sign = request.GET.get('sn', '')
        ts = request.GET.get('ts', '')
        if sign and ts:
            ts_now = int(time.time())
            if abs(ts_now - int(ts)) <= 3600:
                md5 = hashlib.md5()
                # 加密算法
                params = company_id + '&' + grade_id + '&' + id + '&' + ts + '&' + interface_key;
                realSign = str(hashlib.md5(params.encode('utf-8')).hexdigest()).lower()
                if sign == realSign:
                    return  True
                else:
                    data['e'] = '数据错误'
            else:
                data['e'] = '网络超时'
        else:
            data['e'] = '数据丢失'
        return  False


    setting = Settings.objects.filter(company_id=int(company_id))
    if setting:
        setting = setting[0]
        if setting.is_open:
            # 如果是消费者
            if grade_id == "1":
                consumer_id = request.COOKIES.get('TJWX_consumer_id', '')
                if consumer_id:
                    consumer = ConsumerAccount.objects.get(id=int(consumer_id))
                    if consumer:
                        member = Member.objects.filter(consumer_id=int(consumer_id), company_id=int(company_id))
                        if member:
                            member = member[0]
                            member.headImg = consumer.wx_headimgurl
                            member.name = consumer.wx_nickname
                            member.save()

                        return to_mall()
                    else:
                        data['e'] = '用户不存在'
                else:
                    # 去授权
                    return wx_tjfw_base_oauth(request,company_id,'/mall/m/'+company_id+'/1/')
            # 如果是经销商
            elif grade_id == "2":
                agent_id = request.GET.get('agent_id', '')
                if agent_id:
                    #检查签名
                    if not checkSign(agent_id):
                        return render(request, 'mall/m/error.html', data)
                    member = Member.objects.filter(agent_id=int(agent_id), company_id=int(company_id))
                    if member:
                        member = member[0]
                        return to_mall()
                    else:
                        comp = Company.objects.filter(id=int(agent_id), ancestor_id=int(company_id))
                        if comp:
                            comp = comp[0]
                            member = Member(
                                agent=comp,
                                company_id=int(company_id),
                                name=comp.name,
                                gender=0,
                                remark='积分商城注册',
                                province=comp.province,
                                city=comp.city,
                                phone=comp.cell_phone,
                                grade_id=2,
                                headImg=domain+'/static/images/public/avator.png'
                            )
                            member.save()
                            return to_mall()
                        else:
                            data['e'] = '经销不存在'
                else:
                    data['e'] = '数据丢失'
            # 如果是业务员
            elif grade_id == "3":
                sales_man_id = request.GET.get('sales_man_id', '')
                if sales_man_id:
                    if not checkSign(sales_man_id):
                        return render(request, 'mall/m/error.html', data)
                    member = Member.objects.filter(sales_man=int(sales_man_id), company_id=int(company_id))
                    if member:
                        member = member[0]
                        return to_mall()
                    else:
                        sales_man = User.objects.filter(id=int(sales_man_id), ancestor_id=int(company_id))
                        if sales_man:
                            sales_man = sales_man[0]
                            member = Member(
                                sales_man=sales_man,
                                company_id=int(company_id),
                                name=sales_man.username,
                                gender=0,
                                remark='积分商城注册',
                                phone=sales_man.phone,
                                grade_id=3,
                                headImg=domain+'/static/images/public/avator.png'
                            )
                            member.save()
                            return to_mall()
                        else:
                            data['e'] = '经销不存在'
                else:
                    data['e'] = '数据丢失'
            else:
                data['e'] = '数据错误'
        else:
            data['e'] = '积分商城未开通'
    else:
        data['e'] = '积分商城未开通'

    return render(request, 'mall/m/error.html',data)
