
from django.shortcuts import render, redirect
import io
import xlwt
# from django.http import FileResponse
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from reportlab.pdfgen import canvas

# Create your views here.
from django.utils.translation import gettext_lazy as _
from calendar import monthrange
from utils.views import *
from django.db import connection
from .forms import *
from .models import *
from django.apps import apps
import datetime
from lxml import etree
import xlrd
from xlrd import *
from urllib.parse import urlencode
from http.client import HTTPConnection
from random import shuffle
from wx.views import send_hb, transfer_batch, send_wechat_message_template
from inventory.views import LabelQuery
from utils.views import *
from django.db.models import Count

from django.contrib.auth.decorators import login_required
from mall.views import update_member_points_consumer, update_member_points_agent

sK = 'fgfdGvgu$#&3tE@j'

# 2021-03-02
from wx.views import start_wx_enterprise_pay, send_hb_qz

from product.models import Product

from inventory.views import label_sys_info
# wx/wx_enterprise_pay.py
# start_wx_enterprise_pay
import math

# 2022-05-07
from company.models import CompanyCfgOpt

# 2022-06-11 微信消息模板
from wx.views import wechat_message_template_send, SEND_TEMPLATE_MESSAGE_URL

# 2023-03-10
from django.views.decorators.csrf import csrf_exempt


@tj_login_required
def qry_month(request):
    total = 0
    prevTotal = 0
    cid = str(request.user.company.id)
    ancestor_id = request.user.company.ancestor_id
    dt = datetime.datetime.now()
    y = dt.year
    years = []
    for i in range(2019, y + 1):
        years.append(str(i))

    dt0 = dt.replace(day=1) - datetime.timedelta(days=1)
    if cid == "19257":
        dt0 = datetime.datetime.now()
    y = str(dt0.year)
    m = str(dt0.month).zfill(2)
    yr = request.GET.get('year', y)
    mn = request.GET.get('month', m)
    d = str(monthrange(int(yr), int(mn))[1])
    dt1 = str(yr) + '-' + mn + '-01'
    dt2 = str(yr) + '-' + mn + '-' + d
    data = {
        'quantitys': {'category': [], 'data': []},
        'agents': {'category': [], 'data': []},
        'products': {'data': []},
        'years': years,
        'y': yr,
        'm': mn,
        'total': total,
        'series': {'data': []},
        'prev_total': prevTotal,
        'cid': cid
    }
    datap = {
        'quantitys': {'category': [], 'data': []},
        'agents': {'category': [], 'data': []},
        'products': {'data': []},
        'years': years,
        'y': yr,
        'm': mn,
        'total': total,
        'prev_total': prevTotal,
        'cid': cid
    }

    def queryAction(cid, dt1, dt2, data):
        # 查询总数
        sWhere = "where company_id=" + cid + " and vtype_id=2 and (dt between '" + dt1 + "' and '" + dt2 + "')"
        cur = connection.cursor()

        s = "select dt," + \
            "sum((select count(*) from stkdetails.c" + str(ancestor_id) + " where batch_id=a.id)) " + \
            "from inventory_batch a " + sWhere + " group by dt order by dt"
        cur.execute(s)
        for r in cur.fetchall():
            if int(r[1]) > 0:
                data['quantitys']['category'].append(str(r[0].day).zfill(2))
                data['quantitys']['data'].append(int(r[1]))

        s = "select (select name from product_product where id=b.product_id),b.qty qty" + \
            " from (select product_id," + \
            "sum((select count(*) from stkdetails.c" + str(ancestor_id) + " where batch_id=a.id)) qty " + \
            "from inventory_batch a " + sWhere + " group by product_id order by qty desc limit 20) b"
            
        s = "SELECT ( SELECT NAME FROM product_product WHERE ID = b.product_id ), b.qty qty  " + \
            "FROM (SELECT product_id,SUM ( ( SELECT COUNT ( * ) FROM stkdetails.c19318 WHERE id= A.id ) ) qty  " + \
            "FROM stkdetails.c" + str(ancestor_id) + " A " + sWhere + " GROUP BY product_id ORDER BY	qty DESC LIMIT 20 ) b "
        cur.execute(s)
        for r in cur.fetchall():
            if int(r[1]) > 0:
                data['products']['data'].append({'value': int(r[1]), 'name': r[0].replace('\\', '')})
            # data['products']['category'].append(r[0])
            # data['products']['data'].append(int(r[1]))

        s = "select (select name from company_company where id=b.company_to_id),b.qty,b.company_to_id" + \
            " from (select company_to_id," + \
            "sum((select count(*) from stkdetails.c" + str(ancestor_id) + " where batch_id=a.id)) qty " + \
            "from inventory_batch a " + sWhere + " group by company_to_id order by qty desc limit 20) b"
        cur.execute(s)
        for i, r in enumerate(cur.fetchall()):
            # data['agents']['category'].append(r[0])
            # data['agents']['data'].append(int(r[1]))
            if int(r[1]) > 0:
                data['agents']['data'].append({'value': int(r[1]), 'name': r[0], 'index': i, 'company_to_id': r[2]})

    def queryPreviousTotal(cid, dt3, dt4):
        cur = connection.cursor()
        s = "select sum(b.sum) from (select sum((select count(*) from stkdetails.c" + str(ancestor_id) + " where batch_id = a.id)) from logistics.inventory_batch a where company_id = " + cid + " and vtype_id = 2 and (dt between '" + dt3 + "' and '" + dt4 + "') group by dt order by dt)b"
        cur.execute(s)
        r = cur.fetchone()
        return r[0]

    # ---- 查询:按系列分类的总数
    sql = "select series_id,cnt,f.name from (select (select series_id from logistics.product_product where id=product_id) series_id,count(*) cnt " \
          "from stkdetails.c" + str(ancestor_id) + " where vtype_id=2 and company_id='" + cid + "' and (dt between '" + dt1 + "' and '" + dt2 + "'" + ") " \
                                                                                                                                                 "group by series_id)e left join logistics.product_series f on e.series_id=f.id order by cnt desc"
    cur = connection.cursor()
    cur.execute(sql)
    for r in cur.fetchall():
        r0 = r[0]
        r1 = r[1]
        r2 = r[2]
        if (r[0] == None):
            r0 = "无"
            r2 = "其他"
        data['series']['data'].append({'series': r0, 'count': r1, 'name': r2})

    # ---- 查询:按系列分类的总数
    pyr = yr  # (可能的)上一年pyr
    pM = str(int(mn.lstrip('0')) - 1).zfill(2)  # 上个月
    if mn == "01":  # 如果跨年, 这个月是1月，那么上个月是12月，年 - 1
        pM = "12"
        pyr = str(int(yr) - 1)
    dt3 = str(pyr) + '-' + pM + '-01'  # 日期的节点
    dt4 = str(pyr) + '-' + pM + '-' + str(monthrange(int(pyr), int(pM))[1])
    queryAction(cid, dt1, dt2, data)
    # queryAction(cid, dt3, dt4, datap)

    for num in data['quantitys']['data']:  # 设置总数
        data['total'] += num
    # for num in datap['quantitys']['data']:
    #     datap['total'] += num
    # data['prev_total'] = datap['total']     #替换要发送的data中的prev_total

    data['prev_total'] = str(queryPreviousTotal(cid, dt3, dt4))

    data['products']['data'].reverse()
    # print(data)
    return render(request, 'sales/monthly.html', data)


def ajax_qry_agent_detail(request):
    response_array = []

    dt = datetime.datetime.now()
    dt0 = dt.replace(day=1) - datetime.timedelta(days=1)
    y = str(dt0.year)
    m = str(dt0.month).zfill(2)

    yr = request.GET.get('year', y)
    mn = request.GET.get('month', m)
    d = str(monthrange(int(yr), int(mn))[1])
    dt1 = str(yr) + '-' + mn + '-01'
    dt2 = str(yr) + '-' + mn + '-' + d

    cid = request.GET.get('cid')
    comp_to_id = request.GET.get('comp_to_id')
    cur = connection.cursor()
    ancestor_id = get_ancestorId(cid)

    type = request.GET.get('type')
    if cid != None and comp_to_id != None and type != None:
        if type == "agent":
            sql = "select a.product_id, a.count, b.name from (select product_id,count(*) from " \
                  "stkdetails.c" + ancestor_id + " where company_id=" + cid + " and company_to_id=" + comp_to_id + " and vtype_id=2 and (dt between '" + dt1 + "' and '" + dt2 + "')" \
                                                                                                                                                                                 " group by product_id) a " \
                                                                                                                                                                                 "left join logistics.product_product b on a.product_id = b.id"

            cur.execute(sql)
            for r in cur.fetchall():
                response_array.append({"name": r[2], "count": r[1]})
            return JsonResponse({"value": response_array})
        elif type == "series":
            series = request.GET.get('series')
            if series != '无':
                sql = "select * from (select a.count, b.name, b.series_id from (select product_id, count(*) " \
                      "from stkdetails.c" + ancestor_id + " where company_id='" + cid + "' and vtype_id=2 and (dt between '" + dt1 + "' and '" + dt2 + "')" \
                                                                                                                                                       "group by product_id) a " \
                                                                                                                                                       "left join logistics.product_product b " \
                                                                                                                                                       "on a.product_id=b.id) c where series_id=" + series + " order by c.count desc limit 20"
            else:
                sql = "select * from (select a.count, b.name, b.series_id from (select product_id, count(*) " \
                      "from stkdetails.c" + ancestor_id + " where company_id='" + cid + "' and vtype_id=2 and (dt between '" + dt1 + "' and '" + dt2 + "')" \
                                                                                                                                                       "group by product_id) a " \
                                                                                                                                                       "left join logistics.product_product b " \
                                                                                                                                                       "on a.product_id=b.id) c where series_id is null order by c.count desc limit 20"

            cur.execute(sql)
            for r in cur.fetchall():
                # print(r)
                r1 = r[1]
                r0 = r[0]
                if (len(r[1]) == 0):
                    r1 = "未知"
                response_array.append({"name": r1, "count": r0})
            return JsonResponse({"value": response_array})
        else:
            return JsonResponse({"e": 'Invalid type.'})
    else:
        return JsonResponse({'e': 'Lack of parameters.'})
    return JsonResponse([], safe=False)


def ajax_qry_month(request, vtype_id):
    cid = request.GET.get('company_id', '')
    e = time_key_check(request, sK)
    if e:
        return JsonResponse({'e': e})
    if not cid:
        return JsonResponse({'e': 'company_id err'})

    dt = datetime.datetime.now()
    y = dt.year
    years = []
    for i in range(2019, y + 1):
        years.append(str(i))

    dt0 = dt.replace(day=1) - datetime.timedelta(days=1)
    y = str(dt0.year)
    m = str(dt0.month).zfill(2)
    yr = request.GET.get('year', y)
    mn = request.GET.get('month', m)
    d = str(monthrange(int(yr), int(mn))[1])
    dt1 = str(yr) + '-' + mn + '-01'
    dt2 = str(yr) + '-' + mn + '-' + d

    dt1 = str(yr) + '-' + mn + '-01'
    dt2 = str(yr) + '-' + mn + '-' + d
    dt1 = request.GET.get('date_from', dt1)
    dt2 = request.GET.get('date_to', dt2)

    if vtype_id == '2':
        data = {
            'quantitys': {'category': [], 'data': []},
            'agents': {'category': [], 'data': []},
            'products': {'data': []},
            'years': years,
            'y': yr,
            'm': mn,
            'date_from': dt1,
            'date_to': dt2
        }
    elif vtype_id == '1':
        data = {
            'quantitys': {'category': [], 'data': []},
            'products': {'data': []},
            'years': years,
            'y': yr,
            'm': mn,
            'date_from': dt1,
            'date_to': dt2
        }

    sWhere = "where company_id=" + cid + " and vtype_id=" + vtype_id + " and (dt between '" + dt1 + "' and '" + dt2 + "')"
    cur = connection.cursor()
    ancestor_id = get_ancestorId(cid)
    s = "select dt," + \
        "sum((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id)) " + \
        "from inventory_batch a " + sWhere + " group by dt order by dt"
    cur.execute(s)
    for r in cur.fetchall():
        # data['quantitys']['category'].append(str(r[0].day).zfill(2))
        data['quantitys']['category'].append(r[0].strftime('%Y-%m-%d'))
        data['quantitys']['data'].append(int(r[1]))

    s = "select (select name from product_product where id=b.product_id),b.qty qty" + \
        " from (select product_id," + \
        "sum((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id)) qty " + \
        "from inventory_batch a " + sWhere + " group by product_id order by qty desc limit 10) b"
    cur.execute(s)
    for r in cur.fetchall():
        data['products']['data'].append({'value': int(r[1]), 'name': r[0]})
        # data['products']['category'].append(r[0])
        # data['products']['data'].append(int(r[1]))

    if vtype_id == '2':
        s = "select (select name from company_company where id=b.company_to_id),b.qty qty" + \
            " from (select company_to_id," + \
            "sum((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id)) qty " + \
            "from inventory_batch a " + sWhere + " group by company_to_id order by qty desc limit 10) b"
        cur.execute(s)
        for r in cur.fetchall():
            # data['agents']['category'].append(r[0])
            # data['agents']['data'].append(int(r[1]))
            data['agents']['data'].append({'value': int(r[1]), 'name': r[0]})

    c = request.GET.get('callback', '')
    if c:
        response = json.dumps(data, ensure_ascii=False)
        return HttpResponse(c + '(' + response + ')')
    else:
        return JsonResponse(data)


@tj_login_required
def qry_date(request):
    cid = str(request.user.company.id)
    dt = datetime.datetime.now()
    y = dt.year
    years = []
    for i in range(2019, y + 1):
        years.append(str(i))

    dt0 = dt.replace(day=1) - datetime.timedelta(days=1)
    if cid == "19257":
        dt0 = datetime.datetime.now()
    y = str(dt0.year)
    m = str(dt0.month).zfill(2)
    yr = request.GET.get('year', y)
    mn = request.GET.get('month', m)
    d = str(monthrange(int(yr), int(mn))[1])

    dt1 = str(yr) + '-' + mn + '-01'
    dt2 = str(yr) + '-' + mn + '-' + d
    dt1 = request.GET.get('date_from', dt1)
    dt2 = request.GET.get('date_to', dt2)

    data = {
        'quantitys': {'category': [], 'data': []},
        'agents': {'category': [], 'data': []},
        'products': {'data': []},
        'years': years,
        'y': yr,
        'm': mn,
        'date_from': dt1,
        'date_to': dt2
    }
    sWhere = "where company_id=" + cid + " and vtype_id=2 and (dt between '" + dt1 + "' and '" + dt2 + "')"
    cur = connection.cursor()
    ancestor_id = get_ancestorId(cid)
    s = "select dt," + \
        "sum((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id)) " + \
        "from inventory_batch a " + sWhere + " group by dt order by dt"
    cur.execute(s)
    for r in cur.fetchall():
        data['quantitys']['category'].append(r[0].strftime('%Y-%m-%d'))
        data['quantitys']['data'].append(int(r[1]))

    s = "select (select name from product_product where id=b.product_id),b.qty qty" + \
        " from (select product_id," + \
        "sum((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id)) qty " + \
        "from inventory_batch a " + sWhere + " group by product_id order by qty desc limit 10) b"
    cur.execute(s)
    for r in cur.fetchall():
        data['products']['data'].append({'value': int(r[1]), 'name': r[0]})
        # data['products']['category'].append(r[0])
        # data['products']['data'].append(int(r[1]))

    s = "select (select name from company_company where id=b.company_to_id),b.qty qty" + \
        " from (select company_to_id," + \
        "sum((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id)) qty " + \
        "from inventory_batch a " + sWhere + " group by company_to_id order by qty desc limit 10) b"
    cur.execute(s)
    for r in cur.fetchall():
        # data['agents']['category'].append(r[0])
        # data['agents']['data'].append(int(r[1]))
        data['agents']['data'].append({'value': int(r[1]), 'name': r[0]})

    return render(request, 'sales/daily.html', data)


@tj_login_required
def agents_scan(request):
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    data = {'lv1': [], 'lv2': [], 'e': '', "date_from": dt_fr, "date_to": dt_to}
    cur = connection.cursor()
    c = request.user.company
    cid = str(c.id)
    if c.level.sn == 0:
        s = "select (select name from company_company where id=r.company_id)," + \
            "coalesce(r.cnt::int,0),coalesce(c.cnt::int,0) from " + \
            "(select company_id,sum((select count(*) cnt from inventory_batchdetails where batch_id=a.id)) cnt" + \
            " from inventory_batch  a " + \
            " where vtype_id=1 and level_id=2 and ancestor_id=" + cid + " and company_id<>" + cid + \
            " and dt between '" + dt_fr + "' and '" + dt_to + "'" + \
            " group by company_id" + \
            ") r " + \
            " left outer join " + \
            "(select company_id,sum((select count(*) cnt from inventory_batchdetails where batch_id=a.id)) cnt" + \
            " from inventory_batch  a where vtype_id=2" + \
            " and ancestor_id=" + cid + " and company_id<>" + cid + \
            " and dt between '" + dt_fr + "' and '" + dt_to + "'" + \
            " group by company_id" + \
            ") c " + \
            "on r.company_id=c.company_id " + \
            "where (select cell_phone from company_company where id=r.company_id) is not null"
        cur.execute(s)
        for r in cur.fetchall():
            if r[2] == 0 or r[1] == 0:
                rt = ''
            else:
                rt = str(round(r[2] * 100 / r[1], 2)) + '%'
            data['lv1'].append([
                r[0], r[1], r[2], rt
            ])

        s = "select (select name from  company_company where id=s.company_id)," + \
            "(select name from company_company where id=s.company_to_id)," + \
            "coalesce(s.cnt::int,0),coalesce(r.cnt::int,0),coalesce(c.cnt::int,0) from " + \
            "(select company_id,company_to_id,sum((select count(*) cnt from inventory_batchdetails where batch_id=a.id)) cnt " + \
            "from inventory_batch a where vtype_id=2 and level_id=2 and  ancestor_id=" + cid + \
            " and dt between '" + dt_fr + "' and '" + dt_to + "'" + \
            " group by company_id,company_to_id" + \
            ") s " + \
            "left outer join " + \
            "(select company_id,sum((select count(*) cnt from inventory_batchdetails where batch_id=a.id)) cnt " + \
            "from inventory_batch a	where vtype_id=1 and level_id=4 and ancestor_id=" + cid + \
            " and dt between '" + dt_fr + "' and '" + dt_to + "'" + \
            " group by company_id" + \
            ") r " + \
            "on s.company_to_id=r.company_id " + \
            "left outer join " + \
            "(select company_id,sum((select count(*) cnt from inventory_batchdetails where batch_id=a.id)) cnt " + \
            "from inventory_batch a	where vtype_id=2 and level_id=4 and ancestor_id=" + cid + \
            " and dt between '" + dt_fr + "' and '" + dt_to + "'" + \
            " group by company_id" + \
            ") c " + \
            "on s.company_to_id=c.company_id " + \
            "where r.cnt>0"

        cur.execute(s)
        for r in cur.fetchall():
            data['lv2'].append([
                r[0], r[1], r[2], r[3], r[4]
            ])

    return render(request, 'sales/agents_scan.html', data)


@login_required
def edit_obj(request, obj_name, id=None):
    data = {'form': None, 'is_saved': False, 'companys': []}
    cur = connection.cursor()
    u = request.user
    c = u.company
    ancestor_id = get_ancestorId(c.id)
    is_saved = False
    can_edit = False
    if u.id in [1, 3506]:
        for co in Company.objects.filter(level_id=1).order_by('name'):
            data['companys'].append([co.id, co.name])
    else:
        data['companys'].append([c.id, c.name])
    m = apps.get_model('sales', obj_name)
    if id:
        obj = m.objects.get(id=int(id))
        # data['company_id']=obj.company_id
    else:
        obj = m()
        obj.user = u
        # obj.company=c
        obj.status = 0
    if request.method == 'GET':
        if obj_name == 'Award':
            form = AwardForm(instance=obj)
        elif obj_name == 'Activities':
            cur.execute("SELECT id, name  FROM gis.adm where level=1 order by name")
            form = ActivitiesForm(instance=obj, user=u)
            formset = ActivityAwardsFormset(instance=obj)
            a = []
            for r in cur.fetchall():
                a.append([r[0], r[1]])
            data['prs'] = a
            agents = []
            products = []
            levels = []
            adms = []
            batch_ids = []
            if id:
                cur.execute("select id,name from company_company where id in " + \
                            "(select unnest((select agents from sales_activities where id=" + id + ")))"
                            )
                for r in cur.fetchall():
                    agents.append([r[0], r[1]])
                cur.execute("select id,name from product_product where id in " + \
                            "(select unnest((select products from sales_activities where id=" + id + ")))"
                            )
                for r in cur.fetchall():
                    products.append([r[0], r[1]])
                cur.execute("select id,name from company_level where id in " + \
                            "(select unnest((select agent_lvs from sales_activities where id=" + id + ")))"
                            )
                for r in cur.fetchall():
                    levels.append([r[0], r[1]])
                cur.execute(
                    "SELECT id, case when level=1 then name else (select name from gis.adm where id=a.id_1)||name end " + \
                    "FROM gis.adm a where id in (select unnest((select adm_ids from sales_activities where id=" + id + ")))"
                    )
                for r in cur.fetchall():
                    adms.append([r[0], r[1]])
                s = "SELECT a.id,a.code||'  '||coalesce(p.name,'')||'  '||coalesce(c.name) ||'  '||  " + \
                    "to_char((select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id),'9999999') from " + \
                    "(select id,company_id,product_id,code from inventory_batch  where id in " + \
                    "(select unnest((select batch_ids from sales_activities where id=" + id + "))) ) a " + \
                    "left outer join " + \
                    "(select id,name from product_product) p " + \
                    "on a.product_id=p.id " + \
                    "left outer join " + \
                    "(select id,name from company_company) c " + \
                    "on a.company_id=c.id "

                # print(s)

                cur.execute(s)
                for r in cur.fetchall():
                    batch_ids.append([r[0], r[1]])

            data['agents'] = agents
            data['products'] = products
            data['levels'] = levels
            data['adms'] = adms
            data['batch_ids'] = batch_ids
            data['formset'] = formset
    else:
        if obj_name == 'Award':
            form = AwardForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form.save()
                is_saved = True
        elif obj_name == 'Activities':
            form = ActivitiesForm(request.POST, request.FILES, instance=obj, user=request.user)
            formset = ActivityAwardsFormset(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form.save()

                # 2020-12-14
                if formset.is_valid():
                    formset.save()

                is_saved = True
                return HttpResponseRedirect('/obj/list/' + obj_name.lower() + '/')

    data['form'] = form
    data['is_saved'] = is_saved
    if u.id in [1, 3506, 3886, 3901, 2908, 3214]:
        can_edit = True
    # if u.id == 3886:
    #    can_edit=True
    # if u.id ==3901:
    #    can_edit=True
    data['can_edit'] = can_edit

    return render(request, 'sales/' + obj_name.lower() + '.html', data)


# 2020-08-17
def activity_draw(request, act_id):
    data = {'e': '', 'winner_id': 0, 'award': {'name': '', 'img': ''}}
    acts = Activities.objects.filter(id=int(act_id))
    if acts:
        act = acts[0]
        awd = act.draw()
        if awd:
            data['award']['name'] = awd.name
            data['award']['img'] = awd.award.photo.url
            # 写入中奖记录
            w = ConsumerWinner(
                company_id=request.session['wx_company_id'],
                consumer_id=request.session['wx_consumer_id'],
                labelscan_id=request.session['wx_labelscan_id'],
                label_code=request.session['wx_label_code'],
                activity_id=int(act_id),
                award_id=awd.id
            )
            w.save()
            data['winner_id'] = w.id
    else:
        data['e'] = 'activity requested not exists'
    return JsonResponse(data)


def ajax_winning_list(request, company_id, consumer_id):
    data = {'e': '', 'nickname': '', 'headimgurl': '', 'records': []}
    cur = connection.cursor()
    cur.execute("select wx_nickname,wx_headimgurl from sales_consumeraccount where id=" + consumer_id)
    r = cur.fetchone()
    if r:
        data['nickname'] = r[0]
        data['headimgurl'] = r[1]
        s = "select c.name,to_char(a.tm,'yyyy-mm-dd HH24:MI:SS'),coalesce(to_char(a.tm_redeemed,'yyyy-mm-dd HH24:MI:SS'),'')," + \
            "(select name from sales_award where id=c.award_id) from " + \
            "(SELECT label_code,award_id,tm,tm_redeemed from sales_consumerwinner " + \
            "where company_id=" + company_id + " and consumer_id=" + consumer_id + " order by tm) a " + \
            "left outer join " + \
            "(select id,name,activity_id,award_id from sales_activityawards) c " + \
            "on a.award_id=c.id " + \
            "order by tm"
        cur.execute(s)
        for r in cur.fetchall():
            data['records'].append({"award_code": r[0], 'time': r[1], 'award_name': r[3], 'time_redeem': r[2]})
    else:
        data['e'] = 'consumer id error'
    return JsonResponse(data)
    # return HttpResponse(json.dumps(data, ensure_ascii=False))


def ajax_consumer_redeem(request):
    data = {"e": '', 'msg': ''}
    winner_id = request.GET.get('winner_id', '')
    name = request.GET.get('name', '')
    phone = request.GET.get('phone', '')
    address = request.GET.get('address', '')
    remark = request.GET.get('remark', '')
    if winner_id:
        winner_id = decrypt_p(winner_id)
        rds = ConsumerRedeem.objects.filter(winner_id=int(winner_id))
        if rds:
            data['e'] = _('奖品已领过了..')
        else:
            ws = ConsumerWinner.objects.filter(id=int(winner_id)).order_by('-id')
            if ws:
                w = ws[0]
                vs = VoidLabel.objects.filter(label_code=w.label_code)
                if len(vs) == 0:
                    if w.tm_redeemed:
                        data['e'] = _('奖品已领过了..')
                    else:
                        if name:
                            w.name = name
                        if phone:
                            w.phone = phone
                        w.address = address
                        w.remark = remark

                        if w.company_id == 110887:
                            w.tm_expire = datetime.datetime.now() + datetime.timedelta(days=30)

                        if w.award_cat == '福袋':
                            label_code = request.GET.get('label_code', '')
                            if label_code:
                                w.tm_redeemed = now()
                                w.save()
                                w_label = ConsumerWinner.objects.filter(label_code=label_code)
                                if w_label:
                                    data['e'] = _('奖品已领过了..')
                                else:
                                    points = 0
                                    amount = 0
                                    award = w.can_active_award.award
                                    if award.points:
                                        points = award.points
                                    if award.amount:
                                        amount = award.amount
                                    w2 = ConsumerWinner(
                                        company_id=w.company_id,
                                        consumer_id=w.consumer_id,
                                        label_code=label_code,
                                        activity_id=w.activity.id,
                                        activity_name=w.activity.name,
                                        award_id=w.can_active_award_id,
                                        original_award=award,
                                        award_name=award.name,
                                        award_points=points,
                                        award_amount=amount,
                                        award_img=award.photo,
                                        award_cat=award.awardcat.name,
                                        is_need_hexiao=award.is_need_hexiao
                                    )
                                    w2.save()
                            else:
                                data['e'] = '数据丢失'

                        else:
                            award = w.award.award
                            awardcat_id = award.awardcat.id
                            if awardcat_id == 4:
                                # data['msg']='os,'+w.label_code+","+w.consumer.wx_openid+":"+str(w.award.award.amount)
                                openid = w.consumer.wx_openid
                                money = int(award.amount * 100)
                                company_id = w.company_id

                                if (openid == "oh_9g0sFdwfInjKWZrT8ODpFCPKI" or
                                        openid == "oLnwB6aAAUd6Cbp0jBMpgO46ikn0" or
                                        openid == "o2PgU5n7ngNcFXVsq2yTV9XQC--o" or
                                        openid == "oPbbT6EmDE381jqHfuKKXDttneZg" or
                                        openid == "oPbbT6KpxYvcGy13wIvZUKOV_wLY" or
                                        openid == "olr-CuLXpgIlqZTxdII5QDOyoX5k"
                                        ):
                                    money = 100

                                err = send_hb(openid, money, company_id)
                                # print(err)
                                if err['return_code'] == 'SUCCESS':
                                    if err['result_code'] == 'SUCCESS':
                                        w.tm_redeemed = now()
                                        w.save()

                                        if 'send_listid' in err:
                                            wxpay_code = err['send_listid']

                                        if 'partner_trade_no' in err:
                                            wxpay_code = err['partner_trade_no']

                                        w.wxpay_code = wxpay_code

                                        w.save()
                                        try:
                                            set_AwardcatLog(request,w,award.amount,openid,remark)
                                        except:
                                            pass
                                    else:
                                        if err['return_msg'].startswith('您的商户号') or '余额不足' in err['return_msg']:
                                            data['e'] = '系统升级，请保留好二维码稍后再试-1'
                                        else:
                                            data['e'] = err['return_msg']
                                        if 'err_code_des' in err and err['err_code_des']:
                                            if err['err_code_des'].startswith('该用户今日付款次数超过限制'):
                                                data['e'] = '今天可领取次数已达上限'
                                            elif '余额不足' in err['err_code_des']:
                                                data['e'] = '系统升级，请保留好二维码稍后再试-2'
                                            else:
                                                data['e'] = err['err_code_des']
                                else:
                                    data['e'] = '网络超时'
                            # 如果是积分
                            elif awardcat_id == 2:
                                reason = '在《' + w.activity.name + '》活动中获得' + w.award.name
                                r = update_member_points_consumer(w.consumer.id, w.company_id, award.points, reason)
                                if r['e'] == '':
                                    # rd = ConsumerRedeem(winner_id=int(winner_id))
                                    # rd.save()
                                    w.tm_redeemed = now()
                                    w.save()
                                else:
                                    data['e'] = '添加积分失败'

                            else:

                                # 如果核销后需要发送红包
                                if award.send_hb_after_get:
                                    openid = w.consumer.wx_openid
                                    money = int(award.amount * 100)
                                    err = send_hb(openid, money, w.company_id)
                                    # print(err)
                                    if err['return_code'] == 'SUCCESS':
                                        if err['result_code'] == 'SUCCESS':
                                            wxpay_code = ''
                                            if 'send_listid' in err:
                                                wxpay_code = err['send_listid']

                                            if 'partner_trade_no' in err:
                                                wxpay_code = err['partner_trade_no']

                                            w.wxpay_code = wxpay_code
                                        else:
                                            data['e'] = err['return_msg']
                                            return JsonResponse(data)
                                    else:
                                        data['e'] = '网络超时'
                                        return JsonResponse(data)

                                if w.activity_id == 74:
                                    ls = LotterySeeds.objects.filter(label_code=w.label_code)
                                    if ls:
                                        activity_award_id = ls[0].award2
                                        w2_activity_award = ActivityAwards.objects.get(id=activity_award_id)
                                        w2 = ConsumerWinner(
                                            company_id=w.company_id,
                                            consumer_id=w.consumer_id,
                                            label_code=w.label_code,
                                            activity_id=w.activity_id,
                                            award_id=activity_award_id,
                                            activity_name=w.activity.name,
                                            award_name=w2_activity_award.name,
                                            award_img=w2_activity_award.award.photo,
                                            award_cat='卡券',
                                            is_need_hexiao=False,
                                            original_award_id=w2_activity_award.award.id,
                                            tm_redeemed=now()
                                        )
                                        w2.save()

                                        data["award2"] = {
                                            "name": w2.award_name
                                        }

                                w.tm_redeemed = now()
                                w.save()
                else:
                    data['e'] = '奖品已失效'
            else:
                data['e'] = 'winner id err'
    else:
        data['e'] = 'winner id missed'
    return JsonResponse(data)


@login_required
def qz_activitybonus(request):
    data = {
        "br": []
    }
    user = request.user
    company = user.company
    if company.id == 20445:
        o_bonusrecord = ActivityRebate_BonusRecord.objects.filter(company_id_id=20445).order_by('-id')[:20]
        br = []
        for i in o_bonusrecord:
            br.append({
                "id": i.id,
                "labelcode": i.labelcode,
                "operation": i.operation,
                "amount": i.amount,
                "product_id": i.product_id,
                "product": Product.objects.get(id=i.product_id).name,
                "tm": i.tm
            })
    return data


def qz_brandrecommender_redpack_retry(request):
    data = {
        'e': ''
    }
    record_id = request.GET.get('id', '')
    ar_br = ActivityRebate_BrandRecommenderRedpackRecord.objects.filter(id=record_id)
    if len(ar_br) > 0:
        openid = ar_br[0].openid
        result_code = ar_br[0].result_code
        bill_no = ar_br[0].bill_no
        bonus = ar_br[0].bonus

        if not bonus.is_redeemed:
            res = send_hb_qz(openid, bonus.amount * 100, isMiniProgram=True, billnumber=bill_no)
            if res['return_code'] == 'SUCCESS':
                ar_br[0].last_send_tm = datetime.datetime.now()
                ar_br[0].err_code_des = res['err_code_des']
                ar_br[0].return_code = res['return_code']
                ar_br[0].result_code = res['result_code']
                ar_br[0].save()
                if res['result_code'] == 'SUCCESS':
                    bonus.is_redeemed = True
                    bonus.save()

    return JsonResponse(data)


def qz_regular_redpack_retry(request):
    data = {
        'e': ''
    }
    record_id = request.GET.get('id', '')
    ar_sr = ActivityRebate_RedPackSendRecord.objects.filter(id=record_id)
    if len(ar_sr) > 0:
        openid = ar_sr[0].openid
        result_code = ar_sr[0].result_code
        bill_no = ar_sr[0].bill_no
        bonus_record = ar_sr[0].bonus_record

        if ar_sr[0].result_code == 'FAIL':
            res = send_hb_qz(openid, bonus_record.amount * 100, billnumber=bill_no)
            # print('res:', res)
            if res['return_code'] == 'SUCCESS':
                ar_sr[0].last_send_tm = datetime.datetime.now()
                ar_sr[0].err_code_des = res['err_code_des']
                ar_sr[0].return_code = res['return_code']
                ar_sr[0].result_code = res['result_code']
                ar_sr[0].save()

    return JsonResponse(data)


def qz_toggle_anniversary(request):
    data = {
        'e': ''
    }
    record_id = request.GET.get('id', '')
    ar = ActivityRebate_Anniversary.objects.filter(id=record_id)
    if len(ar) > 0:
        ar[0].is_redeemed = not ar[0].is_redeemed
        ar[0].save()
    return JsonResponse(data)


# 2020-09-09
@login_required
def channelpromotion(request, id=None):
    data = {'form': None, 'is_saved': False, 'companys': [],'triggers':[]}
    cur = connection.cursor()
    u = request.user
    c = u.company
    is_saved = False
    if u.id == 1:
        for co in Company.objects.filter(level_id=1).order_by('name'):
            data['companys'].append([co.id, co.name])
    else:
        data['companys'].append([c.id, c.name])
    if id:
        obj = ChannelPromotions.objects.get(id=int(id))
    else:
        obj = ChannelPromotions(company_id=c.id)
        obj.user = u
        obj.status = 0
    if request.method == 'GET':
        agents = []
        products = []
        div_ids = []
        subdiv_ids = []
        saldivision = []

        # 2022-11-29 
        for t in ChannelPromotionTrigger.objects.all():
            data['triggers'].append({'id':str(t.id),'text':t.name})

        if u.id != 1:
            cur.execute(
                "select id,name from company_salesdivision where company_id=" + str(u.company_id) + " order by name")
            for r in cur.fetchall():
                saldivision.append([r[0], r[1]])
        data['saldivision'] = saldivision
        form = ChannelPromotionsForm(instance=obj)
        form.fields['end_level'].queryset = Level.objects.filter(id__in=[2, 4, 5, 6, 7])
        formset = ChannelRebateFormset(instance=obj)
        if id:
            cur.execute("select id,name from company_company where id in " + \
                        "(select unnest((select agents from sales_channelpromotions where id=" + id + ")))"
                        )
            for r in cur.fetchall():
                agents.append([r[0], r[1]])
            cur.execute("select id,name from product_product where id in " + \
                        "(select unnest((select products from sales_channelpromotions where id=" + id + ")))"
                        )
            for r in cur.fetchall():
                products.append([r[0], r[1]])
            cur.execute("select id,name from company_salesdivision where id in " + \
                        "(select unnest((select div_ids from sales_channelpromotions where id=" + id + ")))"
                        )
            for r in cur.fetchall():
                div_ids.append([r[0], r[1]])
            cur.execute("select id,name from company_subsaldivision where id in " + \
                        "(select unnest((select subdiv_ids from sales_channelpromotions where id=" + id + ")))"
                        )
            for r in cur.fetchall():
                subdiv_ids.append([r[0], r[1]])
        data['agents'] = agents
        data['products'] = products
        data['formset'] = formset
        data['div_ids'] = div_ids
        data['subdiv_ids'] = subdiv_ids

        #2023-05-04        
        aformset = AccumulattionFormset(instance=obj) 
        # 2023-05-25
        cformset=CustomizeRebateFormset(instance=obj) 
    else:
        form = ChannelPromotionsForm(request.POST, request.FILES, instance=obj)
        formset = ChannelRebateFormset(request.POST, request.FILES, instance=obj)

        # 2023-05-04
        aformset = AccumulattionFormset(request.POST, request.FILES, instance=obj)
        # 2023-05-25
        cformset=CustomizeRebateFormset(request.POST, request.FILES, instance=obj)

        if form.is_valid():
            # p=form.save()
            if aformset.is_valid():
                aformset.save()
            if cformset.is_valid():
                cformset.save()
            
            
            del_ids = []
            for f in formset.deleted_forms:
               if f.instance.id:
                   del_ids.append(f.instance.id)
            p = form.save()
            for f in formset:
               f.instance.promotion = p
               if f.is_valid():
                   if f.instance.id not in del_ids:
                       f.save()
                   else:
                       f.instance.delete()
            return HttpResponseRedirect('/obj/list/channelpromotions/')
    data['form'] = form
    data['is_saved'] = is_saved

    # 2023-05-04
    data['aformset']=aformset
    # 2023-05-25
    data['cformset']=cformset

    return render(request, 'sales/channelpromotions.html', data)


# 2020-12-11
def channelrebate_app(request):
    data = {'e': '', 'data': []}
    k = 'fgfdvgu$#&3t@j'
    e = time_key_check(request, k)
    if e:
        return JsonResponse({'e': e, 'data': []})

    user_id = request.GET.get('user_id', '')
    dt_fr = request.GET.get('date_from', '')
    dt_to = request.GET.get('date_to', '')
    if not user_id or not dt_fr or not dt_to:
        return JsonResponse({'e': "user_id,date_from,date_to required", 'data': []})

    cur = connection.cursor()
    cur.execute("select company_id," + \
                "(select level_id from company_company where id=company_id)," + \
                "array_to_string(array(select group_id from company_user_groups where user_id=" + user_id + "),',') " + \
                "from company_user where id=" + user_id)
    r = cur.fetchone()
    if not r:
        return JsonResponse({'e': "user_id error", 'data': []})

    cid = str(r[0])
    lv_id = r[1]
    group_ids = r[2].split(',')
    if '5' in group_ids:  # 经销商
        sWhere = ''
        if lv_id == 2:  # 一级
            sWhere = " where (company_id=" + cid + " or company_id in (select id from company_company where parent_id=" + cid + "))"
        elif lv_id == 4:  # 二级
            sWhere = " where company_id=" + cid
        s = "select to_char(a.tm,'yyyy-mm-dd HH24:MI:SS')," + \
            "(select name from sales_channelpromotions where id=a.promotion_id)," + \
            "(select name from company_company where id=a.company_id)," + \
            "array_to_string(array(select name from product_product where id in (" + \
            "select product_id from sales_channelrebatedetails where rebate_batch_id=a.id)),',')," + \
            "case b.vtype_id when 1 then '扫码入库' when 2 then '扫码出库' end," + \
            "to_char(a.val,'FM99999999990.00')," + \
            "a.id," + \
            "(select count(*) from sales_channelrebatedetails where  rebate_batch_id=a.id and label_pkg=3)," + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1), " + \
            "(select name from company_company where id=b.company_to_id)," + \
            "b.vtype_id,a.batch_id from " + \
            "(SELECT id, tm_checked, tm_approved, val, tm, dt, tm_redeemed," + \
            "approved_by_id, batch_id, checked_by_id, company_id,promotion_id," + \
            "company_src_id, confirmed, distance FROM sales_channelrebatebatch " + \
            sWhere + " and checked_by_id>0 and (dt between '" + dt_fr + "' and '" + dt_to + "')" + \
            ") a " + \
            "left outer join " + \
            "(select id,product_id,vtype_id,company_to_id from inventory_batch) b " + \
            "on a.batch_id=b.id order by a.tm"

        cur.execute(s)
        for r in cur.fetchall():
            data['data'].append({
                'time': r[0],
                'promotion_name': r[1],
                'company_name': r[2],
                'product_name': r[3],
                'voucher_type': r[4],
                'amount': r[5],
                'batch_id': r[6],
                'boxes': r[7],
                'bottles': r[8]
            })
    return JsonResponse(data)


def channel_rebate_details_app(request, batch_id):
    data = {'e': '', 'data': []}
    k = 'fgfdvgu$#&3t@j'
    e = time_key_check(request, k)
    if e:
        return JsonResponse({'e': e, 'data': []})

    cur = connection.cursor()
    # 2020-11-16 sales_rebatesubstitute -> inventory_boxbottlesubstitute
    cur.execute("select label_code," + \
                "case label_pkg when 1 then '瓶标' when 3 then '箱标' when 2 then '盒标' end," + \
                "(select name from product_product where id=product_id)," + \
                "to_char(val,'999.90')," + \
                "(select coalesce(to_char(sum(val),'99999999.90'),'') from inventory_boxbottlesubstitute " + \
                "where rebate_batch_id=" + batch_id + " and label_pk_id=a.label_pk_id) " + \
                "from sales_channelrebatedetails a where rebate_batch_id=" + batch_id)
    for r in cur.fetchall():
        data['data'].append({
            'label': r[0],
            'package': r[1],
            'product': r[2],
            'amount': r[3],
            'neg_amount': r[4]
        })
    return JsonResponse(data)


# 2021-01-11
@login_required
def channel_rebate_update(request, what, id):
    data = {'e': '', 'agent': '', 'old': '', 'new': ''}
    u = request.user
    if what == 'payable':
        val = request.POST.get('value', '0.00')
        reason = request.POST.get('reason', '')
        o = RebatePayable.objects.get(id=int(id))
        v0 = float(o.amount_topay)
        o.amount_topay = float(val)
        d = {
            'user': u.last_name,
            'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'old': v0,
            'new': float(val),
            'reason': reason
        }
        o.log_edit.append(d)
        o.save()
        data = {'e': '', 'old': v0, 'new': float(val)}
    return JsonResponse(data)


# 2020-09-21
@login_required
def list_channelrebate_batch(request):
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    dt_max = max(dt_fr, dt_to)
    dt_min = min(dt_fr, dt_to)
    dt_fr = dt_min
    dt_to = dt_max
    d = []
    cur = connection.cursor()
    c = request.user.company

    # 2021-02-24
    # 杨盖:扫码明细表里，我们内勤会按平台商来查询 平台与下级分销的所有扫码明细
    agent_id = request.GET.get('agent_id', '')
    agent_name = ''
    sBatch = ''
    if agent_id:
        s = "select level_id,parent_id,name from company_company where id=" + agent_id
        cur.execute(s)
        r = cur.fetchone()
        if r:
            agent_name = r[2]
            if r[0] == 2:
                agt_id = agent_id
            else:
                agt_id = str(r[1])
            sBatch = "and (company_id=" + agt_id + " or " + \
                     "(select parent_id from company_company where id=company_id)=" + agt_id + ")"

    clmns = ['扫码时间', '平台商', '经销商/分销商', '战区', '分区', '层级', '产品名称', '扫码场景', '扫码类别', '箱数',
             '瓶数', '奖励金额(元)', '距离(米)', '扫码距离确认', '活动名称']
    if c.level_id == 1:
        s = "select to_char(a.tm,'yy-mm-dd HH24:MI:SS')," + \
            "case when c.level_id>2 then (select name from company_company where id=c.parent_id) else c.name end," + \
            "(select name from sales_channelpromotions where id=a.promotion_id)," + \
            "array_to_string(array(select name from product_product where id in (" + \
            "select product_id from sales_channelrebatedetails where rebate_batch_id=a.id)),',')," + \
            "case b.vtype_id when 1 then '扫码入库' when 2 then '扫码出库' when 4 then '销售退库' else '' end," + \
            "to_char(a.val,'FM99999999990.00')," + \
            "case when a.distance=99999999.99 then '未知' else to_char(a.distance,'FM99999') end," + \
            "case when checked_by_id=1 then '系统确认' else (select username from company_user where id=checked_by_id) end," + \
            "a.id," + \
            "a.tm_checked," + \
            "case when a.company_id<>a.company_src_id then 0 else " + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end," + \
            "case when a.company_id<>a.company_src_id then 0 else " + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end," + \
            "case when a.company_src_id=a.company_id then '自主扫码' else '下级扫码'  end," + \
            "(select name from company_level where id=c.level_id)," + \
            "a.batch_id," + \
            "coalesce((select name from company_salesdivision where id=c.division_id),'')," + \
            "coalesce((select name from company_subsaldivision where id=c.sub_division_id),'')," + \
            "case when c.level_id>2 then c.name else c.name end " + \
            "from " + \
            "(SELECT id, tm_checked, tm_approved, val, tm, dt, tm_redeemed," + \
            "approved_by_id, batch_id, checked_by_id, company_id,promotion_id," + \
            "company_src_id, confirmed, distance FROM sales_channelrebatebatch " + \
            "where ancestor_id=" + str(
            c.ancestor_id) + " and (dt between '" + dt_fr + "' and '" + dt_to + "') " + sBatch + \
            ") a " + \
            "left outer join " + \
            "(select id,product_id,vtype_id from inventory_batch) b " + \
            "on a.batch_id=b.id " + \
            "left outer join " + \
            "(select id,name,level_id,parent_id,division_id,sub_division_id from company_company where ancestor_id=" + str(
            c.id) + ") c " + \
            "on a.company_id=c.id"
        cur.execute(s)
        for r in cur.fetchall():
            a = "<a class='btn-details' href='/sales/channelretate/details/" + str(r[8]) + "/'>" + r[0] + "</a>"
            x = ''
            p = ''
            t = r[12]
            lv = r[13]
            if r[6]:
                m=r[6]
            else:
                m=''
            if r[2]:
                promotion=r[2]
            else:
                promotion=''
            if r[10]:
                if r[4] == '销售退库':
                    x = '-' + str(r[10])
                else:
                    x = str(r[10])
            if r[11]:
                if r[4] == '销售退库':
                    p = '-' + str(r[11])
                else:
                    p = str(r[11])
            cfm = r[7]
            if cfm:
                cfm = cfm + " " + r[9].strftime('%y-%m-%d %H:%M')
            else:
                if request.user.has_perm('company.sys_admin') and c.level_id == 1:
                    cfm = "待确认<a class='btn-confirm' href='/sales/update/channelrebate/" + str(
                        r[8]) + "/confirm/'>确认</a>"
            d.append([a, r[1], r[17], r[15], r[16], lv, r[3], r[4], t, x, p, r[5], m, cfm, promotion])

    else:
        if c.is_expense_account:
            if c.level_id == 2:
                sWhere = " where (select division_id from company_company where id=company_id)=" + str(c.division_id)
            elif c.level_id == 4:
                sWhere = " where (select sub_division_id from company_company where id=company_id)=" + str(
                    c.sub_division_id)
        else:
            sWhere = " where company_id=" + str(c.id)
        s = "select to_char(a.tm,'yyyy-mm-dd HH24:MI:SS')," + \
            "case when c.level_id>2 then (select name from company_company where id=c.parent_id) else c.name end," + \
            "(select name from sales_channelpromotions where id=a.promotion_id)," + \
            "array_to_string(array(select name from product_product where id in (" + \
            "select product_id from sales_channelrebatedetails where rebate_batch_id=a.id)),',')," + \
            "case b.vtype_id when 1 then '扫码入库' when 2 then '扫码出库' when 4 then '销售退库' else '' end," + \
            "to_char(a.val,'FM99999999990.00')," + \
            "case when a.distance=99999999.99 then '未知' else to_char(a.distance,'FM99999') end," + \
            "case when checked_by_id=1 then '系统确认' else (select username from company_user where id=checked_by_id) end," + \
            "a.id," + \
            "a.tm_checked," + \
            "case when a.company_id<>a.company_src_id then 0 else " + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end," + \
            "case when a.company_id<>a.company_src_id then 0 else " + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end," + \
            "case when a.company_src_id=a.company_id then '自主扫码' else '下级扫码'  end," + \
            "(select name from company_level where id=c.level_id)," + \
            "a.batch_id," + \
            "coalesce((select name from company_salesdivision where id=c.division_id),'')," + \
            "coalesce((select name from company_subsaldivision where id=c.sub_division_id),'')," + \
            "case when c.level_id>2 then c.name else c.name end " + \
            "from " + \
            "(SELECT id, tm_checked, tm_approved, val, tm, dt, tm_redeemed," + \
            "approved_by_id, batch_id, checked_by_id, company_id,promotion_id," + \
            "company_src_id, confirmed, distance FROM sales_channelrebatebatch " + \
            sWhere + " and dt between   '" + dt_fr + "' and '" + dt_to + "'" + \
            ") a " + \
            "left outer join " + \
            "(select id,product_id,vtype_id from inventory_batch) b " + \
            "on a.batch_id=b.id " + \
            "left outer join " + \
            "(select id,name,level_id,parent_id,division_id,sub_division_id from company_company where ancestor_id=" + str(
            c.ancestor_id) + ") c " + \
            "on a.company_id=c.id"

        cur.execute(s)
        for r in cur.fetchall():
            a = "<a class='btn-details' href='/sales/channelretate/details/" + str(r[8]) + "/'>" + r[0] + "</a>"
            x = ''
            p = ''
            t = r[12]
            lv = r[13]
            if r[10]:
                if r[4] == '销售退库':
                    x = '-' + str(r[10])
                else:
                    x = str(r[10])
            if r[11]:
                if r[4] == '销售退库':
                    p = '-' + str(r[11])
                else:
                    p = str(r[11])
            cfm = r[7]
            if cfm:
                cfm = cfm + " " + r[9].strftime('%Y-%m-%d %H:%M')
            d.append([a, r[1], r[17], r[15], r[16], lv, r[3], r[4], t, x, p, r[5], r[6], cfm, r[2]])

    data = {'clmns': clmns, 'data': d, 'date_from': dt_fr, 'date_to': dt_to, 'agent_id': agent_id,
            'agent_name': agent_name}
    return render(request, 'sales/list_channelrebate.html', data)


# 2020-09-21
@login_required
def update_channelrebate_batch(request, batch_id, what):
    data = {'e': ''}
    u = request.user
    b = ChannelRebateBatch.objects.get(id=int(batch_id))
    if what == 'confirm':
        b.checked_by = u
        b.tm_checked = datetime.datetime.now()
        b.confirmed = True
        b.save()
    return JsonResponse(data)


# 2020-09-29
@login_required
def summary_channelrebate_agent(request):
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    agent_id = request.GET.get('agent_id', '')
    agent_name = ''
    dt_max = max(dt_fr, dt_to)
    dt_min = min(dt_fr, dt_to)
    dt_fr = dt_min
    dt_to = dt_max
    d = []
    cur = connection.cursor()
    c = request.user.company
    sWhere = "where ancestor_id=" + str(c.id)
    if agent_id:
        sWhere = "where company_id=" + agent_id
        agent_name = Company.objects.get(id=int(agent_id)).name
    sWhere = sWhere + " and dt between '" + dt_fr + "' and  '" + dt_to + "' and checked_by_id>0 "
    '''
    if c.level_id==1:
        clmns=['经销商/分销商名称','战区','分区','层级','上一级公司名称','自主扫码箱','自主扫码瓶','下级扫码箱','下级扫码瓶','合计奖励(元)']
        s="select b.name,"+\
            "coalesce((select name from company_salesdivision where id=b.division_id),''),"+\
            "coalesce((select name from company_subsaldivision where id=b.sub_division_id),''),"+\
            "(select name from company_level where id=b.level_id),"+\
            "(select name from company_company where id=b.parent_id),"+\
            "to_char(a.mx,'FM99999999990'),"+\
            "to_char(a.mp,'FM99999999990'),"+\
            "to_char(a.cx,'FM99999999990'),"+\
            "to_char(a.cp,'FM99999999990'),"+\
            "to_char(a.val,'FM99999999990.00') "+\
            "from "+\
            "(select o.company_id,sum(o.val) val,sum(o.mx) mx,sum(o.mp) mp,sum(o.cx) cx,sum(o.cp) cp from "+\
                "(SELECT company_id,"+\
                    "val,"+\
                    "case when company_id<>company_src_id then 0 else "+\
                        "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end mx,"+\
                    "case when company_id<>company_src_id then 0 else "+\
                        "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end mp, "+\
                    "case when company_id=company_src_id then 0 else "+\
                        "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end cx,"+\
                    "case when company_id=company_src_id then 0 else "+\
                        "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end cp "+\
                    "FROM sales_channelrebatebatch a "+sWhere+\
                ") o "+\
                "group by o.company_id"+\
            ") a "+\
            "left outer join "+\
            "(select id,name,level_id,parent_id,division_id,sub_division_id from company_company where ancestor_id="+str(c.id)+") b "+\
            "on a.company_id=b.id"
        cur.execute(s)

        for r in cur.fetchall():           
            d.append([ r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9] ])

    else:
        clmns=[]   
    '''
    if c.level_id == 1:
        if c.ancestor_id == 1644:
            clmns = ['经销商/分销商名称', '战区', '分区', '层级', '上一级公司名称', '自主扫码箱', '自主扫码瓶',
                     '下级扫码箱', '下级扫码瓶',
                     '52度箱', '52度瓶', '54度箱', '54度瓶', '合计奖励(元)']
            s = "select b.name," + \
                "coalesce((select name from company_salesdivision where id=b.division_id),'')," + \
                "coalesce((select name from company_subsaldivision where id=b.sub_division_id),'')," + \
                "(select name from company_level where id=b.level_id)," + \
                "(select name from company_company where id=b.parent_id)," + \
                "to_char(a.mx,'FM99999999990')," + \
                "to_char(a.mp,'FM99999999990')," + \
                "to_char(a.cx,'FM99999999990')," + \
                "to_char(a.cp,'FM99999999990')," + \
                "to_char(a.x52,'FM99999999990')," + \
                "to_char(a.p52,'FM99999999990')," + \
                "to_char(a.x54,'FM99999999990')," + \
                "to_char(a.p54,'FM99999999990')," + \
                "to_char(a.val,'FM99999999990.00') " + \
                "from " + \
                "(select o.company_id,sum(o.val) val,sum(o.mx) mx,sum(o.mp) mp,sum(o.cx) cx,sum(o.cp) cp," + \
                "sum(o.x52) x52,sum(o.p52) p52,sum(o.x54) x54,sum(o.p54) p54 from " + \
                "(SELECT company_id," + \
                "val," + \
                "case when company_id<>company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end mx," + \
                "case when company_id<>company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end mp, " + \
                "case when company_id=company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end cx," + \
                "case when company_id=company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end cp," + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and product_id=900 and label_pkg=3) x52," + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and product_id=900 and label_pkg=1) p52," + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and product_id=1109 and label_pkg=3) x54," + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and product_id=1109 and label_pkg=1) p54 " + \
                "FROM sales_channelrebatebatch a " + sWhere + \
                ") o " + \
                "group by o.company_id" + \
                ") a " + \
                "left outer join " + \
                "(select id,name,level_id,parent_id,division_id,sub_division_id from company_company where ancestor_id=" + str(
                c.id) + ") b " + \
                "on a.company_id=b.id"
        else:
            clmns = ['经销商/分销商名称', '战区', '分区', '层级', '上一级公司名称', '自主扫码箱', '自主扫码瓶',
                     '下级扫码箱', '下级扫码瓶', '合计奖励(元)']
            s = "select b.name," + \
                "coalesce((select name from company_salesdivision where id=b.division_id),'')," + \
                "coalesce((select name from company_subsaldivision where id=b.sub_division_id),'')," + \
                "(select name from company_level where id=b.level_id)," + \
                "(select name from company_company where id=b.parent_id)," + \
                "to_char(a.mx,'FM99999999990')," + \
                "to_char(a.mp,'FM99999999990')," + \
                "to_char(a.cx,'FM99999999990')," + \
                "to_char(a.cp,'FM99999999990')," + \
                "to_char(a.val,'FM99999999990.00') " + \
                "from " + \
                "(select o.company_id,sum(o.val) val,sum(o.mx) mx,sum(o.mp) mp,sum(o.cx) cx,sum(o.cp) cp from " + \
                "(SELECT company_id," + \
                "val," + \
                "case when company_id<>company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end mx," + \
                "case when company_id<>company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end mp, " + \
                "case when company_id=company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=3) end cx," + \
                "case when company_id=company_src_id then 0 else " + \
                "(select count(id) from sales_channelrebatedetails where rebate_batch_id=a.id and label_pkg=1) end cp " + \
                "FROM sales_channelrebatebatch a " + sWhere + \
                ") o " + \
                "group by o.company_id" + \
                ") a " + \
                "left outer join " + \
                "(select id,name,level_id,parent_id,division_id,sub_division_id from company_company where ancestor_id=" + str(
                c.id) + ") b " + \
                "on a.company_id=b.id"
        cur.execute(s)
        for r in cur.fetchall():
            if c.ancestor_id == 1644:
                d.append([r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                          r[10], r[11], r[12], r[13]
                          ])
            else:
                d.append([r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9]])

    else:
        clmns = []

    data = {'clmns': clmns, 'data': d, 'date_from': dt_fr, 'date_to': dt_to, 'agent_id': agent_id,
            'agent_name': agent_name}

    return render(request, 'sales/summary_agent_channelrebate.html', data)


# 2020-10-13
@login_required
def bugsell_agent_details(request, agent_id):
    data = {'e': '', 'data': []}
    u = request.user
    c = request.user.company
    data['clmns'] = [_('标签号码'), _('标签类型'), _('产品名称'), _('超出授权范围'), _('扫码地址'), _('扫码时间')]
    # 非公司级帐户不能查询窜货
    if c.level_id == 1:
        dt = datetime.datetime.now().strftime('%Y-%m-%d')
        dt_fr = request.GET.get('date_from', dt)
        dt_to = request.GET.get('date_to', dt)
        dt_max = max(dt_fr, dt_to)
        dt_min = min(dt_fr, dt_to)
        dt_fr = dt_min
        dt_to = dt_max
        cur = connection.cursor()
        s = "select label_code,address,to_char(distance/1000.0,'FM999990.00'),to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
            "(select name from label.lbl_package where id=label_pkg)," + \
            "(select name from product_product where id=product_id) " + \
            "FROM sales_bugsell where agent_id=" + agent_id + " and dt between '" + dt_fr + "' and '" + dt_to + "'"
        cur.execute(s)
        for r in cur.fetchall():
            data['data'].append([r[0], r[4], r[5], r[2], r[1], r[3]])
    return render(request, 'sales/bugsell_agent_details.html', data)


@login_required
def fakelabel_agent_details(request, agent_id):
    data = {'e': '', 'data': []}
    u = request.user
    c = request.user.company
    data['clmns'] = [_('标签号码'), _('标签类型'), _('产品名称'), _('扫码地址'), _('扫码时间')]
    # 非公司级帐户不能查询窜货
    if c.level_id == 1:
        dt = datetime.datetime.now().strftime('%Y-%m-%d')
        dt_fr = request.GET.get('date_from', dt)
        dt_to = request.GET.get('date_to', dt)
        dt_max = max(dt_fr, dt_to)
        dt_min = min(dt_fr, dt_to)
        dt_fr = dt_min
        dt_to = dt_max
        cur = connection.cursor()
        s = "select label_code,address,'',to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
            "(select name from label.lbl_package where id=label_pkg)," + \
            "(select name from product_product where id=product_id) " + \
            "FROM sales_bugsell where agent_id=" + agent_id + " and dt between '" + dt_fr + "' and '" + dt_to + "'"
        cur.execute(s)
        for r in cur.fetchall():
            data['data'].append([r[0], r[4], r[5], r[1], r[3]])
    return render(request, 'sales/fakelabel_agent_details.html', data)


@login_required
def bugsell_agent_map(request, agent_id):
    data = {'e': '', 'data': []}
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    dt_max = max(dt_fr, dt_to)
    dt_min = min(dt_fr, dt_to)
    dt_fr = dt_min
    dt_to = dt_max
    cur = connection.cursor()
    s = "select label_code,address,to_char(distance/1000.0,'FM999990.00'),to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
        "(select name from label.lbl_package where id=label_pkg)," + \
        "(select name from product_product where id=product_id)," + \
        "lng_lat,id FROM sales_bugsell where agent_id=" + agent_id + " and dt between '" + dt_fr + "' and '" + dt_to + "'"
    cur.execute(s)
    for r in cur.fetchall():
        data['data'].append({
            'label_code': r[0],
            'address': r[1],
            'distance': r[2],
            'time': r[3],
            'package': r[4],
            'product': r[5],
            'lng': str(r[6][0]),
            'lat': str(r[6][1]),
            'id': r[7]
        })

    return render(request, 'sales/bugsell_map.html', data)


# 2022-06-11
@login_required
def fakelabel_agent_map(request, agent_id):
    data = {'e': '', 'data': []}
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    dt_max = max(dt_fr, dt_to)
    dt_min = min(dt_fr, dt_to)
    dt_fr = dt_min
    dt_to = dt_max
    cur = connection.cursor()
    s = "select label_code,address,'',to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
        "coalesce((select name from label.lbl_package where id=label_pkg),'')," + \
        "coalesce((select name from product_product where id=product_id),'')," + \
        "lng_lat,id FROM sales_fakelabel where agent_id=" + agent_id + " and dt between '" + dt_fr + "' and '" + dt_to + "'"
    cur.execute(s)
    for r in cur.fetchall():
        data['data'].append({
            'label_code': r[0],
            'address': r[1],
            'distance': r[2],
            'time': r[3],
            'package': r[4],
            'product': r[5],
            'lng': str(r[6][0]),
            'lat': str(r[6][1]),
            'id': r[7]
        })

    return render(request, 'sales/fakelabel_map.html', data)


@login_required
def rebate_details(request, batch_id):
    cur = connection.cursor()
    data = {'clmns': ['标签号码', '类别', '产品名称', '扫码奖励金额', '瓶标核减'], 'data': [], 'title': ''}

    cur.execute("select tm,code," + \
                "(select username from company_user where id=user_id)," + \
                "(select remark from inventory_voucher where id=vtype_id)," + \
                "(select name from company_company where id=company_id)," + \
                "coalesce((select name from company_company where id=company_to_id),'') " + \
                "from " + \
                "inventory_batch where id=(select batch_id from sales_channelrebatebatch where id=" + batch_id + ")")
    r = cur.fetchone()
    data['time'] = r[0].strftime('%Y-%m-%d %H:%M:%S')
    data['user'] = r[2]
    data['code'] = r[1]
    data['title'] = r[4] + ' 扫码' + r[3]
    data['customer'] = r[5]

    # 2020-11-16 sales_rebatesubstitute -> inventory_boxbottlesubstitute
    cur.execute("select label_code," + \
                "case label_pkg when 1 then '瓶标' when 3 then '箱标' when 2 then '盒标' end," + \
                "(select name from product_product where id=product_id)," + \
                "to_char(val,'999.90')," + \
                "(select coalesce(to_char(sum(val),'99999999.90'),'') from inventory_boxbottlesubstitute " + \
                "where rebate_batch_id=" + batch_id + " and label_pk_id=a.label_pk_id) " + \
                "from sales_channelrebatedetails a where rebate_batch_id=" + batch_id)
    for r in cur.fetchall():
        data['data'].append([r[0], r[1], r[2], r[3], r[4]])
    return render(request, 'sales/rebate_details.html', data)


# 2020-11-22
@login_required
def rebate_period_redeem(request):
    quarters = {
        1: ['01-01', '03-31'],
        2: ['04-01', '06-30'],
        3: ['07-01', '09-30'],
        4: ['10-01', '12-31']
    }
    today = datetime.date.today()
    month0 = today + datetime.timedelta(days=-today.day)
    q0 = (month0.month - 1) // 3 + 1
    last_month = {
        'name': str(month0.year) + '年' + str(month0.month) + '月',
        'dt_fr': str(month0.year) + '-' + str(month0.month).zfill(2) + '-01',
        'dt_to': str(month0.year) + '-' + str(month0.month).zfill(2) + '-' + str(month0.day).zfill(2),
    }
    last_quarter = {
        'name': str(month0.year) + '年第' + str(q0) + '季度',
        'dt_fr': str(month0.year) + '-' + quarters[q0][0],
        'dt_to': str(month0.year) + '-' + quarters[q0][1],
    }
    c = request.user.company
    data = {'e': ''}
    # dt=datet
    data_closing = []
    cal_periods = []
    for p in RebateClosing.objects.filter(company_id=request.user.company_id, calculated_tm__isnull=True):
        cal_periods.append([p.id, p.name])
    # clmns_closing=['会计期','开始日期','结束日期','创建时间','转帐方式','期结时间','账单笔数','应付款金额','申请提现笔数','申请提现金额','已付款笔数','已付款金额','关闭']
    clmns_closing = ['会计期', '开始日期', '结束日期', '转帐方式', '期结时间', '账单笔数', '应付款金额', '申请提现笔数',
                     '申请提现金额', '已付款笔数', '已付款金额', '关闭']
    cur = connection.cursor()
    if c.level_id == 1:  # 企业登录
        sAgt = ' and company_id=' + str(c.id)
    elif c.level_id == 2:  # 一级登录
        if c.is_expense_account:  # 营销战区登录
            sAgt = ' and (select division_id from company_company where id=agent_id)=' + str(c.division_id)
        else:
            sAgt = ' and (agent_id=' + str(
                c.id) + ' or (select parent_id from company_company where id=agent_id)=' + str(c.id) + ')'
    elif c.level_id == 4:  # 二级登录
        if c.is_expense_account:  # 营销分区登录
            sAgt = ' and (select sub_division_id from company_company where id=agent_id)=' + str(c.sub_division_id)
        else:
            sAgt = ' and agent_id=' + str(c.id)
    s = "select a.name,coalesce(to_char(lv1_dt_fr,'yyyy-mm-dd'),''),coalesce(to_char(lv1_dt_to,'yyyy-mm-dd'),'')," + \
        "to_char(dt_fr,'yyyy-mm-dd'),to_char(dt_to,'yyyy-mm-dd'),to_char(tm,'yyyy-mm-dd HH24:MI')," + \
        "coalesce(to_char(a.calculated_tm,'yyyy-mm-dd HH24:MI'),'')," + \
        "coalesce(to_char(b.cnt,'999990'),''),coalesce(to_char(b.amt_prv,'99999999.90'),'')," + \
        "coalesce(to_char(b.amt_cur,'99999999.90'),''),coalesce(to_char(b.amt_tt,'99999999.90'),'')," + \
        "coalesce(to_char(c.cnt,'999999'),''),coalesce(to_char(c.amt,'99999999.90'),'')," + \
        "coalesce(to_char(d.cnt,'999999'),''),coalesce(to_char(d.amt,'99999999.90'),'')," + \
        "a.id," + \
        "case when a.closed_tm is null then '' else to_char(a.closed_tm,'yyyy-mm-dd')||(select last_name from company_user where id=a.closed_user) end," + \
        "a.terms,coalesce(to_char(b.amt_adj,'99999990.00'),'') from " + \
        "(select id,name,period,tm,payable_checked_user_id,payable_checked_tm,application_checked_user_id,application_checked_tm," + \
        "calculated_tm,closed_user,closed_tm,dt_fr,dt_to,lv1_dt_fr,lv1_dt_to,terms::json from sales_rebateclosing where company_id=" + str(
        c.ancestor_id) + ") a " + \
        "left outer join " + \
        "(SELECT rebateclosing_id,count(*) cnt,sum(amount) amt_cur,sum(coalesce(amount_adjustment,0)) amt_adj," + \
        "sum(amount_balance) amt_prv,sum(amount_topay+coalesce(amount_adjustment,0)) amt_tt  from sales_rebatepayable " + \
        "where true " + sAgt + " group by rebateclosing_id) b " + \
        "on a.id=b.rebateclosing_id " + \
        "left outer join " + \
        "(SELECT rebateclosing_id,count(*) cnt,sum(amount) amt from sales_rebateapplication " + \
        "where status_id<>5 " + sAgt + " group by rebateclosing_id) c " + \
        "on a.id=c.rebateclosing_id " + \
        "left outer join " + \
        "(SELECT rebateclosing_id,count(*) cnt,sum(amount) amt from sales_rebatepaid " + \
        "where true " + sAgt + " group by rebateclosing_id) d " + \
        "on a.id=d.rebateclosing_id order by tm"
    cur.execute(s)
    can_close = False
    if request.user.has_perm('company.sys_admin') and c.level_id == 1:
        can_close = True
    for r in cur.fetchall():
        cls = r[16]
        terms = []
        for t in r[17]:
            if t['checked']:
                terms.append(t['name'])
        if not cls and can_close:
            cls = '<input type="checkbox" id="cls-' + str(r[15]) + '"/><label for="cls-' + str(r[15]) + '">关闭</label>'
        # data_closing.append([r[0],r[1],r[2],r[3],r[4], r[5], ','.join(terms), r[6], r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14], cls])
        data_closing.append(
            [r[0], r[1], r[2], r[3], r[4], ','.join(terms), r[6], r[7], r[8], r[9], r[18], r[10], r[11], r[12], r[13],
             r[14], cls])

    periods = []
    cur.execute(
        "select id,name from sales_rebateclosing where company_id=" + str(c.ancestor_id) + " order by dt desc limit 12")
    for r in cur.fetchall():
        periods.append([r[0], r[1]])
    data['data_closing'] = data_closing
    data['clmns_closing'] = clmns_closing
    data['periods'] = periods
    data['last_period'] = {1: last_month, 2: last_quarter}

    sts = []
    for obj in RebateApplicationStatus.objects.filter(act_sn__isnull=False).order_by('act_sn'):
        sts.append([obj.id, obj.act_name])
    data['status'] = sts
    # data['clmns_payable']=['id','经销商/分销商名称','微信钱包','微信收款人实名','上级经销商名称','扫码奖励(元)','应付款金额(元)','备注']
    # data['clmns_payable']=['id','经销商/分销商名称','层级','微信钱包','银行卡','上级经销商名称','扫码奖励','上期余额','本期应付','本期已付']
    # data['clmns_payable']=['id','经销商/分销商','层级','上级经销商名称','本期奖励奖励(元)','上期余额','本期应提(元)','本期提现(元)','本期税金(元)','本期付款(元)']
    data['clmns_payable'] = ['id', '经销商/分销商', '层级', '上级经销商名称', '战区', '分区', '本期奖励奖励(元)',
                             '上期余额', '本期调整', '本期应提(元)', '本期提现(元)', '本期税金(元)', '本期付款(元)',
                             '提现结余']

    # data['clmns_application']=['id','经销商/分销商名称','所属战区','片区','申请人','申请时间','应付款金额','申请提现(元)','收款人微信','实名','当前状态','审票','放款']
    data['clmns_application'] = ['id', '经销商/分销商', '所属战区', '申请人', '本期应付', '申请提现', '税率%', '税额',
                                 '合计', '微信钱包', '银行卡', '状态', '发票', '内勤', '财务', '申请时间']
    data['clmns_paid'] = ['id', '经销商/分销商名称', '层级', '上级经销商名称', '微信付款单号', '银行转帐流水单号',
                          '转帐时间', '转帐金额(元)']

    # data['clmns_transfer']=['id','经销商/分销商','所属战区','申请人','本期奖励','提现','税率%','税额','合计','微信钱包','银行卡','状态','发票','出纳','申请时间']
    data['clmns_transfer'] = ['id', '经销商/分销商', '所属战区', '申请人', '本期应付', '申请提现', '税率%', '税额',
                              '合计', '微信钱包', '银行卡', '状态', '发票', '出纳', '申请时间', '开户行', '账号',
                              '开户人']

    # data['clmns_lv1']=['id','平台商名称','所属战区','扫码奖励金额','上期余额','应货返金额','货返']
    data['clmns_lv1'] = ['id', '平台商名称', '所属战区', '扫码奖励金额', '上期余额', '转预付总金额', '备注']

    data['cal_periods'] = cal_periods
    return render(request, 'sales/channelrebate/rebate_period_redeem.html', data)


# 2020-11-23
@login_required
def rebate_period_action(request, what):
    data = {'e': ''}
    u = request.user
    c = request.user.company
    cur = connection.cursor()

    if c.level_id == 1:  # 企业登录
        sAgt = ' and company_id=' + str(c.id)
    elif c.level_id == 2:  # 一级登录
        sAgt = ' and (select division_id from company_company where  id=agent_id)=' + str(c.division_id)
    elif c.level_id == 4:  # 二级登录
        sAgt = ' and  (select sub_division_id from company_company where  id=agent_id)=' + str(c.sub_division_id)
    # 进行期结操作
    if what == 'close':
        if c.level_id != 1:
            data['e'] = '公司层级错误'
        else:
            pid = int(request.GET.get('id', '0'))
            clss = RebateClosing.objects.filter(id=pid)
            if not clss:
                data['e'] = '会计期 id 不存在'
            else:
                cls = clss[0]
                if cls.calculated_tm:
                    data['e'] = '会计期 ' + cls.name + '已做过期结'
                else:
                    # 上期期结ID
                    cur.execute(
                        "select max(id) from sales_rebateclosing where company_id=" + str(c.id) + " and id<>" + str(
                            pid))
                    r = cur.fetchone()
                    if r:
                        prv_id = str(r[0])
                    else:
                        prv_id = '0'
                    # 2021-04-01 内参 一级商和二级商 会计期不一致
                    # 二级商
                    s = "insert into sales_rebatepayable(" + \
                        "company_id,parent_id,level_id,amount,amount_balance,amount_topay,dt,tm,agent_id,rebateclosing_id,agent_name,parent_name,log_edit" + \
                        ") select " + \
                        str(c.id) + ",c.parent_id,c.level_id,a.cur_val,a.prv_val,a.cur_val+a.prv_val,now(),now(),a.company_id," + str(
                        cls.id) + ",c.name," + \
                        "(select name from company_company where id=c.parent_id),'[]' from " + \
                        "(select z.company_id,coalesce(sum(z.cur_val),0) cur_val,coalesce(sum(z.prv_val),0) prv_val from " + \
                        "(select company_id,sum(val) cur_val,0 prv_val from sales_channelrebatebatch where ancestor_id=" + str(
                        c.id) + \
                        " and (select level_id from company_company where id=company_id)=4 " + \
                        " and (dt between  '" + cls.dt_fr.strftime('%Y-%m-%d') + "' and '" + cls.dt_to.strftime(
                        '%Y-%m-%d') + "') group by company_id " + \
                        "union all " + \
                        "select agent_id company_id,0 cur_val,coalesce(amount_balance,0)+coalesce(amount,0)-" + \
                        "coalesce((select sum(amount) from sales_rebatepaid where agent_id=p.agent_id and rebateclosing_id=" + prv_id + "),0) prv_val " + \
                        "FROM sales_rebatepayable p where rebateclosing_id=" + prv_id + " and level_id=4" + \
                        ") z group by z.company_id" + \
                        ") a " \
                        "left outer join " + \
                        "(select id,name,parent_id,level_id from company_company) c " + \
                        "on a.company_id=c.id where a.cur_val+a.prv_val<>0"
                    cur.execute(s)
                    # 一级商
                    # s="insert into sales_rebatepayable(company_id,parent_id,level_id,amount,dt,tm,agent_id,rebateclosing_id,agent_name,parent_name,amount_topay,log_edit) select "+\
                    #    str(c.id)+",c.parent_id,c.level_id,a.val,now(),now(),a.company_id,"+str(cls.id)+",c.name,"+\
                    #    "(select name from company_company where id=c.parent_id),a.val,'[]' from "+\
                    #    "(select company_id,sum(val) val from sales_channelrebatebatch where ancestor_id="+str(c.id)+\
                    #        " and (select level_id from company_company where id=company_id)=2 "+\
                    #        " and (dt between '"+cls.lv1_dt_fr.strftime('%Y-%m-%d')+"' and '"+cls.lv1_dt_to.strftime('%Y-%m-%d')+"') group by company_id) a "\
                    #    "left outer join "+\
                    #    "(select id,name,parent_id,level_id from company_company) c "+\
                    #    "on a.company_id=c.id"
                    s = "insert into sales_rebatepayable(" + \
                        "company_id,parent_id,level_id,amount,amount_balance,amount_topay,dt,tm,agent_id,rebateclosing_id,agent_name,parent_name,log_edit" + \
                        ") select " + \
                        str(c.id) + ",c.parent_id,c.level_id,a.cur_val,a.prv_val,a.cur_val+a.prv_val,now(),now(),a.company_id," + str(
                        cls.id) + ",c.name," + \
                        "(select name from company_company where id=c.parent_id),'[]' from " + \
                        "(select z.company_id,coalesce(sum(z.cur_val),0) cur_val,coalesce(sum(z.prv_val),0) prv_val from " + \
                        "(select company_id,sum(val) cur_val,0 prv_val from sales_channelrebatebatch where ancestor_id=" + str(
                        c.id) + \
                        " and (select level_id from company_company where id=company_id)=2 " + \
                        " and (dt between '" + cls.lv1_dt_fr.strftime('%Y-%m-%d') + "' and '" + cls.lv1_dt_to.strftime(
                        '%Y-%m-%d') + "') group by company_id " + \
                        "union all " + \
                        "select agent_id company_id,0 cur_val,coalesce(amount_balance,0)+coalesce(amount,0)-" + \
                        "coalesce((select sum(amount) from sales_rebatepaid where agent_id=p.agent_id and rebateclosing_id=" + prv_id + "),0) prv_val " + \
                        "FROM sales_rebatepayable p where rebateclosing_id=" + prv_id + " and level_id=2" + \
                        ") z group by z.company_id" + \
                        ") a " \
                        "left outer join " + \
                        "(select id,name,parent_id,level_id from company_company) c " + \
                        "on a.company_id=c.id where a.cur_val+a.prv_val<>0"
                    # 2021-11-19 内参3/4季度期结:1/2季度已全部转帐完成, 期结期初和调整为0 ,
                    s = "insert into sales_rebatepayable(" + \
                        "company_id,parent_id,level_id,amount,amount_balance,amount_topay,dt,tm,agent_id,rebateclosing_id,agent_name,parent_name,log_edit" + \
                        ") select " + \
                        str(c.id) + ",c.parent_id,c.level_id,a.cur_val,0 prv_val,a.cur_val,now(),now(),a.company_id," + str(
                        cls.id) + ",c.name," + \
                        "(select name from company_company where id=c.parent_id),'[]' from " + \
                        "(select z.company_id,coalesce(sum(z.cur_val),0) cur_val,0 prv_val from " + \
                        "(select company_id,sum(val) cur_val,0 prv_val from sales_channelrebatebatch where ancestor_id=" + str(
                        c.id) + \
                        " and (select level_id from company_company where id=company_id)=2 " + \
                        " and (dt between '" + cls.lv1_dt_fr.strftime('%Y-%m-%d') + "' and '" + cls.lv1_dt_to.strftime(
                        '%Y-%m-%d') + "') group by company_id " + \
                        "union all " + \
                        "select agent_id company_id,0 cur_val,coalesce(amount_balance,0)+coalesce(amount,0)-" + \
                        "coalesce((select sum(amount) from sales_rebatepaid where agent_id=p.agent_id and rebateclosing_id=" + prv_id + "),0) prv_val " + \
                        "FROM sales_rebatepayable p where rebateclosing_id=" + prv_id + " and level_id=2" + \
                        ") z group by z.company_id" + \
                        ") a " \
                        "left outer join " + \
                        "(select id,name,parent_id,level_id from company_company) c " + \
                        "on a.company_id=c.id where a.cur_val+a.prv_val<>0"
                    cur.execute(s)
                    cur.execute(
                        "select count(*),sum(amount) from sales_rebatepayable where rebateclosing_id=" + str(cls.id))
                    r = cur.fetchone()
                    cls.payable_counting = r[0]
                    cls.payable_amount = r[1]
                    cls.calculated_tm = datetime.datetime.now()
                    cls.save()
    elif what == 'list_payable':
        # clmns=['id','经销商/分销商名称','微信钱包','微信收款人实名','上级经销商名称','扫码奖励(元)','应付款金额(元)','备注']
        clmns = ['id', '经销商/分销商', '层级', '上级经销商名称', '战区', '分区', '本期奖励(元)', '上期余额',
                 '本期调整', '本期应提(元)', '本期提现(元)', '本期税金(元)', '本期付款(元)']
        d = []
        cls_id = request.GET.get('closing_id', '')
        lv_id = request.GET.get('lv_id', '')
        sLv = ''
        if lv_id:
            sLv = " and level_id=" + lv_id
        if cls_id:
            # 2021-02-18
            # 1;1644;0;"已提交申请"
            # 2;1644;1;"内勤已申核"
            # 3;1644;2;"财务已审核"
            # 4;1644;10;"申请变更"
            # 5;1644;10000;"已确认"
            s = "select a.id,a.agent_name,(select name from company_level where id=a.level_id),a.parent," + \
                "a.amt1,a.amt0,a.amt2," + \
                "p.amt,p.amt_vat,p.amt_total " + \
                "from " + \
                "(select id,agent_name,coalesce(to_char(amount,'99999999.90'),'') amt1," + \
                "case when amount_balance is null then '' else to_char(amount_balance,'99999990.00') end amt0," + \
                "coalesce(to_char(amount_topay,'99999999.90'),'') amt2," + \
                "case when level_id=2 then '' else parent_name end parent,log_edit,agent_id,level_id " + \
                "from sales_rebatepayable a where rebateclosing_id=" + str(cls_id) + sAgt + sLv + ") a " + \
                "left outer join " + \
                "(select agent_id,sum(amount) amt,sum(amount_vat) amt_vat,sum(amount_total) amt_total from sales_rebatepaid " + \
                "where rebateclosing_id=" + str(cls_id) + " group by agent_id) p " + \
                "on a.agent_id=p.agent_id"

            s = "select a.id,a.agent_name,(select name from company_level where id=a.level_id),a.parent," + \
                "a.amount::float,a.amount_balance::float,a.amount_topay::float," + \
                "p.amt::float,p.amt_vat::float,p.amt_total::float," + \
                "(coalesce(a.amount,0.0)+coalesce(amount_balance,0.0)-coalesce(p.amt,0.0))::float," + \
                "(select name from company_salesdivision where id=c.division_id)," + \
                "(select name from company_subsaldivision where id=c.sub_division_id)," + \
                "coalesce(a.amount_adjustment,0)::float from " + \
                "(select id,agent_name,amount,agent_id,amount_balance,(amount_topay+coalesce(amount_adjustment,0)) amount_topay,amount_adjustment," + \
                "case when level_id=2 then '' else parent_name end parent,log_edit,level_id " + \
                "from sales_rebatepayable a where rebateclosing_id=" + str(cls_id) + sAgt + sLv + ") a " + \
                "left outer join " + \
                "(select agent_id,sum(amount) amt,sum(amount_vat) amt_vat,sum(amount_total) amt_total from sales_rebatepaid " + \
                "where rebateclosing_id=" + str(cls_id) + " group by agent_id) p " + \
                "on a.agent_id=p.agent_id " + \
                "left outer join " + \
                "(select id,name,division_id,sub_division_id from company_company where ancestor_id=" + str(
                c.ancestor_id) + ") c " + \
                "on a.agent_id=c.id"

            cur.execute(s)
            for r in cur.fetchall():
                # li=''
                # lgs=json.loads(r[6])
                # if lgs:
                #    for l in lgs:
                #        reason=''
                #        if l['reason']:
                #            reason="<div>"+l['reason']+"</div>"
                #        li=li+'<li>时间:'+l['time']+'</li>'+\
                #            format(l['old'],'.2f')+' → '+format(l['new'],'.2f')+'  '+l['user']+ reason
                # if li:
                #    li="<span style='cursor:pointer' title='"+r[0]+"：'  data-container='#tb_payable td' "+\
                #        "data-toggle='popover' data-content='<div>"+li+"</div>' >查看修改记录</span>"
                d.append([r[0], r[1], r[2], r[3], r[11], r[12], r[4], r[5], r[13], r[6], r[7], r[8], r[9], r[10]])
        else:
            data['e'] = 'id missing'
        data['clmns'] = clmns
        data['data'] = d

    elif what == 'list_application':
        # clmns=['id','经销商/分销商名称','所属战区','申请人'       ,'应付款金额','申请提现(元)','微信钱包','银行卡','当前状态','发票','内勤审票','财务审票','出纳付款','申请时间']
        # clmns=['id','经销商/分销商名称','所属战区','申请人','类别','应付款','提现','税率%','税额','合计','微信钱包','银行卡','状态','发票','内勤','财务','出纳','申请时间']
        clmns = ['id', '经销商/分销商', '所属战区', '申请人', '本期奖励', '提现', '税率%', '税额', '合计', '微信钱包',
                 '银行卡', '状态', '发票', '内勤', '财务', '申请时间']
        d = []
        cls_id = request.GET.get('closing_id', '')
        # 2021-07-01
        cls = RebateClosing.objects.get(id=int(cls_id))
        is_closed = False
        if cls.closed_user:
            is_closed = True
        status = request.GET.get('status', '')
        method = request.GET.get('method', '')
        invoice_needed = request.GET.get('invoice_needed', '')

        sStatus = ''
        sMethod = ''
        sInvoice = ''
        if method:
            sMethod = " and payment_method=" + method
        if invoice_needed:
            sInvoice = " and invoice_needed=" + invoice_needed
        if status:
            sStatus = " and status_id=" + status
        cnt_transmit = 0
        amt_transmit = 0.0

        # 用户组别
        group_ids = []
        cur.execute("select group_id FROM company_user_groups where user_id=" + str(u.id))
        for r in cur.fetchall():
            group_ids.append(r[0])

        # if status:
        # sStatus=" and status_id not in (3,10)"

        if cls_id:
            s = "select a.agent_name,coalesce(to_char(a.amount,'99999990.00'),'')," + \
                "coalesce((select name from company_salesdivision where id=d.division_id),'')," + \
                "coalesce((select name from company_subsaldivision where id=d.sub_division_id),'')," + \
                "(select status from sales_rebateapplicationstatus where id=a.status_id)," + \
                "(select last_name from company_user where id=user_id)," + \
                "case when a.payment_method=2  then '' else " + \
                "c.wx_nickname||'<br />'||(select realname from company_wxwallet where id=a.wxwallet_id) end," + \
                "case when a.payment_method=1  then '' else bnk.bank_name||'<br />'||bnk.bank_account||bnk.payee end," + \
                "coalesce(to_char((select amount_topay+coalesce(amount_adjustment,0) from sales_rebatepayable where rebateclosing_id=" + str(
                cls_id) + " and agent_id=a.agent_id),'99999999.90'),'')," + \
                "coalesce(to_char(tm,'mm-dd HH24:MI'),''),a.status_id,a.id,a.payment_method,a.wx_transmit," + \
                "jsonb_array_length(img_invoices),case when a.invoice_needed=1 then '开票' else '不开票' end," + \
                "coalesce(to_char(a.rate_vat,'99'),''),coalesce(to_char(a.amount_vat,'9999990.00'),''),coalesce(to_char(a.amount_total,'9999990.00'),''),a.invoice_needed," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from company_applicationreviewlog where " + \
                "content_type='rebateapplication' and obj_id=a.id and status_id=2 order by tm desc limit 1),'')," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from company_applicationreviewlog where " + \
                "content_type='rebateapplication' and obj_id=a.id and status_id=10 order by tm desc limit 1),'')," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from company_applicationreviewlog where " + \
                "content_type='rebateapplication' and obj_id=a.id and status_id=6 order by tm desc limit 1),'') " + \
                "from (SELECT id,company_id,agent_name,parent_name,amount,img_invoices,dt,tm,tm_chceked,agent_id,status_id,code,user_id,invoice_needed,rate_vat,amount_vat,amount_total," + \
                "payment_method,bankinfo_id,wxwallet_id,(select wxopenid_id from company_wxwallet where id=wxwallet_id) wxopenid_id,wx_transmit " + \
                "from sales_rebateapplication where rebateclosing_id=" + str(
                cls_id) + sAgt + sStatus + sMethod + sInvoice + ") a " + \
                "left outer join " + \
                "(select id,wx_nickname,wx_headimgurl FROM company_wxopenid) c " + \
                "on a.wxopenid_id=c.id " + \
                "left outer join " + \
                "(SELECT id,bank_name,bank_account,payee FROM company_bankinfo where " + \
                "ancestor_id=" + str(c.ancestor_id) + ") bnk " + \
                "on a.bankinfo_id=bnk.id " + \
                "left outer join " + \
                "(select id,division_id,sub_division_id,rebate_payment from company_company) d " + \
                "on a.agent_id=d.id " + \
                "left outer join " + \
                "(SELECT id,act_name,status FROM sales_rebateapplicationstatus where company_id=" + str(
                u.ancestor_id) + ") s " + \
                "on a.status_id=s.id "
            cur.execute(s)
            for r in cur.fetchall():
                backoffice_check = r[20]
                finance_check = r[21]
                casher_pay = r[22]
                reject = ''
                status_id = r[10]
                inv_cnt = r[14]
                m = r[12]

                if r[19]:
                    if inv_cnt > 0:
                        invoice = '<button class="btn btn-primary btn-xs" act="review_invoice">' + str(
                            inv_cnt) + ' 张</button>'
                    else:
                        invoice = '待上传'
                else:
                    invoice = '不开票'
                    # 1;0;"待内勤审票"
                # 2;1;"待财务审票"
                # 3;2;"待付款"
                # 4;4;"被驳回"
                # 5;10;"已作废"
                # 6;100;"已转帐"
                # 8;3;"待转帐"
                # 10;5;"待付款"
                # 12;6;"部分付款"

                # goup_id
                # 4;"系统管理员"
                # 12;"销售助理"
                # 18;"财务"
                # 20;"出纳"
                # 7;"内勤管理组"
                app_id = str(r[11])
                if status_id == 1:
                    # if is_closed:
                    #    if u.id==3891:
                    #        reject='<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                    # else:
                    if 4 in group_ids or 12 in group_ids:
                        reject = '<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                    # if (inv_cnt>0 and 12 in group_ids) or r[19]==0:
                    if 12 in group_ids:
                        backoffice_check = '<input type="checkbox" class="backoffice_check" id="cb-backoffice-' + app_id + '"/><label for="cb-backoffice-' + app_id + '">通过</label>'
                elif status_id == 2:
                    # if not is_closed:
                    if 4 in group_ids or 18 in group_ids:
                        reject = '<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                    if 18 in group_ids:
                        finance_check = '<input type="checkbox" class="finance_check" id="cb-finance-' + app_id + '"/><label for="cb-finance-' + app_id + '">通过</label>'
                elif status_id in [3, 8, 10, 12]:
                    # if not is_closed:
                    if 4 in group_ids or 20 in group_ids:
                        reject = '<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                    if 20 in group_ids:
                        casher_pay = '<input type="checkbox" id="cb-casher-' + app_id + '" class="casher_pay" method="' + str(
                            m) + '" />' + \
                                     '<label for="cb-casher-' + app_id + '">转帐</label>'
                status = r[4]
                if status_id in [4, 5]:
                    status = '<a class="viewlog" href="/sales/channelretate/period/action/view_rebateapplog/?id=' + app_id + '">' + \
                             r[4] + '</a>'
                d.append([app_id, '<sapan class="agent">' + r[0] + '</span>', r[2], r[5], r[8],
                          '<span class="amt">' + r[1] + '</span>',
                          r[16], r[17], r[18], r[6], r[7], status + '<br/>' + reject, invoice, backoffice_check,
                          finance_check, r[9]])
        else:
            data['e'] = 'id missing'
        data['clmns'] = clmns
        data['data'] = d
        data['cnt_transmit'] = cnt_transmit
        data['amt_transmit'] = amt_transmit

        # print(amt_transmit)



    elif what == 'list_transfer':
        # clmns=['id','经销商/分销商名称','所属战区','申请人'       ,'应付款金额','申请提现(元)','微信钱包','银行卡','当前状态','发票','内勤审票','财务审票','出纳付款','申请时间']
        # clmns=['id','经销商/分销商名称','所属战区','申请人','类别','应付款','提现','税率%','税额','合计','微信钱包','银行卡','状态','发票','内勤','财务','出纳','申请时间']
        clmns = ['id', '经销商/分销商', '所属战区', '申请人', '本期应付', '申请提现', '税率%', '税额', '合计',
                 '微信钱包', '银行卡', '状态', '发票', '出纳', '申请时间', '开户行', '账号', '开户人']
        d = []
        cls_id = request.GET.get('closing_id', '')
        # 2021-07-01
        cls = RebateClosing.objects.get(id=int(cls_id))
        is_closed = False
        if cls.closed_user:
            is_closed = True
        status = request.GET.get('status', '')
        method = request.GET.get('method', '')
        invoice_needed = request.GET.get('invoice_needed', '')

        sStatus = ''
        sMethod = ''
        sInvoice = ''
        if method:
            sMethod = " and payment_method=" + method
        if invoice_needed:
            sInvoice = " and invoice_needed=" + invoice_needed

        cnt_transmit = 0
        amt_transmit = 0.0
        amt_unpaid = 0.0
        amt_paid = 0.0
        # 用户组别
        group_ids = []
        cur.execute("select group_id FROM company_user_groups where user_id=" + str(u.id))
        for r in cur.fetchall():
            group_ids.append(r[0])

        if not status:
            sStatus = " and status_id in (3,6,10,12)"
        else:
            sStatus = " and status_id in (" + status + ")"
        if cls_id:
            '''
            s="select a.agent_name,coalesce(to_char(a.amount,'99999990.00'),''),"+\
                "coalesce((select name from company_salesdivision where id=d.division_id),''),"+\
                "coalesce((select name from company_subsaldivision where id=d.sub_division_id),''),"+\
                "(select status from sales_rebateapplicationstatus where id=a.status_id),"+\
                "(select last_name from company_user where id=user_id),"+\
                "case when a.payment_method=2  then '' else "+\
                    "c.wx_nickname||'<br />'||(select realname from company_wxwallet where id=a.wxwallet_id) end,"+\
                "case when a.payment_method=1  then '' else bnk.bank_name||'<br />'||bnk.bank_account||bnk.payee end,"+\
                "coalesce(to_char((select amount_topay from sales_rebatepayable where rebateclosing_id="+str(cls_id)+" and agent_id=a.agent_id),'99999999.90'),''),"+\
                "coalesce(to_char(tm,'mm-dd HH24:MI'),''),a.status_id,a.id,a.payment_method,a.wx_transmit,"+\
                "jsonb_array_length(img_invoices),case when a.invoice_needed=1 then '开票' else '不开票' end,"+\
                "coalesce(to_char(a.rate_vat,'99'),''),coalesce(to_char(a.amount_vat,'9999990.00'),''),coalesce(to_char(a.amount_total,'9999990.00'),''),a.invoice_needed,"+\
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from company_applicationreviewlog where "+\
                    "content_type='rebateapplication' and obj_id=a.id and status_id=2 order by tm desc limit 1),''),"+\
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from company_applicationreviewlog where "+\
                    "content_type='rebateapplication' and obj_id=a.id and status_id=10 order by tm desc limit 1),''),"+\
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from company_applicationreviewlog where "+\
                    "content_type='rebateapplication' and obj_id=a.id and status_id=6 order by tm desc limit 1),''),"+\
                "(select (select last_name from company_user where id=operator_id)||'<br/>'||to_char(tm,'mm-dd HH24:MI') from sales_rebatepaylog "+\
                    "where application_id=a.id order by id desc limit 1),"+\
                "coalesce(bnk.bank_name,''),coalesce(bnk.bank_account,''),coalesce(bnk.payee,''),"+\
                "wa.status_id,(select remark from company_wxwalletstatus where id=wa.status_id) from "+\
                "(SELECT id,company_id,agent_name,parent_name,amount,img_invoices,dt,tm,tm_chceked,agent_id,status_id,code,user_id,invoice_needed,rate_vat,amount_vat,amount_total,"+\
                    "payment_method,bankinfo_id,wxwallet_id,(select wxopenid_id from company_wxwallet where id=wxwallet_id) wxopenid_id,wx_transmit "+\
                    "from sales_rebateapplication where rebateclosing_id="+str(cls_id)+sAgt+sStatus+sMethod+sInvoice+\
                ") a "+\
                "left outer join "+\
                "(select id,wx_nickname,wx_headimgurl FROM company_wxopenid) c "+\
                "on a.wxopenid_id=c.id "+\
                "left outer join "+\
                "(SELECT id,bank_name,bank_account,payee FROM company_bankinfo where "+\
                    "ancestor_id="+str(c.ancestor_id)+") bnk "+\
                "on a.bankinfo_id=bnk.id "+\
                "left outer join "+\
                "(select id,division_id,sub_division_id,rebate_payment from company_company) d "+\
                "on a.agent_id=d.id "+\
                "left outer join "+\
                "(SELECT id,act_name,status FROM sales_rebateapplicationstatus where company_id="+str(u.ancestor_id)+") s "+\
                "on a.status_id=s.id "+\
                "left outer join "+\
                "(SELECT id,cellphone,realname,company_id,wxopenid_id,application_id FROM company_wxwallet) w "+\
                "on w.id=a.wxwallet_id "+\
                "left outer join "+\
                "(SELECT id, status_id,wxwallet_id FROM company_wxwalletapplication) wa "+\
                "on wa.id=w.application_id"
            '''
            s = "select a.agent_name||case when t.cnt>1 then ' ('||sn||'/'||cnt||')' else '' end," + \
                "case when sn>1 then '' else coalesce(to_char(a.amount_total,'99999990.00'),'') end," + \
                "coalesce((select name from company_salesdivision where id=d.division_id),'')," + \
                "coalesce((select name from company_subsaldivision where id=d.sub_division_id),'')," + \
                "(select status from sales_rebateapplicationstatus where id=a.status_id)," + \
                "(select last_name from company_user where id=user_id)," + \
                "case when a.payment_method=2  then '' else " + \
                "c.wx_nickname||'<br />'||(select realname from company_wxwallet where id=a.wxwallet_id) end," + \
                "case when a.payment_method=1  then '' else bnk.bank_name||'<br />'||bnk.bank_account||bnk.payee end," + \
                "case when sn>1 then '' else " + \
                "coalesce(to_char((select amount_topay from sales_rebatepayable where rebateclosing_id=" + str(
                cls_id) + " and agent_id=a.agent_id),'99999999.90'),'') end," + \
                "coalesce(to_char(a.tm,'mm-dd HH24:MI'),'')," + \
                "case when p.id>0 then 6 else a.status_id end," + \
                "t.id,a.payment_method,a.wx_transmit," + \
                "jsonb_array_length(img_invoices),case when a.invoice_needed=1 then '开票' else '不开票' end," + \
                "coalesce(to_char(a.rate_vat,'99'),''),coalesce(to_char(t.amount_vat,'9999990.00'),''),coalesce(to_char(t.amount_total,'9999990.00'),''),a.invoice_needed," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'yyyy-mm-dd HH24:MI') from company_applicationreviewlog where " + \
                "content_type='rebateapplication' and obj_id=a.id and status_id=2 order by tm desc limit 1),'')," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'yyyy-mm-dd HH24:MI') from company_applicationreviewlog where " + \
                "content_type='rebateapplication' and obj_id=a.id and status_id=10 order by tm desc limit 1),'')," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'yyyy-mm-dd HH24:MI') from company_applicationreviewlog where " + \
                "content_type='rebateapplication' and obj_id=a.id and status_id=6 order by tm desc limit 1),'')," + \
                "(select (select last_name from company_user where id=operator_id)||'<br/>'||to_char(tm,'yyyy-mm-dd HH24:MI') from sales_rebatepaylog " + \
                "where application_id=a.id order by id desc limit 1)," + \
                "coalesce(bnk.bank_name,''),coalesce(bnk.bank_account,''),coalesce(bnk.payee,'')," + \
                "wa.status_id,(select remark from company_wxwalletstatus where id=wa.status_id) from " + \
                "(SELECT id,amount,wx_transmit,remark,application_id,tm,amount_total,amount_vat,operator_id,cnt,sn " + \
                "FROM sales_rebatetransfer where rebateclosing_id=" + str(cls_id) + " and company_id=" + str(
                u.ancestor_id) + \
                ") t " + \
                "left outer join " + \
                "(SELECT id,company_id,agent_name,parent_name,amount,img_invoices,dt,tm,tm_chceked,agent_id,status_id,code,user_id,invoice_needed,rate_vat,amount_vat,amount_total," + \
                "payment_method,bankinfo_id,wxwallet_id,(select wxopenid_id from company_wxwallet where id=wxwallet_id) wxopenid_id,wx_transmit " + \
                "from sales_rebateapplication where rebateclosing_id=" + str(
                cls_id) + sAgt + sStatus + sMethod + sInvoice + \
                ") a " + \
                "on t.application_id=a.id " + \
                "left outer join " + \
                "(select id,wx_nickname,wx_headimgurl FROM company_wxopenid) c " + \
                "on a.wxopenid_id=c.id " + \
                "left outer join " + \
                "(SELECT id,bank_name,bank_account,payee FROM company_bankinfo where " + \
                "ancestor_id=" + str(c.ancestor_id) + ") bnk " + \
                "on a.bankinfo_id=bnk.id " + \
                "left outer join " + \
                "(select id,division_id,sub_division_id,rebate_payment from company_company) d " + \
                "on a.agent_id=d.id " + \
                "left outer join " + \
                "(SELECT id,act_name,status FROM sales_rebateapplicationstatus where company_id=" + str(
                u.ancestor_id) + ") s " + \
                "on a.status_id=s.id " + \
                "left outer join " + \
                "(SELECT id,cellphone,realname,company_id,wxopenid_id,application_id FROM company_wxwallet) w " + \
                "on w.id=a.wxwallet_id " + \
                "left outer join " + \
                "(SELECT id, status_id,wxwallet_id FROM company_wxwalletapplication) wa " + \
                "on wa.id=w.application_id " + \
                "left outer join " + \
                "(SELECT tm,operator_id,payment_no,rebatepaylog_id,amount_total,amount_vat,rate_vat,amount,transfer_id,id FROM sales_rebatepaid) p " + \
                "on t.id=p.transfer_id " + \
                "where a.id>0 "
            cur.execute(s)
            for r in cur.fetchall():
                backoffice_check = r[20]
                finance_check = r[21]
                casher_pay = r[22]
                reject = ''
                status_id = r[10]
                inv_cnt = r[14]
                m = r[12]

                if status_id == 6:
                    amt_paid = amt_paid + float(r[18])
                else:
                    amt_unpaid = amt_unpaid + float(r[18])
                # print(status_id,amt_paid,amt_unpaid)
                if r[19]:
                    if inv_cnt > 0:
                        invoice = '<button class="btn btn-primary btn-xs" act="review_invoice">' + str(
                            inv_cnt) + ' 张</button>'
                    else:
                        invoice = '待上传'
                else:
                    invoice = '不开票'
                wa_status = ''
                if r[27]:
                    if r[27] != 5:
                        wa_status = r[28]

                # 1;  0;  1644;"待内勤审票"
                # 2;  1;  1644;"待财务审票"
                # 10; 2;  1644;"待转帐"
                # 3;  3;  1644;"已转帐"
                # 4;  10; 1644;"被驳回"
                # 5;  20; 1644;"已作废"

                # goup_id
                # 4;"系统管理员"
                # 12;"销售助理"
                # 18;"财务"
                # 20;"出纳"
                # 7;"内勤管理组"

                # 2021-07-21: 改为实际是rebatetransfer_id
                app_id = str(r[11])
                # if status_id==1:
                #    if 4 in group_ids or 12 in group_ids:
                #        reject='<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                #    #if (inv_cnt>0 and 12 in group_ids) or r[19]==0:
                #    #    backoffice_check='<input type="checkbox" class="backoffice_check" id="cb-backoffice-'+app_id+'"/><label for="cb-backoffice-'+app_id+'">通过</label>'
                # elif status_id==2:
                #    if 4 in group_ids or 18 in group_ids:
                #        reject='<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                #    if r[19]:
                #        #if inv_cnt>0 and 18 in group_ids:
                #        #    finance_check='<input type="checkbox" class="finance_check" id="cb-finance-'+app_id+'"/><label for="cb-finance-'+app_id+'">通过</label>'
                #    else:
                #        casher_pay='<input type="checkbox" id="cb-casher-'+app_id+'" class="casher_pay" method="'+str(m)+'" />'+\
                #                '<label for="cb-casher-'+app_id+'">转帐</label>'

                # elif status_id in [3,10]:

                # if (4 in group_ids or 20 in group_ids) and status_id!=6 and not is_closed:
                if (4 in group_ids or 20 in group_ids) and status_id != 6:
                    reject = '<button class="btn btn-primary btn-xs" act="reject">驳回</button>'
                if status_id == 6:
                    casher_pay = r[23]
                else:
                    # if 20 in group_ids  and not is_closed:
                    if 20 in group_ids:
                        casher_pay = '<input type="checkbox" id="cb-casher-' + app_id + '" class="casher_pay" method="' + str(
                            m) + '" wa_status="' + wa_status + '"/>' + \
                                     '<label for="cb-casher-' + app_id + '">转帐</label>'
                        # status=r[4]
                # if status_id in [4,5]:
                # status='<a class="viewlog" href="/sales/channelretate/period/action/view_rebateapplog/?id='+app_id+'">'+r[4]+'</a>'
                status = r[4]
                d.append([app_id, '<sapan class="agent">' + r[0] + '</span>', r[2], r[5], r[8],
                          '<span class="amt">' + r[1] + '</span>',
                          r[16], r[17], r[18], r[6], r[7], status + '<br/>' + reject, invoice, casher_pay, r[9], r[24],
                          r[25], r[26]])
        else:
            data['e'] = 'id missing'
        data['clmns'] = clmns
        data['data'] = d
        data['amt_paid'] = amt_paid
        data['amt_unpaid'] = amt_unpaid



    elif what == 'list_paid':
        clmns = ['id', '经销商/分销商名称', '层级', '上级经销商名称', '微信付款单号', '银行转帐流水单号', '转帐时间',
                 '转帐金额(元)']
        d = []
        cls_id = request.GET.get('closing_id', '')

        sMethod = request.GET.get('paid_method', '')
        sLv = request.GET.get('paid_lv', '')
        if sMethod:
            sMethod = " and payment_method=" + sMethod
        if sLv:
            sLv = " and level_id=" + sLv
        if cls_id:
            s = "select agent_name,case when a.level_id=2 then '' else parent_name end,coalesce(to_char(amount,'99999999.90'),'')," + \
                "(select name from company_level where id=a.level_id),id," + \
                "coalesce(payment_no,''),coalesce(bank_statement,'')," + \
                "case when bank_statement is null then to_char(tm,'yyyy-mm-dd HH24:MI:SS') else to_char(dt,'yyyy-mm-dd') end " + \
                "from " + \
                "sales_rebatepaid a where rebateclosing_id=" + str(cls_id) + sAgt + sMethod + sLv + \
                "order by application_id,transfer_id"
            cur.execute(s)
            for r in cur.fetchall():
                d.append([r[4], r[0], r[3], r[1], r[5], r[6], r[7], r[2]])
        else:
            data['e'] = 'id missing'
        data['clmns'] = clmns
        data['data'] = d


    elif what == 'list_lv1':
        clmns = ['id', '平台商名称', '所属战区', '扫码奖励金额', '上期余额', '转预付总金额', '备注']
        # 用户组别
        group_ids = []
        cur.execute("select group_id FROM company_user_groups where user_id=" + str(u.id))
        for r in cur.fetchall():
            group_ids.append(r[0])
        d = []
        cls_id = request.GET.get('closing_id', '')
        if cls_id:
            s = "select id,agent_name," + \
                "(select name from company_salesdivision where id=(select division_id from company_company where id=agent_id))," + \
                "coalesce(to_char(amount,'99999999.90'),'')," + \
                "coalesce(to_char(amount_balance,'99999999.90'),'')," + \
                "coalesce(to_char(amount_topay,'99999999.90'),'')," + \
                "coalesce((select (select last_name from company_user where id=user_id)||'<br/>'||to_char(tm,'yyyy-mm-dd HH24:MI:SS') " + \
                "from sales_rebatepaid where rebatepayable_id=a.id),'') " + \
                "from sales_rebatepayable a where rebateclosing_id=" + str(cls_id) + " and level_id=2 " + sAgt
            cur.execute(s)
            for r in cur.fetchall():
                act = r[6]
                act = ''
                pid = str(r[0])
                # if not act and 18 in group_ids:
                #    act='<input type="checkbox" id="cb-lv1-'+pid+'" class="lv1_pay" />'+\
                #        '<label for="cb-lv1-'+pid+'">货返</label>'

                d.append([r[0], r[1], r[2], r[3], r[4], r[5], act])
        else:
            data['e'] = 'id missing'
        data['clmns'] = clmns
        data['data'] = d

    elif what == 'review_invoice':
        u = request.user
        if request.method == 'GET':
            id = request.GET.get('id', '')
            data = {'id': id, 'images': []}
            app = None
            apps = RebateApplication.objects.filter(id=int(id))
            if apps:
                app = apps[0]
            if app:
                data['payment_method'] = app.payment_method
                data['amount'] = app.amount_total
                if app.payment_method == 1:
                    data['payee_name'] = app.wxwallet.realname
                    data['wx_nickname'] = app.wx_nickname
                    data['wx_headimgurl'] = app.wx_headimgurl
                else:
                    data['bank_name'] = app.bankinfo.bank_name
                    data['bank_account'] = app.bankinfo.bank_account
                    data['payee'] = app.bankinfo.payee
                for i in app.img_invoices:
                    data['images'].append(i)
            return render(request, 'sales/channelrebate/agent_invoices.html', data)
    elif what == 'rebateapplication_reject':
        u = request.user
        if request.method == 'GET':
            # 2021-07-21 如果是从转帐页面驳回，则传过来的是transfer_id
            from_transfer = request.GET.get('from_transfer', '0')
            id = request.GET.get('id', '')
            data = {'id': id, 'images': []}

            app = None
            if from_transfer == '1':
                t = RebateTransfer.objects.get(id=int(id))
                app = t.application
            else:
                apps = RebateApplication.objects.filter(id=int(id))
                if apps:
                    app = apps[0]
            if app:
                # 2021-04-19
                data['payee_name'] = ''
                if app.payment_method == 1:
                    if app.wxwallet:
                        data['payee_name'] = app.wxwallet.realname
                else:
                    if app.bankinfo:
                        data['payee_name'] = app.bankinfo.payee
                data['amount'] = app.amount
                data['wx_nickname'] = app.wx_nickname
                data['wx_headimgurl'] = app.wx_headimgurl
                for i in app.img_invoices:
                    data['images'].append(i)
                data['id'] = app.id
            return render(request, 'sales/channelrebate/rebateapplication_reject.html', data)
        else:
            r = json.loads(request.body)
            id = int(r['id'])
            reason = r['reason']
            action = r['action']
            status = ''
            app = None
            apps = RebateApplication.objects.filter(id=int(id))
            if apps:
                app = apps[0]
            if app:
                u = request.user
                if action == 'reject':
                    app.status_id = 4
                    status = '被驳回'
                elif action == 'scrap':
                    app.status_id = 5
                    status = '已作废'
                app.save()
                l = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebateapplication', obj_id=app.id,
                                         status_id=app.status_id, user_id=u.id, comment=reason)
                l.save()
            else:
                data['e'] = 'id missing or incorrect'
            data['status'] = status
    elif what == 'invoice':
        checked = request.POST.get('checked')
        id = request.POST.get('id')
        app = None
        apps = RebateApplication.objects.filter(id=int(id))
        if apps:
            app = apps[0]
        if app:
            if checked == 'true':
                # app.status_id=3
                # status='待放款'
                # 2021-03-02 核票后直接待转帐
                app.status_id = 8
                status = '待转帐'
            else:
                app.status_id = 2
                status = '待审票'
            app.save()
        else:
            data['e'] = 'id missing or incorrect'
        data['status'] = status
    elif what == 'transmit':
        data['status'] = '待转帐'
        checked = request.POST.get('checked')
        id = request.POST.get('id')

        t = None
        ts = Transfer.objects.filter(id=int(id))
        if ts:
            t = ts[0]
        if t:
            if checked == 'true':
                t.wx_transmit = True
            else:
                t.wx_transmit = False
            t.save()
        else:
            data['e'] = 'id missing or incorrect'

        # app=None
        # apps=RebateApplication.objects.filter(id=int(id))
        # if apps:
        #    app=apps[0]
        # if app:
        #    if checked=='true':
        #        app.wx_transmit=True
        #    else:
        #        app.wx_transmit=False
        #    app.save()
        # else:
        #    data['e']='id missing or incorrect'

    # 2021-03-28
    elif what == 'backoffice_check':
        checked = request.POST.get('checked')
        id = request.POST.get('id')
        app = None
        apps = RebateApplication.objects.filter(id=int(id))
        if apps:
            app = apps[0]
        if app:
            if checked == 'true':
                # 2021-04-15 不开票提现也要财务审核
                app.status_id = 2
                status = '财务审票'

                # if app.invoice_needed:
                #    app.status_id=2
                #    status='财务审票'
                # else:
                #    app.status_id=3
                #    status='出纳付款'
            else:
                app.status_id = 1
                status = '内勤审票'
            app.save()
            l = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebateapplication', obj_id=app.id,
                                     status_id=app.status_id, user_id=u.id)
            l.save()
        else:
            data['e'] = 'id missing or incorrect'
        data['status'] = status
    elif what == 'finance_check':
        checked = request.POST.get('checked')
        id = request.POST.get('id')
        app = None
        apps = RebateApplication.objects.filter(id=int(id))
        if apps:
            app = apps[0]
        if app:
            if checked == 'true':
                app.status_id = 10
                status = '出纳付款'
                # 2021-07-19 application->rebatetransfer
                for r in RebateTransfer.objects.filter(application_id=app.id):
                    r.delete()
                cfg = c.cfg_company
                lmt = cfg.wx_transfer_amt

                amt = float(app.amount)
                amt_vat = float(app.amount_vat)
                amt_tt = float(app.amount_total)
                t_amt = 0.0
                t_vat = 0.0
                t_tt = 0.0
                cur_amt = 0.0
                cur_vat = 0.0
                cur_tt = 0.0
                if app.agent.level_id > 2 and app.payment_method == 1 and amt_tt > lmt:
                    cnt = math.ceil(amt_tt / cfg.wx_transfer_amt)
                    for i in range(cnt):
                        if i == (cnt - 1):
                            cur_tt = amt_tt - t_tt
                            cur_amt = amt - t_amt
                            cur_vat = cur_tt - cur_amt
                        else:
                            cur_tt = lmt
                            cur_amt = round(lmt * amt / amt_tt, 2)
                            cur_vat = cur_tt - cur_amt
                        r = RebateTransfer(rebateclosing_id=app.rebateclosing_id, operator_id=u.id,
                                           application_id=app.id, company_id=u.ancestor_id,
                                           amount_total=cur_tt, amount=cur_amt, amount_vat=cur_vat, cnt=cnt, sn=(i + 1))
                        r.save()
                        t_tt = t_tt + cur_tt
                        t_amt = t_amt + cur_amt
                        t_vat = t_vat + cur_vat
                else:
                    r = RebateTransfer(rebateclosing_id=app.rebateclosing_id, operator_id=u.id, application_id=app.id,
                                       company_id=u.ancestor_id,
                                       amount_total=app.amount_total, amount=app.amount, amount_vat=app.amount_vat)
                    r.save()
            else:
                app.status_id = 2
                status = '财务审票'
            app.save()
            l = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebateapplication', obj_id=app.id,
                                     status_id=app.status_id, user_id=u.id)
            l.save()
        else:
            data['e'] = 'id missing or incorrect'
        data['status'] = status
    elif what == 'rebateapplication_bankpaid':
        u = request.user
        if request.method == 'GET':
            id = request.GET.get('id', '')
            data = {'id': id, 'images': []}
            app = None
            # apps=RebateApplication.objects.filter(id=int(id))
            # if apps:
            #    app=apps[0]

            # 2021-08-04
            ts = RebateTransfer.objects.filter(id=int(id))
            if ts:
                # a=apps[0]
                t = ts[0]
                app = t.application
            if app:
                if app.bankinfo:
                    data['bank_name'] = app.bankinfo.bank_name
                    data['bank_account'] = app.bankinfo.bank_account
                else:
                    data['bank_name'] = '未知'
                    data['bank_account'] = '未知'

                data['amount'] = app.amount
                # for i in app.img_invoices:
                #    data['images'].append(i)
            return render(request, 'sales/channelrebate/rebateapplication_bankpaid.html', data)
        else:
            r = json.loads(request.body)
            id = int(r['id'])
            dt_paid = r['dt_paid']
            bank_statement = r['bank_statement']
            status = ''
            a = None
            # apps=RebateApplication.objects.filter(id=int(id))
            ts = RebateTransfer.objects.filter(id=int(id))
            if ts:
                # a=apps[0]
                t = ts[0]
                a = t.application
            if a:
                u = request.user
                l = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebateapplication', obj_id=a.id,
                                         status_id=6, user_id=u.id)

                l.save()
                # ps=RebatePaid.objects.filter(application_id=a.id)
                ps = RebatePaid.objects.filter(transfer_id=t.id)
                if not ps:
                    p = RebatePaid(company_id=c.ancestor_id, rebateclosing_id=a.rebateclosing_id, application_id=a.id,
                                   operator_id=u.id, level_id=a.level_id,
                                   parent_name=a.parent_name, agent_id=a.agent_id, agent_name=a.agent_name,
                                   user_id=a.user_id, bank_statement=bank_statement,
                                   invoice_needed=a.invoice_needed, payment_method=a.payment_method, transfer_id=t.id)
                else:
                    p = ps[0]
                    p.dt = dt_paid
                    p.bank_statement = bank_statement
                    p.transfer_id = id
                p.amount = t.amount
                p.amount_vat = t.amount_vat
                p.amount_total = t.amount_total
                p.rebatepaylog_id = l.id
                p.save()
                # 已转帐
                if p.full_paid():
                    a.status_id = 6
                # 部分转帐
                else:
                    a.status_id = 12
                a.save()

                # 2021-07-19 如果转帐的会计期不是当前会计期，要把此笔转帐记入到当前会计期的adjustment
                cs = RebateClosing.objects.filter(company_id=u.ancestor_id, closed_tm=None).order_by('-id')
                if cs:
                    cls = cs[0]
                    if cls.id != p.rebateclosing_id:
                        rs = RebatePayable.objects.filter(rebateclosing_id=cls.id, agent_id=a.agent_id)
                        if rs:
                            r = rs[0]
                            # r.amount_adjustment=-p.amount

                            # 2021-11-03
                            r.amount_adjustment = r.amount_adjustment - p.amount

                            r.log_adjustment.append({
                                'tm_paid': p.tm.strftime('%Y-%m-%d %H:%M:%S'),
                                'amount_paid': {'total': float(p.amount_total), 'vat': float(p.amount_vat),
                                                'amount': float(p.amount)},
                                'user': {'id': u.id, 'name': u.last_name},
                                'from_period': {'id': a.rebateclosing.id, 'name': a.rebateclosing.name}
                            })
                            r.save()
            else:
                data['e'] = 'id missing or incorrect'
            data['status'] = status
    elif what == 'lv1_pay':
        u = request.user
        if request.method == 'GET':
            id = request.GET.get('id', '')
            data = {}
            app = None
            apps = RebatePayable.objects.filter(id=int(id))
            if apps:
                app = apps[0]
            if app:
                data['amount'] = app.amount
                data['amount_balance'] = app.amount_balance
                data['amount_topay'] = app.amount_topay
                data['id'] = id

                # for i in app.img_invoices:
                #    data['images'].append(i)
            return render(request, 'sales/channelrebate/lv1_pay.html', data)
        else:
            r = json.loads(request.body)
            id = int(r['id'])
            dt_paid = r['dt_paid']
            amt_paid = r['amt_paid']
            # bank_statement=r['bank_statement']
            status = ''
            a = None
            apps = RebatePayable.objects.filter(id=int(id))
            if apps:
                a = apps[0]
            if a:
                u = request.user
                l = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebatepayable', obj_id=a.id,
                                         status_id=3, user_id=u.id)
                l.save()
                ps = RebatePaid.objects.filter(rebatepayable_id=a.id)
                if not ps:
                    p = RebatePaid(company_id=c.ancestor_id, rebateclosing_id=a.rebateclosing_id, operator_id=u.id,
                                   level_id=a.level_id,
                                   agent_id=a.agent_id, agent_name=a.agent_name, amount=a.amount,
                                   amount_total=float(amt_paid), user_id=u.id,
                                   invoice_needed=0, payment_method=3, rebatepayable_id=a.id, dt=dt_paid)
                    p.save()
                else:
                    p = ps[0]
                    p.dt = dt_paid

                p.rebatepaylog_id = l.id
                p.save()
                a.status_id = 6
                status = '已转帐'
                a.save()


            else:
                data['e'] = 'id missing or incorrect'
            data['status'] = status
    elif what == 'wx_pay':
        companyCertId = 0
        # 2021-03-02 logistics.company_companycert
        sn_prefix = ''
        if c.ancestor_id == 1644:
            companyCertId = 1
            sn_prefix = 'NC'
        if c.ancestor_id == 19257:
            companyCertId = 3
            sn_prefix = 'MJH'
        result = []
        clmns = ['经销商名称', '转帐金额', '电话', '微信昵称', '收款人', '处理结果']

        data = {'cnt_paid': 0, 'amt_paid': 0.00, 'cnt_err': 0, 'amt_err': 0.00}
        # cls_id=request.POST.get('closing_id','')
        ids = request.POST.get('ids', '')
        a_ids = ids.split(',')
        if len(a_ids) == 0:
            return JsonResponse(data)
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[-1].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
            # for a in  RebateApplication.objects.filter(id__in=ids.split(',')):
        # 2021-07-19
        for t in RebateTransfer.objects.filter(id__in=ids.split(',')):
            a = t.application
            sn = sn_prefix + str(t.id).zfill(10)
            # print(companyCertId,a.wxwallet.wxopenid.wx_openid,int(t.amount_total*100),sn,ip,a.wxwallet.realname,a.rebateclosing.name+'扫码奖励')
            r = start_wx_enterprise_pay(companyCertId, a.wxwallet.wxopenid.wx_openid, int(t.amount_total * 100), sn, ip,
                                        a.wxwallet.realname, a.rebateclosing.name + '扫码奖励')
            l = RebatePaylog(company_id=c.ancestor_id, application_id=a.id, operator_id=u.id, msg=r, transfer_id=t.id)
            # print(r)
            if r['return_code'] == "SUCCESS" and r["result_code"] == 'SUCCESS':
                l.is_success = True
                data['cnt_paid'] = data['cnt_paid'] + 1
                data['amt_paid'] = data['amt_paid'] + float(a.amount_total)
                # ps=RebatePaid.objects.filter(application_id=a.id)
                ps = RebatePaid.objects.filter(transfer_id=t.id)
                if not ps:
                    p = RebatePaid(company_id=c.ancestor_id, rebateclosing_id=a.rebateclosing_id, application_id=a.id,
                                   rebatepaylog_id=l.id, operator_id=u.id, level_id=a.level_id,
                                   parent_name=a.parent_name, agent_id=a.agent_id, agent_name=a.agent_name,
                                   payment_no=sn, user_id=a.user_id, transfer_id=t.id)
                else:
                    p = ps[0]
                    p.dt = datetime.datetime.now()
                    p.tm = datetime.datetime.now()
                    p.rebatepaylog_id = l.id
                p.amount = t.amount
                p.amount_vat = t.amount_vat
                p.amount_total = t.amount_total
                p.save()

                # 已转帐
                if p.full_paid():
                    a.status_id = 6
                # 部分转帐
                else:
                    a.status_id = 12
                a.save()
                result.append([a.agent_name, str(p.amount_total), a.wxwallet.cellphone, a.wxwallet.wxopenid.wx_nickname,
                               a.wxwallet.realname, '成功'])

                # 2021-07-19 如果转帐的会计期不是当前会计期，要把此笔转帐记入到当前会计期的adjustment
                cs = RebateClosing.objects.filter(company_id=u.ancestor_id, closed_tm=None).order_by('-id')
                if cs:
                    cls = cs[0]
                    if cls.id != p.rebateclosing_id:
                        rs = RebatePayable.objects.filter(rebateclosing_id=cls.id, agent_id=a.agent_id)
                        if rs:
                            r = rs[0]
                            r.amount_adjustment = -p.amount
                            r.log_adjustment.append({
                                'tm_paid': p.tm.strftime('%Y-%m-%d %H:%M:%S'),
                                'amount_paid': {'total': float(p.amount_total), 'vat': float(p.amount_vat),
                                                'amount': float(p.amount)},
                                'user': {'id': u.id, 'name': u.last_name},
                                'from_period': {'id': a.rebateclosing.id, 'name': a.rebateclosing.name}
                            })
                            r.save()

                            # 2021-04-13
                try:
                    lg = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebateapplication', obj_id=a.id,
                                              status_id=6, user_id=u.id)
                    lg.save()
                except Exception:
                    pass
            else:
                l.is_success = False
                data['cnt_err'] = data['cnt_err'] + 1
                data['amt_err'] = data['amt_err'] + float(a.amount_total)
                result.append([a.agent_name, str(a.amount_total), a.wxwallet.cellphone, a.wxwallet.wxopenid.wx_nickname,
                               a.wxwallet.realname, '失败:' + l.msg['err_code_des']])

            l.save()

            # 2021-05-03
        data['data'] = result
        data['clmns'] = clmns
        return render(request, 'sales/channelrebate/transfer_result.html', data)
    elif what == 'cancel_paid':
        # checked=request.POST.get('checked')
        id = request.POST.get('id')
        app = None
        apps = RebateApplication.objects.filter(id=int(id))
        if apps:
            app = apps[0]
        if app:
            app.status_id = 3
            status = '出纳付款'
            app.save()
            l = ApplicationReviewLog(company_id=u.ancestor_id, content_type='rebateapplication', obj_id=app.id,
                                     status_id=app.status_id, user_id=u.id)
            l.save()
        else:
            data['e'] = 'id missing or incorrect'
        data['status'] = status

    elif what == 'view_rebateapplog':
        data = {'comment': '', 'user': '', 'time': '', 'status': ''}
        id = request.GET.get('id', '0')
        cur.execute("select to_char(tm,'yyyy-mm-dd HH24:MI:SS'),coalesce(comment,'')," + \
                    "(select last_name from company_user where id=user_id)," + \
                    "(select name from sales_rebateapplicationstatus where id=status_id) " + \
                    "from company_applicationreviewlog where content_type='rebateapplication' and obj_id=" + id + " order by id desc limit 1")
        r = cur.fetchone()
        if r:
            data['time'] = r[0]
            data['comment'] = r[1]
            data['user'] = r[2]
            data['status'] = r[3]
        return render(request, 'sales/channelrebate/view_appreviewlog.html', data)

    # 2021-05-18
    elif what == 'close_period':
        data = {'e': '', 'msg': ''}
        tm = datetime.datetime.now().strftime('%Y-%m-%d')
        # r=json.loads(request.body)
        cls_id = request.POST.get('cls_id')
        cur.execute("update sales_rebateclosing set closed_tm=now(),closed_user=" + str(u.id) + " where id=" + cls_id)
        data['msg'] = tm + u.last_name
    return JsonResponse(data)


@login_required
def saldiv_rebates_ajax(request):
    user_id = request.user.id
    product_id = request.GET.get('product_id', '')
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt = request.GET.get('date', dt)
    data = saldiv_rebates_data(user_id, dt, product_id)
    return JsonResponse(data)


def saldiv_rebates_app(request):
    k = 'fgfdvgu$#&3t@j'
    e = time_key_check(request, k)
    if e:
        return JsonResponse({'e': e})

    user_id = request.GET.get('user_id', '')
    if not user_id:
        return JsonResponse({'e': 'user_id missing'})

    product_id = request.GET.get('product_id', '')
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt = request.GET.get('date', dt)
    data = saldiv_rebates_data(user_id, dt, product_id)
    return JsonResponse(data, safe=False)


# 2020-12-08
def saldiv_rebates_details(user_id, dt, division_id, vtype_id, is_app=False, product_id=None):
    dt0 = '2020-11-01'  # 最早发货时间
    data = []
    u = User.objects.get(id=int(user_id))
    aid = str(u.company.ancestor_id)
    cur = connection.cursor()
    if product_id:
        product_ids = '(' + str(product_id) + ')'
    else:
        product_ids = "(900,1109)"
    p = "(select name from company_company where id=a.parent_id) parent,"
    if int(vtype_id) == 1:
        clmns = ['经销商', '分销商', '类型', '扫码时间', '数量(箱)', '物流码(箱码)', '数量(瓶)', '物流码(瓶码)']
        t = "'分销' agent,"
        sLv = "4 "
    elif int(vtype_id) == 2:
        clmns = ['经销商', '类型', '扫码时间', '数量(箱)', '物流码(箱码)', '数量(瓶)', '物流码(瓶码)']
        t = '(select name from company_company where id=b.company_to_id) agent,'
        sLv = "2 "
    s = "select (select name from company_salesdivision where id=" + str(division_id) + ")," + \
        p + "(select name from company_company where id=a.company_id)," + t + \
        "to_char(a.tm,'yyyy-mm-dd HH24:MI'), " + \
        "coalesce(dx.cnt,0),coalesce(dx.labels,''),coalesce(dp.cnt,0),coalesce(dp.labels,'') " + \
        "from " + \
        "(select id,batch_id,company_id,tm," + \
        "(select parent_id from  company_company where id=b1.company_id) parent_id " + \
        "from sales_channelrebatebatch b1 where ancestor_id=" + aid + " and confirmed=true " + \
        "and (select level_id from company_company where id=b1.company_id)=" + sLv + \
        "and vtype_id=" + vtype_id + " and (dt between '" + dt0 + "' and '" + dt + "') " \
                                                                                   "and (select division_id from company_company where id=b1.company_id)=" + division_id + \
        ") a " + \
        "left outer join " + \
        "(select id,company_to_id from inventory_batch) b " + \
        "on a.batch_id=b.id " + \
        "left outer join " + \
        "(select rebate_batch_id,count(*) cnt," + \
        "array_to_string(ARRAY(SELECT unnest(array_agg(label_code))),'|<br/>') labels " + \
        "from sales_channelrebatedetails where label_pkg=3 " + \
        "and product_id in " + product_ids + " group by rebate_batch_id" + \
        ") dx " + \
        "on a.id=dx.rebate_batch_id " + \
        "left outer join " + \
        "(select rebate_batch_id,count(*) cnt," + \
        "array_to_string(ARRAY(SELECT unnest(array_agg(label_code))),'|<br/>') labels " + \
        "from sales_channelrebatedetails where label_pkg=1 " + \
        "and product_id in " + product_ids + " group by rebate_batch_id" + \
        ") dp " + \
        "on a.id=dp.rebate_batch_id " + \
        "order by (select name from company_company where id=a.parent_id),a.company_id,a.tm"
    cur.execute(s)
    for r in cur.fetchall():
        if int(vtype_id) == 1:
            data.append([r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8]])
        elif int(vtype_id) == 2:
            data.append([r[2], r[3], r[4], r[5], r[6], r[7], r[8]])
    return {'clmns': clmns, 'data': data}


# 2020-12-08
@login_required
def saldiv_rebates_details_ajax(request):
    user_id = request.user.id
    division_id = request.GET.get('division_id', '')
    product_id = request.GET.get('product_id', '')
    vtype_id = request.GET.get('vtype_id', '')
    dt = request.GET.get('date', '')
    data = saldiv_rebates_details(user_id, dt, division_id, vtype_id, product_id)
    # return JsonResponse(data,safe=False)
    return render(request, 'sales/saldiv_rebates_details.html', data)


# 2020-12-09
def saldiv_rebates_details_app(request):
    k = 'fgfdvgu$#&3t@j'
    e = time_key_check(request, k)
    if e:
        return JsonResponse({'e': e})
    user_id = request.GET.get('user_id', '')
    division_id = request.GET.get('division_id', '')
    product_id = request.GET.get('product_id', '')
    vtype_id = request.GET.get('vtype_id', '')
    dt = request.GET.get('date', '')
    if not user_id or not division_id or not vtype_id or not dt:
        return JsonResponse({'e': 'user_id,division_id,vtype_id,dt required'})

    data = saldiv_rebates_details(user_id, dt, division_id, vtype_id, True, product_id)
    return JsonResponse(data, safe=False)


# 2020-12-01 此接口只用于公司内部营销相关人员使用
def saldiv_rebates_data(user_id, dt, product_id=None):
    dt0 = '2020-11-01'  # 最早发货时间
    data = {'divisions': [], 'product_id': product_id, 'date': dt}

    u = User.objects.get(id=int(user_id))
    c = u.company
    company_id = str(c.id)
    ancestor_id = str(c.ancestor_id)
    if product_id:
        product_ids = '(' + str(product_id) + ')'
    else:
        product_ids = "(900,1109)"

    cur = connection.cursor()
    provincial_saldiv = []
    extra_saldiv = []

    sWhere_cur = " where dt='" + dt + "' and ancestor_id=" + ancestor_id
    sWhere_acc = " where ancestor_id=" + ancestor_id + " and (dt between '" + dt0 + "' and '" + dt + "')"
    sWhere_stk = " where company_id=" + ancestor_id + " and vtype_id=2 and (dt between '" + dt0 + "' and '" + dt + "') " + \
                 "and product_id in " + product_ids + " "
    sWhere_saldiv = ''
    sWhere_subsaldiv = ''
    sWhere_anent = ''
    aa = []
    if int(user_id) not in [1, 6, 3891]:  # admin,nc_admin,tj_nc_admin
        s = "select saldiv_ids,subsaldiv_ids,agent_ids,group_ids from company_staffsaldiv where user_id=" + str(user_id)
        cur.execute(s)
        r = cur.fetchone()
        if r:
            # 目前，条件先只有 战区（大区）
            if r[0]:
                for d in r[0]:
                    aa.append(str(d))
                if aa:
                    sWhere_saldiv = " where a.id in (" + ",".join(aa) + ") "
        else:
            return data
    cur.execute(
        "select category from company_salesdivision where company_id=" + ancestor_id + " group by category order by category")
    rs = cur.fetchall()
    sUnion = ''
    for r0 in rs:
        cat_id = r0[0]
        if cat_id == 1:
            cat_name = '湖南市场'
        elif cat_id == 2:
            cat_name = '省外战区'
        elif cat_id == 3:
            cat_name = ''
            sUnion = " union all select 0,'其它',0,999,'' "
        d = []
        sWhere_div = " where company_id=" + ancestor_id + " and is_delete=false and rpt_shown=true and category=" + str(
            cat_id)
        s = "select a.id,a.name,coalesce(g1.boxes1,0),coalesce(g1.boxes2,0)," + \
            "coalesce(g2.boxes1,0),coalesce(g2.boxes2,0),coalesce(d.boxes,0),a.code from " + \
            "(select id,name,provincial,sn,code from company_salesdivision" + sWhere_div + sUnion + ") a " + \
            "left outer join " + \
            "(select division_id,sum(boxes1) boxes1,sum(boxes2) boxes2 " + \
            "from " + \
            "(select coalesce((select division_id from company_company where id=company_id),0) division_id," + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a1.id and label_pkg=3 and product_id in " + product_ids + ") boxes1,0 boxes2 " + \
            "from sales_channelrebatebatch a1 " + sWhere_cur + " and confirmed=true and vtype_id=2 " + \
            "and (select level_id from company_company where id=a1.company_id)=2 " + \
            "union all " + \
            "select coalesce((select division_id from company_company where id=company_id),0) division_id," + \
            "0 boxes1,(select count(*) from sales_channelrebatedetails where rebate_batch_id=a2.id and label_pkg=3 and product_id in " + product_ids + ") boxes2 " + \
            "from sales_channelrebatebatch a2 " + sWhere_cur + " and confirmed=true and vtype_id=1 " + \
            "and (select level_id from company_company where id=a2.company_id)=4" + \
            ") b " + \
            "group by division_id" + \
            ") g1 " + \
            "on a.id=g1.division_id " + \
            "left outer join " + \
            "(select division_id,sum(boxes1) boxes1,sum(boxes2) boxes2 from " + \
            "(select coalesce((select division_id from company_company where id=company_id),0) division_id," + \
            "(select count(*) from sales_channelrebatedetails where rebate_batch_id=a1.id  and label_pkg=3 and product_id in " + product_ids + ") boxes1,0 boxes2 " + \
            "from sales_channelrebatebatch a1 " + sWhere_acc + " and confirmed=true and vtype_id=2 " + \
            "and (select level_id from company_company where id=a1.company_id)=2 " + \
            "union all " + \
            "select coalesce((select division_id from company_company where id=company_id),0) division_id," + \
            "0 boxes1,(select count(*) from sales_channelrebatedetails where rebate_batch_id=a2.id and label_pkg=3 and product_id in " + product_ids + ") boxes2 " + \
            "from sales_channelrebatebatch a2  " + sWhere_acc + " and confirmed=true and vtype_id=1" + \
            "and (select level_id from company_company where id=a2.company_id)=4" + \
            ") c " + \
            "group by division_id" + \
            ") g2 " + \
            "on a.id=g2.division_id " + \
            "left outer join " + \
            "(select t.division_id division_id,sum(t.boxes) boxes from " + \
            "(select coalesce((select division_id from company_company where id=company_to_id),0) division_id," + \
            "(select count(*) from stkdetails.c" + ancestor_id + " where batch_id=a.id) boxes from inventory_batch a " + \
            sWhere_stk + \
            " and (select is_expense_account from company_company where id=company_to_id)=false" + \
            ") t " + \
            "group by t.division_id" + \
            ") d " + \
            "on a.id=d.division_id " + \
            sWhere_saldiv + \
            "order by a.code"

        cur.execute(s)
        for r in cur.fetchall():
            if r[6] == 0:
                rt = ''
            else:
                rt = "{:.2f}".format((float(r[4]) + float(r[5])) * 100.0 / float(r[6]))
            d.append({
                "division_id": r[0],
                "division_name": r[1],
                "cur_lv1_boxes": r[2],
                "cur_lv2_boxes": r[3],
                "acc_lv1_boxes": r[4],
                "acc_lv2_boxes": r[5],
                "acc_delivery_boxes": r[6],
                "rate": rt,
            })
        data['divisions'].append({'category': cat_name, 'data': d})
    cur.close()
    return data


@login_required
def saldiv_rebates(request):
    dt0 = '2020-11-01'  # 最早发货时间
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt = request.GET.get('date', dt)
    return render(request, 'sales/saldivision_rebates.html', {'dt': dt, 'dt0': dt0})


# 2020-12-21 修改/存款应付款
# @login_required
# def rebate_

def rebate_payable(closing_id, edit=0):
    cur = connection.cursor()
    s = "select id,parent_name,agent_name,amount,amount,to_char(tm,'yyyy-mm-dd HH24:MI:SS') " + \
        "from sales_rebatepayable where rebateclosing_id=" + id
    cur.execute(s)
    for r in cur.fetchall():
        pass

    # SELECT id, company_id, agent_name, parent_id, parent_name, level_id,
    #   amount, dt, tm, tm_chceked, remark, agent_id, rebateclosing_id,
    #   is_closed, log_edit, image_invoice  FROM logistics.sales_rebatepayable;
    return render(request, 'sales/rebate_payable.html', {'edit': edit, 'dt0': dt0})


'''
#2020-11-23
@login_required
def edit_period_rebate(request):
    data={'e':''}
    u=request.user
    c=u.company
    cur=connection.cursor()
    if request.method=='GET':
        clms=['ID','层级','经销商/分销商名称','应付款金额','实际付款金额']
        data=[]
        closing_id=request.GET.get('closing_id','')
        level_id=request.GET.get('level_id','')
        sLv=''
        if level_id:
            sLv=" and level_id="+level_id
        s="select id,agent_name,to_char(amount,'99999999.90'),"+\
            "(select name from company_level where id=level_id) where "+\
            "company_id="+str(c.id)+" and rebateclosing_id="+closing_id+" and amount>0"+sLv
        cur.execute(s)
        for r in cur.fetchall():
            data.append([ r[0],r[3],r[1],r[2],'' ])

'''


@csrf_exempt
def promotionCode_CardDecide(request):
    ecpid = request.GET.get('ecpid', '')
    consumer_id = request.GET.get('uid', '')
    decide_item = request.GET.get('item', '')

    if not ecpid or not consumer_id or not decide_item:
        return JsonResponse({'e': 'lack of params.'})
    else:
        card = PromotionCode.objects.filter(remark=ecpid)[0]
        if card.items and len(card.items) > 1 and card.activity_id == 18:
            # 选卡状态
            if int(decide_item) in card.items:
                card.item = decide_item
                card.uid_id = consumer_id
                card.status = 1
                card.save()
                return JsonResponse({'e': ''})
            else:
                return JsonResponse({'e': '选项不在可选范围之内'})
        else:
            return JsonResponse({'e': '不是可选状态'})


# 2020-11-24 酒鬼酒鼠年纪念酒活动
@csrf_exempt
def promotionCode_labelCheckAndGet(request):
    """
    user=3837

    {status}:
        0: 初始状态
        1: 已领取
        2: 已转赠
        3: 已消耗
    {ecpid.remark}: 加密的码
    {item}:
        1: 担当鼠
        2: 励志鼠
        3: 相知鼠
        4: 结缘鼠
        5: 守望鼠
        6: 回眸鼠
    {operation}:
        1: 领取操作
        2: 转赠操作, code转为已转赠状态
        3: 兑换操作, code转为被消耗状态
        4: 仅扫码
        5: 非正常操作
    """

    ecpid = request.GET.get('ecpid', '')
    consumer_id = request.GET.get('uid', '')
    tm = datetime.datetime.now()

    if not consumer_id:
        return JsonResponse({'e': 'no consumer_id.'})
    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})
    if not ecpid:
        return JsonResponse({'e': 'no ecpid.'})
    try:
        if ecpid.startswith('k') or ecpid.startswith('h'):
            ecpid = PromotionCode.objects.get(remark=ecpid)
        else:
            ecpid = PromotionCode.objects.get(code=ecpid)
        activity_id = ecpid.activity_id
        id = ecpid.id
        cpid = ecpid.code
        item = ecpid.item
        status = ecpid.status
        if status == 0:
            # 初始状态，领取
            if ecpid.items and len(ecpid.items) > 1 and activity_id == 18:
                if not ecpid.itemDecided:
                    return JsonResponse({'msg': '选卡', 'to_decide': 1, 'item': item, 'activity_id': activity_id})
            p = PromotionCodeStatusRecord(code=ecpid, operation=1, uid=user, tm=tm)
            p.save()
            ecpid.status = 1
            ecpid.uid = user
            ecpid.save()
            return JsonResponse({'msg': '领取成功', 'item': item, 'activity_id': activity_id})
        elif status == 1:
            # 已领取，写一条仅查询的记录，返回已被领取
            p = PromotionCodeStatusRecord(code=ecpid, operation=4, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '已被领取', 'item': item, 'activity_id': activity_id})
        elif status == 2:
            # 已转赠，领取
            p = PromotionCodeStatusRecord(code=ecpid, operation=1, uid=user, tm=tm)
            p.save()
            ecpid.status = 1
            ecpid.uid = user
            ecpid.save()
            p.save()
            return JsonResponse({'msg': '领取成功', 'item': item, 'activity_id': activity_id})
        else:
            # 已消耗，写一条仅查询的记录，返回已被消耗
            p = PromotionCodeStatusRecord(code=ecpid, operation=4, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '已被消耗', 'item': item, 'activity_id': activity_id})
    except Exception as e:
        return HttpResponse(e)


@csrf_exempt
def promotionCode_getUserData(request):
    consumer_id = request.GET.get('uid', '')
    activity_id = request.GET.get('activity', '18')
    tm = datetime.datetime.now()
    if not consumer_id:
        return JsonResponse({'e': 'no consumer id'})
    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'not correct consumer id.'})

    cur = connection.cursor()


    list = [0, 0, 0, 0, 0, 0]
    bonuslist = []
    redeemedlist = []

    if request.GET.get('all','') == '1':
        list = {
            'mouse': [0, 0, 0, 0, 0, 0],
            'ox': [0, 0, 0, 0, 0, 0],
            'tiger': [0, 0, 0, 0, 0, 0],
            'rabbit': [0, 0, 0, 0, 0 ,0]
        }
        sql = f"""
            SELECT
                activity_id,
                item,
                COUNT ( * ) 
            FROM
                sales_promotioncode 
            WHERE
                uid_id = {user.id} 
                AND status IN ( 1 ) 
                AND activity_id IN ( 18, 55, 98, 122 ) 
            GROUP BY
                activity_id,
                item 
            ORDER BY
                activity_id
        """
        cur.execute(sql)
        rs = cur.fetchall()
        for i in rs:
            item = i[1]
            cnt = i[2]
            if i[0] == 18:
                list['mouse'][item - 1] = cnt
            elif i[0] == 55:
                list['ox'][item - 1] = cnt
            else:
                list['tiger'][item - 1] = cnt
        
    else:
        sql = f"select item, count(*) from sales_promotioncode where uid_id={user.id} and status in (1) and activity_id={activity_id} group by item"
        cur.execute(sql)
        r = cur.fetchall()
        for i in r:
            list[i[0] - 1] = i[1]

    sql2 = f"select id, award_id, " \
           f"(select award_id from logistics.sales_activityawards where id=a.award_id) award_item_id, " \
           f"(select name from sales_award where id=(select award_id from sales_activityawards where id=a.award_id)), " \
           f"tm, activity_id " \
           f"from sales_consumerwinner a " \
           f"where activity_id in (18, 55, 98, 104, 122) and consumer_id={user.id} and tm_redeemed is null"
    cur.execute(sql2)
    t = cur.fetchall()

    # 中奖id, 奖项id, 奖品id, 奖品名称, 时间
    for i in t:
        bonuslist.append({
            'id': i[0],
            'award_id': i[1],
            'award_item_id': i[2],
            'award_name': i[3],
            'tm': i[4],
            'activity_id': i[5]
        })
    sql3 = f"select id, award_id, " \
           f"(select award_id from logistics.sales_activityawards where id=a.award_id) award_item_id, " \
           f"(select name from sales_award where id=(select award_id from sales_activityawards where id=a.award_id)), " \
           f"tm, tm_redeemed, activity_id " \
           f"from sales_consumerwinner a " \
           f"where activity_id in (18, 55, 98, 104, 122) and consumer_id={user.id} and tm_redeemed is not null"
    cur.execute(sql3)
    d = cur.fetchall()

    # 中奖id, 奖项id, 奖品id, 奖品名称, 时间
    for i in d:
        # print(i)
        redeemedlist.append({
            'id': i[0],
            'award_id': i[1],
            'award_item_id': i[2],
            'award_name': i[3],
            'tm': i[4],
            'tm_redeemed': i[5],
            'activity_id': i[6]
        })

    return JsonResponse({
        'cards': list,
        'bonus': bonuslist,
        'redeemed': redeemedlist
    })


@csrf_exempt
def promotionCode_share(request):
    ecpid = request.POST.get('ecpid', '')
    consumer_id = request.POST.get('uid', '')
    tm = datetime.datetime.now()

    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})
    if not ecpid:
        return JsonResponse({'e': 'no ecpid.'})

    ecpid = PromotionCode.objects.filter(remark=ecpid, uid=user).first()
    if ecpid:
        id = ecpid.id
        item = ecpid.item
        status = ecpid.status
        if status == 0:
            # 初始状态, 状态不正常，写入记录
            p = PromotionCodeStatusRecord(code=ecpid, operation=5, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '初始状态'})
        elif status == 1:
            # 已领取，转为转赠状态
            p = PromotionCodeStatusRecord(code=ecpid, operation=2, uid=user, tm=tm)
            p.save()
            ecpid.status = 2
            ecpid.uid = user
            ecpid.save()
            return JsonResponse({'msg': '转赠成功'})
        elif status == 2:
            # 已转赠，状态不正常，写入记录
            p = PromotionCodeStatusRecord(code=ecpid, operation=5, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '已转赠'})
        else:
            # 已消耗，状态不正常，写入记录
            p = PromotionCodeStatusRecord(code=ecpid, operation=5, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '已被消耗'})
    else:
        return JsonResponse({'msg': '转赠失败'})


@csrf_exempt
def promotionCode_share_json(request):
    # ecpid = request.POST.get('ecpid', '')
    # consumer_id = request.POST.get('uid', '')

    req_json = json.loads(request.body)
    ecpid = req_json['ecpid']
    consumer_id = int(req_json['uid'])
    tm = datetime.datetime.now()

    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})
    if not ecpid:
        return JsonResponse({'e': 'no ecpid.'})

    ecpid = PromotionCode.objects.filter(remark=ecpid, uid=user).first()
    if ecpid:
        id = ecpid.id
        item = ecpid.item
        status = ecpid.status
        if status == 0:
            # 初始状态, 状态不正常，写入记录
            p = PromotionCodeStatusRecord(code=ecpid, operation=5, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '初始状态'})
        elif status == 1:
            # 已领取，转为转赠状态
            p = PromotionCodeStatusRecord(code=ecpid, operation=2, uid=user, tm=tm)
            p.save()
            ecpid.status = 2
            ecpid.uid = user
            ecpid.save()
            return JsonResponse({'msg': '转赠成功'})
        elif status == 2:
            # 已转赠，状态不正常，写入记录
            p = PromotionCodeStatusRecord(code=ecpid, operation=5, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '已转赠'})
        else:
            # 已消耗，状态不正常，写入记录
            p = PromotionCodeStatusRecord(code=ecpid, operation=5, uid=user, tm=tm)
            p.save()
            return JsonResponse({'msg': '已被消耗'})
    else:
        return JsonResponse({'msg': '转赠失败'})


@csrf_exempt
def promotionCode_compose20201214(request):
    """
    {plan}
     0: 3个卡片 兑换 三等奖 258mL红坛品鉴1瓶,
     1: 5个卡片 兑换 二等奖 500mL红坛品鉴1瓶,
     2: 6个不同卡片 兑换 一等奖 五彩酒鬼酒1瓶
    """
    consumer_id = request.POST.get('uid', '')
    activity = request.POST.get('activity', 18)
    company_id = request.POST.get('company', 1)
    plan = request.POST.get('plan', '')

    tm = datetime.datetime.now()

    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})

    if not consumer_id or not plan:
        return JsonResponse({'e': 'lack of params'})

    cur = connection.cursor()

    if company_id == 1:
        plan = int(plan)
        card_consume_list = []
        sql0 = f"select item, count(*) from sales_promotioncode where uid_id={user.id} and status=1 group by item"
        cur.execute(sql0)
        r = cur.fetchall()
        list = []
        for i in r:
            list.append({
                i[0]: i[1]
            })
        # 有几种卡
        cat = len(list)

        if plan == 0:
            activityAward = 17
            qty = 1
            total = 0
            for j in list:
                j_key = sorted(j.keys())[0]
                amt = j[j_key]
                total = total + amt
            if total >= 3:
                limit = 3
                count = 0
                for k in list:
                    k_key = sorted(k.keys())[0]
                    amt = k[k_key]
                    for l in range(amt):
                        if count >= limit:
                            break
                        sql1 = f"select id, item from sales_promotioncode where uid_id={user.id} and status=1 and item={k_key} limit 1"
                        cur.execute(sql1)
                        r = cur.fetchone()
                        # 修改code的状态
                        ecpid = PromotionCode.objects.get(id=r[0])
                        ecpid.status = 3
                        ecpid.save()
                        # # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=ecpid, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': r[0], 'item': r[1]})
                        count += 1
                # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=1,
                    consumer_id=user.id,
                    activity_id=18,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()

            else:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
        if plan == 1:
            activityAward = 16
            qty = 1
            total = 0
            for j in list:
                j_key = sorted(j.keys())[0]
                amt = j[j_key]
                total = total + amt
            if total >= 5:
                limit = 5
                count = 0
                for k in list:
                    k_key = sorted(k.keys())[0]
                    amt = k[k_key]
                    for l in range(amt):
                        if count >= limit:
                            break
                        sql1 = f"select id, item from sales_promotioncode where uid_id={user.id} and status=1 and item={k_key} limit 1"
                        cur.execute(sql1)
                        r = cur.fetchone()
                        # 修改code的状态
                        ecpid = PromotionCode.objects.get(id=r[0])
                        ecpid.status = 3
                        ecpid.save()
                        # # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=ecpid, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': r[0], 'item': r[1]})
                        count += 1
                    # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=1,
                    consumer_id=user.id,
                    activity_id=18,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()

            else:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-2'})

        if plan == 2:
            activityAward = 15
            qty = 1
            if cat >= 6:
                limit = 6
                count = 0
                for j in list:
                    j_key = sorted(j.keys())[0]
                    amt = j[j_key]
                    # 修改 code 的状态为被消耗
                    sql1 = f"select id, item from sales_promotioncode where uid_id={user.id} and status=1 and item={j_key} limit 1"
                    cur.execute(sql1)
                    r = cur.fetchall()
                    for k in r:
                        # 修改code的状态
                        ecpid = PromotionCode.objects.get(id=k[0])
                        ecpid.status = 3
                        ecpid.save()
                        # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=ecpid, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': k[0], 'item': k[1]})
                    count += 1
                    if count >= limit:
                        break
                # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=1,
                    consumer_id=user.id,
                    activity_id=18,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()
            else:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-3'})
        return JsonResponse({'card_consumed': card_consume_list, 'plan': plan})
    return JsonResponse({'msg': ''})


@csrf_exempt
def promotionCode_compose(request):
    """
    {plan}
     0: 3个卡片 兑换 三等奖 258mL红坛品鉴1瓶,
     1: 5个卡片 兑换 二等奖 500mL红坛品鉴1瓶,
     2: 6个不同卡片 兑换 一等奖 五彩酒鬼酒1瓶
    """
    consumer_id = request.POST.get('uid', '')
    activity = request.POST.get('activity', 18)
    company_id = request.POST.get('company', 1)
    plan = request.POST.get('plan', '')
    cardsUse = request.POST.get('cardsUse', [])
    tm = datetime.datetime.now()

    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})

    if not consumer_id or not plan or not cardsUse:
        return JsonResponse({'e': 'lack of params'})

    cur = connection.cursor()

    if company_id == 1:
        plan = int(plan)
        card_consume_list = []
        sql0 = f"select item, count(*) from sales_promotioncode where activity={activity} and uid_id={user.id} and status in (1,2) group by item"
        cur.execute(sql0)
        r = cur.fetchall()
        list = []
        listArray = [0, 0, 0, 0, 0, 0]
        cardsUseArray = cardsUse.split(',')
        for i, v in enumerate(cardsUseArray):
            cardsUseArray[i] = int(v)
        for i in r:
            list.append({
                i[0]: i[1]
            })
            listArray[i[0] - 1] = i[1]
        # 有几种卡
        cat = len(list)

        if plan == 0:
            activityAward = 17
            qty = 1
            total = 0
            limit = 3
            cardsUseSum = 0
            for i in cardsUseArray:
                cardsUseSum += i
            if cardsUseSum != limit:
                return JsonResponse({'e': 'limit not match', 'code': '16-1'})

            sufficientCards = True
            for i, v in enumerate(listArray):
                if cardsUseArray[i] > listArray[i]:
                    sufficientCards = False
                    break
            if sufficientCards == False:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
            else:
                for j, jv in enumerate(cardsUseArray):
                    if jv == 0:
                        continue
                    sql = f"select id, item from sales_promotioncode where activity={activity} and uid_id={user.id} and status in (1,2) and item={j + 1} limit {jv}"
                    cur.execute(sql)
                    rs = cur.fetchall()
                    for r in rs:
                        # 修改code的状态
                        pc = PromotionCode.objects.get(id=r[0])
                        pc.status = 3
                        pc.save()
                        # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': r[0], 'item': r[1]})
                    # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=1,
                    consumer_id=user.id,
                    activity_id=18,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()
        if plan == 1:
            activityAward = 16
            qty = 1
            total = 0
            limit = 5
            cardsUseSum = 0
            for i in cardsUseArray:
                cardsUseSum += i
            if cardsUseSum != limit:
                return JsonResponse({'e': 'limit not match', 'code': '16-1'})
            sufficientCards = True
            for i, v in enumerate(listArray):
                if cardsUseArray[i] > listArray[i]:
                    sufficientCards = False
                    break
            if sufficientCards == False:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
            else:
                for j, jv in enumerate(cardsUseArray):
                    if jv == 0:
                        continue
                    sql = f"select id, item from sales_promotioncode activity={activity} and where uid_id={user.id} and status in (1,2) and item={j + 1} limit {jv}"
                    cur.execute(sql)
                    rs = cur.fetchall()

                    for r in rs:
                        # 修改code的状态
                        pc = PromotionCode.objects.get(id=r[0])
                        pc.status = 3
                        pc.save()
                        # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': r[0], 'item': r[1]})
                    # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=1,
                    consumer_id=user.id,
                    activity_id=18,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()
        if plan == 2:
            activityAward = 15
            qty = 1
            if cat >= 6:
                limit = 6
                count = 0
                for j in list:
                    j_key = sorted(j.keys())[0]
                    amt = j[j_key]
                    # 修改 code 的状态为被消耗
                    sql1 = f"select id, item from sales_promotioncode where activity={activity} and uid_id={user.id} and status in (1,2) and item={j_key} limit 1"
                    cur.execute(sql1)
                    r = cur.fetchall()
                    for k in r:
                        # 修改code的状态
                        ecpid = PromotionCode.objects.get(id=k[0])
                        ecpid.status = 3
                        ecpid.save()
                        # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=ecpid, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': k[0], 'item': k[1]})
                        count += 1
                    if count >= limit:
                        break
                # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=1,
                    consumer_id=user.id,
                    activity_id=18,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()
            else:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-3'})
        return JsonResponse({'card_consumed': card_consume_list, 'plan': plan})
    return JsonResponse({'msg': 'ok'})


@csrf_exempt
def promotionCode_compose_json(request):
    """
    {plan}
     0: 3个卡片 兑换 三等奖 258mL红坛品鉴1瓶,
     1: 5个卡片 兑换 二等奖 500mL红坛品鉴1瓶,
     2: 6个不同卡片 兑换 一等奖 五彩酒鬼酒1瓶
    """

    # consumer_id = request.POST.get('uid', '')
    # activity = request.POST.get('activity', 18)
    # company_id = request.POST.get('company', 1)
    # plan = request.POST.get('plan', '')
    # cardsUse = request.POST.get('cardsUse', [])

    req_json = json.loads(request.body)

    consumer_id = req_json['uid']
    activity = req_json['activity']
    company_id = 1
    plan = req_json['plan']
    cardsUse = req_json['cardsUse']

    tm = datetime.datetime.now()

    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})

    # if not consumer_id or not plan or not cardsUse or not activity or not company_id:
    #     print(consumer_id,plan,cardsUse,activity,company_id)
    #     return JsonResponse({'e': 'lack of params'})

    cur = connection.cursor()

    if company_id == 1:
        plan = int(plan)
        card_consume_list = []
        sql0 = f"select item, count(*) from sales_promotioncode where uid_id={user.id} and status in (1,2) and activity_id='{activity}' group by item"
        cur.execute(sql0)
        r = cur.fetchall()
        list = []
        listArray = [0, 0, 0, 0, 0, 0]
        cardsUseArray = cardsUse.split(',')
        for i, v in enumerate(cardsUseArray):
            cardsUseArray[i] = int(v)
        for i in r:
            list.append({
                i[0]: i[1]
            })
            listArray[i[0] - 1] = i[1]
        # 有几种卡
        cat = len(list)

        if activity == 98:

            qty = 1
            if plan == 1:
                activityAward = 419
                limit = 6
            elif plan == 2:
                activityAward = 412
                limit = 5
            elif plan == 3:
                activityAward = 411
                limit = 3
            else:
                activityAward = 410
                limit = 2

            cardsUseSum = 0
            for i in cardsUseArray:
                cardsUseSum += i
            if cardsUseSum != limit:
                return JsonResponse({'e': 'limit not match', 'code': '16-1'})

            sufficientCards = True
            for i, v in enumerate(listArray):
                if cardsUseArray[i] > listArray[i]:
                    sufficientCards = False
                    break
            if sufficientCards == False:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
            else:
                for j, jv in enumerate(cardsUseArray):
                    if jv == 0:
                        continue
                    sql = f"select id, item from sales_promotioncode where activity_id={activity} and uid_id={user.id} and status in (1,2) and item={j + 1} limit {jv}"
                    cur.execute(sql)
                    rs = cur.fetchall()
                    for r in rs:
                        # 修改code的状态
                        pc = PromotionCode.objects.get(id=r[0])
                        pc.status = 3
                        pc.save()
                        # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': r[0], 'item': r[1]})
                    # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=company_id,
                    consumer_id=user.id,
                    activity_id=activity,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()
                return JsonResponse({'card_consumed': card_consume_list, 'plan': plan})
        else:
            if plan == 0:
                if activity == 18:
                    activityAward = 17
                else:
                    activityAward = 296
                qty = 1
                total = 0
                limit = 3
                cardsUseSum = 0
                for i in cardsUseArray:
                    cardsUseSum += i
                if cardsUseSum != limit:
                    return JsonResponse({'e': 'limit not match', 'code': '16-1'})

                sufficientCards = True
                for i, v in enumerate(listArray):
                    if cardsUseArray[i] > listArray[i]:
                        sufficientCards = False
                        break
                if sufficientCards == False:
                    return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
                else:
                    for j, jv in enumerate(cardsUseArray):
                        if jv == 0:
                            continue
                        sql = f"select id, item from sales_promotioncode where uid_id={user.id} and status in (1,2) and activity_id='{activity}' and item={j + 1} limit {jv}"
                        cur.execute(sql)
                        rs = cur.fetchall()
                        for r in rs:
                            # 修改code的状态
                            pc = PromotionCode.objects.get(id=r[0])
                            pc.status = 3
                            pc.save()
                            # 写消耗的记录
                            p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                            p.save()
                            card_consume_list.append({'id': r[0], 'item': r[1]})
                        # 写 ConsumerWinner
                    c = ConsumerWinner(
                        company_id=1,
                        consumer_id=user.id,
                        activity_id=activity,
                        award_id=activityAward,
                        qty=qty
                    )
                    c.save()
            if plan == 1:
                if activity == 18:
                    activityAward = 16
                else:
                    activityAward = 295
                qty = 1
                total = 0
                limit = 5
                cardsUseSum = 0
                for i in cardsUseArray:
                    cardsUseSum += i
                if cardsUseSum != limit:
                    return JsonResponse({'e': 'limit not match', 'code': '16-1'})
                sufficientCards = True
                for i, v in enumerate(listArray):
                    if cardsUseArray[i] > listArray[i]:
                        sufficientCards = False
                        break
                if sufficientCards == False:
                    return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
                else:
                    for j, jv in enumerate(cardsUseArray):
                        if jv == 0:
                            continue
                        sql = f"select id, item from sales_promotioncode where uid_id={user.id} and status in (1,2) and activity_id='{activity}' and item={j + 1} limit {jv}"
                        cur.execute(sql)
                        rs = cur.fetchall()

                        for r in rs:
                            # 修改code的状态
                            pc = PromotionCode.objects.get(id=r[0])
                            pc.status = 3
                            pc.save()
                            # 写消耗的记录
                            p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                            p.save()
                            card_consume_list.append({'id': r[0], 'item': r[1]})
                        # 写 ConsumerWinner
                    c = ConsumerWinner(
                        company_id=1,
                        consumer_id=user.id,
                        activity_id=activity,
                        award_id=activityAward,
                        qty=qty
                    )
                    c.save()
            if plan == 2:
                if activity == 18:
                    activityAward = 15
                else:
                    activityAward = 294
                qty = 1
                if cat >= 6:
                    limit = 6
                    count = 0
                    for j in list:
                        j_key = sorted(j.keys())[0]
                        amt = j[j_key]
                        # 修改 code 的状态为被消耗
                        sql1 = f"select id, item from sales_promotioncode where uid_id={user.id} and status in (1,2) and activity_id='{activity}' and item={j_key} limit 1"
                        cur.execute(sql1)
                        r = cur.fetchall()
                        for k in r:
                            # 修改code的状态
                            ecpid = PromotionCode.objects.get(id=k[0])
                            ecpid.status = 3
                            ecpid.save()
                            # 写消耗的记录
                            p = PromotionCodeStatusRecord(code=ecpid, operation=3, uid=user, tm=tm)
                            p.save()
                            card_consume_list.append({'id': k[0], 'item': k[1]})
                            count += 1
                        if count >= limit:
                            break
                    # 写 ConsumerWinner
                    c = ConsumerWinner(
                        company_id=1,
                        consumer_id=user.id,
                        activity_id=activity,
                        award_id=activityAward,
                        qty=qty
                    )
                    c.save()
                else:
                    return JsonResponse({'e': 'insufficient cards', 'code': '15-3'})
            return JsonResponse({'card_consumed': card_consume_list, 'plan': plan})
    return JsonResponse({'msg': 'ok'})


@csrf_exempt
def promotionCode_compose_json_jg(request):
    """
    {plan}
     0: 馥郁奖,
     1: 三香奖,
    """

    req_json = json.loads(request.body)

    consumer_id = req_json['uid']
    activity = req_json['activity']
    company_id = 1
    plan = req_json['plan']
    cardsUse = req_json['cardsUse']

    tm = datetime.datetime.now()

    try:
        user = ConsumerAccount.objects.get(id=consumer_id)
    except Exception as e:
        return JsonResponse({'e': 'invalid consumer_id.'})

    cur = connection.cursor()

    if company_id == 1:
        plan = int(plan)
        if plan == 1:
            card_consume_list = []
            activityAward = 426
            qty=1
            ids = []
            for key, value in cardsUse.items():
                sql = f"select id, item from sales_promotioncode where activity_id={key} and uid_id={user.id} and status in (1,2) and item={value[0]} limit 1"
                cur.execute(sql)
                rs = cur.fetchall()
                for r in rs:
                    ids.append([r[0],r[1]])
            if len(ids) == 3:
                for r in ids:
                    # 修改code的状态
                    pc = PromotionCode.objects.get(id=r[0])
                    pc.status = 3
                    pc.save()
                        # 写消耗的记录
                    p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                    p.save()
                    card_consume_list.append({'id': r[0], 'item': r[1]})
                # 写 ConsumerWinner
                c = ConsumerWinner(
                        company_id=company_id,
                        consumer_id=user.id,
                        activity_id=activity,
                        award_id=activityAward,
                        qty=qty
                    )
                c.save()
                return JsonResponse({'card_consumed': card_consume_list, 'plan': plan})
            else:
                return JsonResponse({'msg': 'not enough'})
        elif plan == 0:
            card_consume_list = []
            sql0 = f"select item, count(*) from sales_promotioncode where uid_id={user.id} and status in (1,2) and activity_id='{activity}' group by item"
            cur.execute(sql0)
            r = cur.fetchall()
            list = []
            listArray = [0, 0, 0, 0, 0, 0]
            cardsUseArray = cardsUse.split(',')
            for i, v in enumerate(cardsUseArray):
                cardsUseArray[i] = int(v)
            for i in r:
                list.append({
                    i[0]: i[1]
                })
                listArray[i[0] - 1] = i[1]

            qty = 1
            limit = 6
            activityAward = 425

            cardsUseSum = 0
            for i in cardsUseArray:
                cardsUseSum += i
            if cardsUseSum != limit:
                return JsonResponse({'e': 'limit not match', 'code': '16-1'})

            sufficientCards = True
            for i, v in enumerate(listArray):
                if cardsUseArray[i] > listArray[i]:
                    sufficientCards = False
                    break
            if sufficientCards == False:
                return JsonResponse({'e': 'insufficient cards', 'code': '15-1'})
            else:
                for j, jv in enumerate(cardsUseArray):
                    if jv == 0:
                        continue
                    sql = f"select id, item from sales_promotioncode where activity_id={activity} and uid_id={user.id} and status in (1,2) and item={j + 1} limit {jv}"
                    cur.execute(sql)
                    rs = cur.fetchall()
                    for r in rs:
                        # 修改code的状态
                        pc = PromotionCode.objects.get(id=r[0])
                        pc.status = 3
                        pc.save()
                        # 写消耗的记录
                        p = PromotionCodeStatusRecord(code=pc, operation=3, uid=user, tm=tm)
                        p.save()
                        card_consume_list.append({'id': r[0], 'item': r[1]})
                    # 写 ConsumerWinner
                c = ConsumerWinner(
                    company_id=company_id,
                    consumer_id=user.id,
                    activity_id=104,
                    award_id=activityAward,
                    qty=qty
                )
                c.save()
                return JsonResponse({'card_consumed': card_consume_list, 'plan': plan})

    return JsonResponse({'msg': 'ok'})


@csrf_exempt
def promotionCode_redeem(request):
    consumer_id = request.POST.get('uid', '')
    winner_id = request.POST.get('winner_id', '')

    name = request.POST.get('name', '')
    province = request.POST.get('province', '')
    phone = request.POST.get('phone', '')
    city = request.POST.get('city', '')
    county = request.POST.get('county', '')
    address = request.POST.get('address', '')
    if not consumer_id or not winner_id or not name or not province or not phone or not city or not county or not address:
        return JsonResponse({'e': 'lack of params', 'code': '16'})

    activity = 18
    company_id = 1

    tm = datetime.datetime.now()

    userlist = ConsumerAccount.objects.filter(id=consumer_id)

    if not userlist.exists():
        return JsonResponse({'e': 'invalid consumer_id.'})
    p = ConsumerWinner.objects.filter(id=winner_id).first()
    if p:
        k = ConsumerRedeem.objects.filter(winner_id=winner_id)
        if k.exists():
            return JsonResponse({'e': '已兑奖'})
        else:
            p.tm_redeemed = tm
            p.save()
            redeem = ConsumerRedeem(
                winner=p,
                province=province,
                phone=phone,
                city=city,
                county=county,
                address=address,
                remark=name
            )
            redeem.save()
            return JsonResponse({'msg': 'ok'})
    else:
        return JsonResponse({'e': '不存在该奖品的合成记录', 'code': '17'})


@csrf_exempt
def promotionCode_redeem_json(request):
    req_json = json.loads(request.body)

    consumer_id = int(req_json['uid'])
    winner_id = req_json['winner_id']
    activity = int(req_json['activity'])
    company_id = int(req_json['company_id'])
    name = req_json['name']
    province = req_json['province']
    phone = req_json['phone']
    city = req_json['city']
    county = req_json['county']
    address = req_json['address']

    if not consumer_id or not winner_id or not name or not province or not phone or not city or not county or not address:
        return JsonResponse({'e': 'lack of params', 'code': '16'})

    # activity = 18
    # company_id = 1

    tm = datetime.datetime.now()

    userlist = ConsumerAccount.objects.filter(id=consumer_id)

    if not userlist.exists():
        return JsonResponse({'e': 'invalid consumer_id.'})
    p = ConsumerWinner.objects.filter(id=winner_id).first()
    if p:
        k = ConsumerRedeem.objects.filter(winner_id=winner_id)
        if k.exists():
            return JsonResponse({'e': '已兑奖'})
        else:
            p.tm_redeemed = tm
            p.save()
            redeem = ConsumerRedeem(
                winner=p,
                province=province,
                phone=phone,
                city=city,
                county=county,
                address=address,
                remark=name
            )
            redeem.save()
            return JsonResponse({'msg': 'ok'})
    else:
        return JsonResponse({'e': '不存在该奖品的合成记录', 'code': '17'})


@csrf_exempt
def promotionCode_super_prize_redeem_json(request):
    req_json = json.loads(request.body)

    consumer_id = int(req_json['uid'])
    activity = int(req_json['activity'])
    company_id = int(req_json['company_id'])
    name = req_json['name']
    province = req_json['province']
    phone = req_json['phone']
    city = req_json['city']
    county = req_json['county']
    address = req_json['address']

    if not consumer_id or not name or not province or not phone or not city or not county or not address:
        return JsonResponse({'e': 'lack of params', 'code': '16'})

    activity = 18
    company_id = 1

    tm = datetime.datetime.now()

    userlist = ConsumerAccount.objects.filter(id=consumer_id)

    if not userlist.exists():
        return JsonResponse({'e': 'invalid consumer_id.'})

    # 鼠卡一等奖
    prize_first_mouse = ConsumerWinner.objects.filter(activity_id=18, award_id=15, consumer_id=consumer_id,
                                                      tm_redeemed=None)
    # 牛卡一等奖
    prize_first_ox = ConsumerWinner.objects.filter(activity_id=55, award_id=294, consumer_id=consumer_id,
                                                   tm_redeemed=None)

    # print('prize_first_mouse', len(prize_first_mouse))
    # print('prize_first_ox', len(prize_first_ox))

    if len(prize_first_mouse) > 0 and len(prize_first_ox) > 0:
        p_mouse = prize_first_mouse[0]
        p_ox = prize_first_ox[0]
        p_mouse.tm_redeemed = tm
        p_ox.tm_redeemed = tm
        redeem_mouse = ConsumerRedeem(
            winner=p_mouse,
            province=province,
            phone=phone,
            city='',
            county='',
            address='',
            remark='兑换特等奖'
        )
        redeem_ox = ConsumerRedeem(
            winner=p_ox,
            province=province,
            phone=phone,
            city='',
            county='',
            address='',
            remark='兑换特等奖'
        )
        cw = ConsumerWinner(
            company_id=1,
            consumer_id=consumer_id,
            activity_id=18,
            award_id=305,  # 特等奖
            qty=1,
            tm_redeemed=tm
        )
        rd = ConsumerRedeem(
            winner=cw,
            province=province,
            phone=phone,
            city=city,
            county=county,
            address=address,
            remark=name
        )

        p_mouse.save()
        p_ox.save()
        redeem_mouse.save()
        redeem_ox.save()
        cw.save()
        rd.save()
        return JsonResponse({'msg': 'ok'})
    else:
        return JsonResponse({'msg': '没有可供合成的一等奖'})


@csrf_exempt
def promotionCode_getRedeemStatus(request):
    consumerwinner_id = request.GET.get('id', '')

    if not consumerwinner_id:
        return JsonResponse({'e': 'lack of parameters'})
    try:
        c = ConsumerRedeem.objects.get(winner=ConsumerWinner.objects.get(id=consumerwinner_id))
        return JsonResponse({'id': c.id, 'check': c.checked_tm,
                             'send': c.tm_send, 'delivery': c.waybill_number, 'e': ''})
    except Exception as e:
        return JsonResponse({'e': '异常'})


@csrf_exempt
def promotionCode_setRedeemStatus(request):
    consumerwinner_id = request.POST.get('id', '')
    operation = request.POST.get('operation', '')
    tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    if not consumerwinner_id or not operation:
        return JsonResponse({'e': 'lack of parameters'})

    if operation == '1':  # 通过审核
        try:
            c = ConsumerRedeem.objects.get(winner=ConsumerWinner.objects.get(id=consumerwinner_id))
            c.checked_tm = tm
            c.save()
            return JsonResponse({'msg': 'success'})
        except Exception as e:
            return JsonResponse({'e': '异常'})
    elif operation == '2':  # 发货
        n = request.POST.get('number', '')
        if not n:
            return JsonResponse({'e': 'lack of parameters'})
        try:
            c = ConsumerRedeem.objects.get(winner=ConsumerWinner.objects.get(id=consumerwinner_id))
            c.tm_send = tm
            c.waybill_number = n
            c.save()
            return JsonResponse({'msg': 'success'})
        except Exception as e:
            return JsonResponse({'e': '异常'})
    else:
        return JsonResponse({'e': '异常 3'})


@csrf_exempt
def promotionCode_setRedeemStatus_json(request):
    req_json = json.loads(request.body)
    consumerwinner_id = int(req_json['id'])
    operation = req_json['operation']

    tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    if not consumerwinner_id or not operation:
        return JsonResponse({'e': 'lack of parameters'})

    if operation == '1':  # 通过审核
        try:
            c = ConsumerRedeem.objects.get(winner=ConsumerWinner.objects.get(id=consumerwinner_id))
            c.checked_tm = tm
            c.save()
            return JsonResponse({'msg': 'success'})
        except Exception as e:
            return JsonResponse({'e': '异常'})
    elif operation == '2':  # 发货
        n = request.POST.get('number', '')
        if not n:
            return JsonResponse({'e': 'lack of parameters'})
        try:
            c = ConsumerRedeem.objects.get(winner=ConsumerWinner.objects.get(id=consumerwinner_id))
            c.tm_send = tm
            c.waybill_number = n
            c.save()
            return JsonResponse({'msg': 'success'})
        except Exception as e:
            return JsonResponse({'e': '异常'})
    else:
        return JsonResponse({'e': '异常 3'})


@csrf_exempt
def promotionCode_getShareCard(request):
    consumer_id = request.POST.get('uid', '')
    item = request.POST.get('item', '')
    if not item or not consumer_id:
        return JsonResponse({'e': 'lack of params.'})
    sql = f"select remark from sales_promotioncode where status=1 and uid_id={consumer_id} and item={item}"
    cur = connection.cursor()
    cur.execute(sql)
    r = cur.fetchone()
    if r:
        return JsonResponse({'data': r[0]})
    else:
        return JsonResponse({'data': ''})


@csrf_exempt
def promotionCode_getShareCard_json(request):
    req_json = json.loads(request.body)
    consumer_id = int(req_json['uid'])
    item = int(req_json['item'])

    if not item or not consumer_id:
        return JsonResponse({'e': 'lack of params.'})
    sql = f"select remark from sales_promotioncode where status=1 and uid_id={consumer_id} and item={item}"
    cur = connection.cursor()
    cur.execute(sql)
    r = cur.fetchone()
    if r:
        return JsonResponse({'data': r[0]})
    else:
        return JsonResponse({'data': ''})


def status_monitor(request):
    cur = connection.cursor()

    # 酒鬼庚子年纪念集卡活动: activity_id=18
    sql = "select count(*) from sales_promotioncode where company_id=1 and status!=0"
    cur.execute(sql)
    r = cur.fetchone()
    activatedNumber = r[0]
    sql2 = "select count(*) from sales_consumerwinner where activity_id=18"
    cur.execute(sql2)
    r = cur.fetchone()
    winnerNumber = r[0]
    sql3 = "select count(*) from sales_consumerwinner where activity_id=18 and tm_redeemed is not null"
    cur.execute(sql3)
    r = cur.fetchone()
    redeemedNumber = r[0]
    sql4 = "select * from sales_promotioncodestatusrecord order by id desc limit 10"
    cur.execute(sql4)
    r = cur.fetchall()
    recentOperation = []
    for i in r:
        i = list(i)
        if i[1] == 0: i[1] = "初始"
        if i[1] == 1: i[1] = "领取"
        if i[1] == 2: i[1] = "转赠"
        if i[1] == 3: i[1] = "兑换"
        if i[1] == 4: i[1] = "仅查询"
        if i[1] == 5: i[1] = "异常"
        i[2] = i[2].strftime('%m-%d %H:%M')
        recentOperation.append(i)
    sql5 = "select item,count(*) from sales_promotioncode where status!=0 group by item"
    cur.execute(sql5)
    r = cur.fetchall()
    categoryList = []
    for i in r:
        categoryList.append({
            "item": i[0],
            "itemName": "",
            "count": i[1]
        })
    for i in categoryList:
        if i['item'] == 1: i['itemName'] = "担当鼠"
        if i['item'] == 2: i['itemName'] = "励志鼠"
        if i['item'] == 3: i['itemName'] = "相知鼠"
        if i['item'] == 4: i['itemName'] = "结缘鼠"
        if i['item'] == 5: i['itemName'] = "守望鼠"
        if i['item'] == 6: i['itemName'] = "回眸鼠"
    activatedRatio = activatedNumber / 600

    sql6 = "select count(*) from sales_promotioncode where array_length(items,1)=2 and status != 0"
    cur.execute(sql6)
    problemCards = cur.fetchone()[0]

    data = {
        'activatedNumber': activatedNumber,
        'activatedRatio': round(activatedRatio, 4),
        'winnerNumber': winnerNumber,
        'redeemedNumber': redeemedNumber,
        "recentOperation": recentOperation,
        "categoryList": categoryList,
        "problemCards": problemCards
    }
    return render(request, 'sales/status_monitor.html', data)


# Jonathan
# 2020-12-15

@login_required
def bujiang_labels(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['营销活动', '手动步奖'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['标签序号', '奖品名称', '领取状态', '是否可用', '备注', '时间']
    data['show_add'] = True
    data['murl'] = '/sales/bujiang/'
    for label in BuJiang_Labels.objects.filter(company_id=request.user.company.id):
        flag = '否'
        is_get = '未领取'
        if label.is_active:
            flag = '是'
        if label.is_get:
            is_get = '已领取'
        data['data'].append([
            "<a href='/sales/bujiang/" +
            str(label.id) + "/'>" + label.label_code + "</a>",
            str(label.award.name),
            is_get,
            flag,
            label.remark,
            str(label.tm)
        ])
    return render(request, 'sales/bujiang_labels.html', data)


@login_required
def bujiang(request, id=None):
    if id:
        obj = BuJiang_Labels.objects.get(id=int(id))
    else:
        obj = BuJiang_Labels(company_id=request.user.company.id)
    if request.method == 'GET':
        form = BuJiang_Form(instance=obj, user=request.user)
    else:
        form = BuJiang_Form(request.POST, instance=obj, user=request.user)
    if form.is_valid():
        form.save()
    return render(request, 'sales/bujiang.html', {'form': form})


class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        return json.JSONEncoder.default(self, obj)
        # super(DecimalEncoder, self).default(obj)


# Jonathan
# 奖池布奖
@login_required
def lotteryseeds(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['营销活动', '奖池布奖'], 'murl': '', 'dt': True, 'add': True, 'clmns2': [], 'cnts': [],
            'clmns3': [], 'cnts2': []}
    data['clmns'] = []
    data['show_add'] = True
    data['murl'] = '/sales/lottery/'
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    data["date_from"] = dt_fr
    data["date_to"] = dt_to
    dt_to = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    f = "company_id = " + str(request.user.company.id) + " and tm>='" + dt_fr + "' and tm <='" + dt_to + "'"
    cur = connection.cursor()
    cur.execute("SELECT label_code,(SELECT name from sales_activities WHERE id = activity_id)," +
                "(SELECT name from sales_activityawards WHERE id = a.award_id)," +
                "coalesce((SELECT name from sales_activityawards WHERE id = a.award2),'')," +
                "coalesce((SELECT name from product_product WHERE id = product_id),'')," +
                "coalesce((select code from inventory_batch where id = batch_id),'')," +
                "coalesce((SELECT name from company_company WHERE id = (select company_to_id from inventory_batch where id = batch_id)),'')," +
                "(SELECT tm_redeemed from sales_consumerwinner WHERE label_code = a.label_code limit 1)," +
                "coalesce(remark,''),tm,id,is_terminal_rebate " +
                "FROM sales_lotteryseeds a where " + f)
    rs = cur.fetchall()
    for r in rs:
        is_get = '未领取'
        if r[7]:
            is_get = '已领取'
        if r[11] == True:
            is_terminal='是'
        else:
            is_terminal='否'
        check_box = '<input  class="checkchild" value="' + str(r[10]) + '" type="checkbox">'
        data['data'].append([check_box,
            r[0],
            r[1],
            r[2],
            r[3],
            r[4],
            r[5],
            r[6],
            is_get,
            r[8],
            r[9].strftime("%Y-%m-%d %H:%M:%S"),is_terminal,
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(r[10]) + ")'>删除</button>"
        ])

    data['clmns2'] = ['活动', '奖品', '数量']
    cur.execute(f"""select count(id),activity_id,award_id,
                (SELECT name from sales_activities WHERE id = activity_id),
                (SELECT name from sales_activityawards WHERE id = a.award_id) 
                from sales_lotteryseeds a where {f} group by activity_id,award_id""")
    rs = cur.fetchall()
    for r in rs:
        data['cnts'].append([
            r[3],
            r[4],
            r[0]
        ])

    data['clmns3'] = ['批次', '经销商', '金额', '数量', '合计']
    cur.execute(f"""select count(id),
                coalesce((select code from inventory_batch where id = batch_id),''),
                coalesce(( SELECT name from company_company where id = (select company_to_id from inventory_batch where id = batch_id) ),''),
                (select amount from sales_award where id = (( SELECT award_id FROM sales_activityawards WHERE ID = A.award_id )))
                from sales_lotteryseeds a where {f} group by batch_id,award_id ORDER BY batch_id""")
    rs = cur.fetchall()
    for r in rs:
        amount = 0
        heji = r[0]
        if r[3]:
            amount = r[3]
        if amount:
            heji = heji * amount

        data['cnts2'].append([
            r[1],
            r[2],
            str(amount),
            r[0],
            str(heji)
        ])

    return render(request, 'sales/lotteryseeds.html', data)


# Jonathan 2022-07-14 指定中奖人奖池
@login_required
def lotterywinnerseeds(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['营销活动', '奖品指定'], 'murl': '', 'dt': True, 'add': True, 'clmns2': [], 'cnts': []}
    data['clmns'] = ['手机号码', '活动', '奖品', '安全锁', '备注', '时间', '操作']
    data['show_add'] = True
    data['murl'] = '/sales/winner_lottery/'
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    data["date_from"] = dt_fr
    data["date_to"] = dt_to
    dt_to = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    f = "company_id = " + str(request.user.company.id) + " and tm>='" + dt_fr + "' and tm <='" + dt_to + "'"
    cur = connection.cursor()
    cur.execute("SELECT phone,(SELECT name from sales_activities WHERE id = activity_id)," +
                "(SELECT name from sales_activityawards WHERE id = a.award_id)," +
                "is_lock," +
                "coalesce(remark,''),tm,id " +
                "FROM sales_lotterywinnerseeds a where " + f)
    rs = cur.fetchall()
    for r in rs:
        is_lock = '放通中'
        if r[3]:
            is_lock = '已锁定'

        data['data'].append([
            r[0],
            r[1],
            r[2],
            is_lock,
            r[4],
            r[5].strftime("%Y-%m-%d %H:%M:%S"),
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(r[6]) + ")'>删除</button>"
        ])

    data['clmns2'] = ['活动', '奖品', '数量']
    cur.execute(f"""select count(id),activity_id,award_id,
                (SELECT name from sales_activities WHERE id = activity_id),
                (SELECT name from sales_activityawards WHERE id = a.award_id) 
                from sales_lotterywinnerseeds a where {f} group by activity_id,award_id""")
    rs = cur.fetchall()
    for r in rs:
        data['cnts'].append([
            r[3],
            r[4],
            r[0]
        ])
    return render(request, 'sales/lotterywinnerseeds.html', data)


# 布奖删除
@login_required
def lotteryseeds_delete(request, id=None):
    if id:
        obj = LotterySeeds.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()

    return redirect('/sales/lotteryseeds/')


# 布奖批量删除
@login_required
def lotteryseeds_batch_delete(request):
    if request.method == 'POST':
        otteryseeds_ids = request.POST.get('otteryseeds_ids','')
        if otteryseeds_ids:
            otteryseeds = otteryseeds_ids.split(',')
            print(otteryseeds)
        for os_id in otteryseeds:
            obj = LotterySeeds.objects.get(id=int(os_id), company_id=request.user.company.id)
            if obj:
                obj.delete()
    return redirect('/sales/lotteryseeds/')
    # return  JsonResponse(data={})


@login_required
def lotterywinnerseeds_delete(request, id=None):
    if id:
        obj = LotteryWinnerSeeds.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()

    return redirect('/sales/lotterywinnerseeds/')


# 布奖页面
@login_required
def lottery(request, id=None):
    data = {
        'activites': []
    }

    activites = Activities.objects.filter(company_id=request.user.company.id)
    if activites:
        for a in activites:
            data['activites'].append({
                'name': a.name,
                'id': a.id
            })

    return render(request, 'sales/lottery.html', data)


# 查询活动中的奖品
@tj_login_required
@csrf_exempt
def activity_awards(request):
    data = {
        'e': '',
        'awards': []
    }
    activity_id = request.GET.get('activity_id', '')
    if activity_id:
        aws = ActivityAwards.objects.filter(activity_id=int(activity_id))
        if aws:
            for aw in aws:
                data['awards'].append({
                    'id': aw.id,
                    'name': aw.name
                })
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 进行布奖
@tj_login_required
@csrf_exempt
def activity_lottery(request):
    data = {
        'e': ''
    }
    activity_id = request.POST.get('activity_id', '')
    batch_id = request.POST.get('batch_id', '')
    batch=batch_id.split(',')
    batch_id=batch_id[0:-1]
    awards_ = request.POST.get('awards', '')
    remark = request.POST.get('remark', '')
    lotteryMethod = request.POST.get('lotteryMethod', '')
    abcode = request.POST.get('abcode', 'A')
    company_id = request.user.company.id
    ancestor_id = get_ancestorId(company_id)
    is_terminal_rebate=request.POST.get('is_terminal_rebate','')

    if activity_id and batch_id and awards_:
        awards = json.loads(awards_)
        cur = connection.cursor()
        # cur.execute("select product_id,code,company_to_id from inventory_batch where id = " + batch_id + "")
        # r = cur.fetchone()
        # product_id = r[0]
        # batch_no = r[1]
        # agent_id = r[2]

        if lotteryMethod == "1":
            codesql = "code"
            if abcode == 'B':
                codesql = "(select code_b from label.lbl_abcode where code_a = code)"
            cur.execute(
                f"""
                select {codesql},id,package_id,parent_id,
                (select code from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id)),
                 (select company_to_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id)),
                 (select product_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id)),
                 (select id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id))
                 from label.labelinfo a where parent_id in (SELECT label_id from stkdetails.c{ancestor_id} WHERE batch_id in({batch_id})) and package_id=1
                """);
            rs = cur.fetchall()
            if len(rs) == 0:
                cur.execute(f"""
                    select {codesql},id,package_id,(select parent_id from label.labelinfo where a.parent_id=id),
                     (select code from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) ),
                     (select company_to_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) ),
                     (select product_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) ),
                     (select id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) )
                     from label.labelinfo a where parent_id in (
                        select id from label.labelinfo where parent_id in (
                            SELECT label_id from stkdetails.c{ancestor_id} WHERE batch_id in ({batch_id})
                        )
                    )
                    and package_id=1
                """)
                rs = cur.fetchall()
            shuffle(rs)
            i = 0
            for r in awards:
                award_id = r['award_id']
                num = r['num']
                for n in range(0, num):
                    s = LotterySeeds(
                        company_id=company_id,
                        activity_id=activity_id,
                        award_id=award_id,
                        label_code=rs[i][0],
                        label_pkg=rs[i][2],
                        label_id=rs[i][1],
                        label_pk_id=rs[i][3],
                        product_id=rs[i][6],
                        remark=remark,
                        agent_id=rs[i][5],
                        batch_no=rs[i][4],
                        batch_id=rs[i][7],
                        is_terminal_rebate=is_terminal_rebate
                    )
                    s.save()
                    i = i + 1
        elif lotteryMethod == "2":
            codesql = "code"
            if abcode == 'B':
                codesql = "(select code_b from label.lbl_abcode where code_a = code)"
            boxBottleNum = int(request.POST.get('boxBottleNum', '0'))
            # print(boxBottleNum)
            if boxBottleNum:
                cur.execute(f"""select {codesql},id,package_id,parent_id,
                (select code from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id)),
                 (select company_to_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id)),
                 (select product_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id)),
                 (select id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.parent_id))
                 from label.labelinfo a where parent_id in 
                                (SELECT label_id from stkdetails.c{str(ancestor_id)} WHERE batch_id in ({batch_id})) and package_id=1
                                ORDER BY parent_id""")
                rs = cur.fetchall()
                if len(rs)==0:
                    cur.execute(f"""
                        select {codesql},id,package_id,(select parent_id from label.labelinfo where a.parent_id=id) as parent_id, 
                        (select code from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) ),
                     (select company_to_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) ),
                     (select product_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) ),
                     (select id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=(select parent_id from label.labelinfo where  a.parent_id=id  limit 1 ) ) )
                        from label.labelinfo a where parent_id in (
                        select id from label.labelinfo where parent_id in (
                            SELECT label_id from stkdetails.c{ancestor_id} WHERE batch_id in ({batch_id})
                        )
                    )
                    and package_id=1 order by parent_id
                    """)
                    rs = cur.fetchall()
                rss = []
                for i in range(0, len(rs), boxBottleNum):
                    r = rs[i:i + boxBottleNum]
                    rss.append(r)

                for r in rss:
                    shuffle(r)
                    i = 0
                    for a in awards:
                        award_id = a['award_id']
                        num = a['num']
                        for n in range(0, num):
                            s = LotterySeeds(
                                company_id=company_id,
                                activity_id=activity_id,
                                award_id=award_id,
                                label_code=r[i][0],
                                label_pkg=r[i][2],
                                label_id=r[i][1],
                                label_pk_id=rs[i][3],
                                product_id=r[i][6],
                                remark=remark,
                                agent_id=r[i][5],
                                batch_no=r[i][4],
                                batch_id=r[i][7],
                                is_terminal_rebate=is_terminal_rebate
                            )
                            s.save()
                            i = i + 1
                # print(rss)


    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 单枚布奖
@login_required
def lottery_single(request, id=None):
    if id:
        obj = LotterySeeds.objects.get(id=int(id))
    else:
        obj = LotterySeeds(company_id=request.user.company.id)
    if request.method == 'GET':
        form = LOTTERY_SINGLE_Form(instance=obj, user=request.user)
    else:
        form = LOTTERY_SINGLE_Form(instance=obj, user=request.user)
        # form = LOTTERY_SINGLE_Form(request.POST, instance=obj,user=request.user)
        label_codes = request.POST.get('label_codes', '')
        activity = request.POST.get('activity', '')
        award = request.POST.get('award', '')
        award2 = request.POST.get('award2', '')
        remark = request.POST.get('remark', '')
        company_id = request.user.company.id
        if label_codes and activity and award:
            # o = form.save(False)
            cur = connection.cursor()

            codes = label_codes.split(',')

            for c in codes:
                label_code = c
                cur.execute(
                    "select coalesce((select code_a from  label.lbl_abcode where code_b='" + label_code + "'),'" + label_code + "')")
                rrrr = cur.fetchone()
                label_code = rrrr[0]
                cur.execute("select id,package_id from label.labelinfo where code = '" + label_code + "'")
                r = cur.fetchall()
                if r:

                    o = LotterySeeds()

                    label_id = r[0][0]
                    package_id = r[0][1]

                    o.label_pkg = package_id
                    o.label_id = label_id
                    o.label_code = label_code
                    o.company_id = company_id
                    o.activity_id = activity
                    o.award_id = award
                    if award2:
                        o.award2 = award2
                    o.remark = remark

                    d = label_sys_info(label_code, request.user.company, has_price=False)
                    product_id = d['product']['id']
                    if product_id:
                        o.product_id = product_id

                    o.save()

    return render(request, 'sales/lottery_single.html', {'form': form})


@login_required
def winner_lottery(request, id=None):
    if id:
        obj = LotteryWinnerSeeds.objects.get(id=int(id))
    else:
        obj = LotteryWinnerSeeds(company_id=request.user.company.id)
    if request.method == 'GET':
        form = Lottery_Winner_Form(instance=obj, user=request.user)
    else:
        form = Lottery_Winner_Form(request.POST, instance=obj, user=request.user)
        if form.is_valid():
            form.save()

    return render(request, 'sales/winner_lottery.html', {'form': form})


@login_required
def list_set_config(request, what):
    d = {
        'productputon': ['产品上架', 'sales', 'Productputon'],
        'member': ['会员设置', 'sales', 'Member'],
    }
    data = []
    clmns = []
    subtt = [_('会员管理'), _(d[what][0])]
    m = apps.get_model(d[what][1], d[what][2])
    cid = request.user.company.id
    edit_perm = False
    is_saved = False
    dt = False
    cur = connection.cursor()
    murl = '/list/edit/' + what + '/'
    if what == 'productputon':
        clmns = [_('产品名称'), _('产品价格'), _('产品图片'), _('首页显示'),
                 _('推荐'), _('热销'), _('备注'), _('操作')]

        s = "select name, price,photo, case is_active when true then '是' else '' end," + \
            "case is_push when true then'是' else '' end,case is_sale when true then '是' else '' end," + \
            "remark,id from sales_productputon where company_id=" + str(cid)
        cur.execute(s)
        for r in cur.fetchall():
            if edit_perm:
                name = "<a href='/product/edit/upload/" + str(r[7]) + "'>" + r[0] + "</a>"
            else:
                name = r[0]
            img = ''
            if r[2]:
                img = "<img src='/media/" + r[2] + "' style='height:30px;cursor:pointer;' tt='" + r[0] + "'></img>"
            data.append([name, r[1], img, str(r[3]), str(r[4]), str(r[5]), r[6], '下架'])
    elif what == 'member':
        clmns = [_('姓名'), _('性别'), _('生日'),
                 _('地址'), _('联系方式'), _('备注')]
        s = "select name, case  gender when 0 then '未知' when 1 then '男' when 2 then '女' end ,birthday, coalesce (address,''),phone,coalesce(remark,''),id from sales_member where company_id=" + str(
            cid) + " and grade_id = 1"
        cur.execute(s)
        for r in cur.fetchall():
            if edit_perm:
                name = "<a href='/product/edit/upload/" + str(r[6]) + "'>" + r[0] + "</a>"
            else:
                name = r[0]
            # img = ''
            # if r[2]:
            #     img = "<img src='/media/" + r[2] + "' style='height:30px;cursor:pointer;' tt='" + r[0] + "'></img>"
            rena = '<a href="/list/edit/member/' + str(r[6]) + '/" >' + str(_("修改")) + '</a>'
            data.append([name, r[1], str(r[2]), str(r[3]), str(r[4]), r[5]])
    return render(request, 'obj/list_obj.html',
                  {'clmns': clmns,
                   'data': json.dumps(data, cls=DecimalEncoder),
                   'subtt': subtt,
                   'edit_perm': edit_perm,
                   'murl': murl,
                   'show_add': False})


@login_required
def list_edit(request, what, id=None):
    d = {
        'productputon': ['产品上架', 'sales', 'Productputon'],
        'member': ['会员设置', 'sales', 'Member'],
    }
    m = apps.get_model(d[what][1], d[what][2])
    is_saved = False
    if what == 'productputon':
        if id:
            obj = m.objects.get(id=int(id))
        else:
            obj = m(company=request.user.company, user=request.user)
        if request.method == 'GET':
            form = ProductPutonForm(instance=obj)
        else:
            form = ProductPutonForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form.save()
                return redirect('/list/set/productputon/')
                is_saved = True
        return render(request, 'product/product_upload.html',
                      {'form': form, 'is_saved': is_saved, "id": id})
    elif what == 'member':
        if id:
            obj = m.objects.get(id=int(id))
        else:
            obj = m(company=request.user.company)
        if request.method == 'GET':
            form = MemberForm(instance=obj)
        else:
            form = MemberForm(request.POST, instance=obj)
            if form.is_valid():
                form.save()
                return redirect('/list/set/member/')
                is_saved = True
        return render(request, 'sales/member/member_list.html',
                      {'form': form, 'is_saved': is_saved, "id": id})


@login_required
@csrf_exempt
def sms_send(request):
    clmns = [_('姓名'), _('性别'), _('生日'),
             _('地址'), _('联系方式'), _('备注'), _('操作')]
    data = []
    lev = []
    cid = request.user.company.id
    cur = connection.cursor()
    edit_perm = False
    is_saved = False
    dt = False
    if request.method == 'GET':
        s = "select name, gender, birthday, address, phone, remark, id from sales_member where company_id=" + str(
            cid)
        cur.execute(s)
        for r in cur.fetchall():
            if edit_perm:
                name = "<a href='/product/edit/upload/" + str(r[6]) + "'>" + r[0] + "</a>"
            else:
                name = r[0]
            send = '<button class="btn-send" value="' + str(r[4]) + '" >发送短信'
            data.append([name, r[1], str(r[2]), str(r[3]), str(r[4]), r[5], send])
        cur.execute("select level,name from sales_memberlevel where company_id =" + str(cid))
        for l in cur.fetchall():
            le = {
                'name': l[1],
                'id': l[0]
            }
            lev.append(le)
        return render(request, 'sales/member/SMS_send.html',
                      {'clmns': clmns,
                       'data': json.dumps(data),
                       'edit_perm': edit_perm,
                       'lev': lev,
                       })
    else:
        r = json.loads(request.body)
        e = ''
        if not r['msg']:
            e = '请输入短信内容！'
            return JsonResponse({'data': json.dumps(data),
                                 'e': json.dumps(e, ensure_ascii=False)})
        if r['gs'] == 'one':
            mobile = r['phone']
            text = r['msg']
            if cid == 19257:
                send_sms(mobile, text, "茗酒荟")
            else:
                send_sms(mobile, text)
            tm = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            dt = datetime.date.today().strftime("%Y-%m-%d")
            cur.execute("insert into sales_sms (messages,phone,company_id,dt,tm) values " + \
                        "('" + text + "','" + mobile + "','" + str(cid) + "','" + dt + "','" + tm + "')")
            return JsonResponse({'data': json.dumps(data)})
        elif r['gs'] == 'more':
            if r['lev'] == '0':
                e = '请选择会员等级！'
                return JsonResponse({'data': json.dumps(data),
                                     'e': json.dumps(e, ensure_ascii=False)})
            s = 'SELECT phone from sales_member where member_level_id = ' + \
                '(select id from sales_memberlevel WHERE level  = ' + str(r['lev']) + \
                ' and company_id = ' + str(cid) + ') GROUP BY phone'
            cur.execute(s)
            phone = cur.fetchall()
            if not phone:
                e = '暂无该等级会员！'
                return JsonResponse({'data': json.dumps(data),
                                     'e': json.dumps(e, ensure_ascii=False)})
            for p in phone:
                if cid == 19257:
                    send_sms(p[0], r['msg'], "茗酒荟")
                else:
                    send_sms(p[0], r['msg'])
                tm = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                dt = datetime.date.today().strftime("%Y-%m-%d")
                cur.execute(
                    "insert into sales_sms (messages,phone,company_id,dt,tm) values ('" + r['msg'] + "','" + p[
                        0] + "','" +
                    str(cid) + "','" + dt + "','" + tm + "')")

            return JsonResponse({'data': json.dumps(data)})


@login_required
def member_level_conf(request):
    clmns = [_('等级'), _('名称'), _('图片'), _('积分'), _('备注'), _('编辑')]
    datas = []
    cid = request.user.company.id
    cur = connection.cursor()
    murl = '/member/level/save/'
    if request.method == 'GET':
        s = 'select  level,name,photo,integral,remark,id from sales_memberlevel where company_id=' + str(cid)
        cur.execute(s)
        for r in cur.fetchall():
            img = ''
            if r[5]:
                img = "<img src='/media/" + r[2] + "' style='height:30px;cursor:pointer;' tt='" + str(r[0]) + "'></img>"
            rena = '<a href="/member/level/details/' + str(r[5]) + '/" >' + str(_("修改")) + '</a>'
            datas.append([r[0], r[1], img, r[3], r[4], rena])
        return render(request, 'sales/member/member_level.html',
                      {'datas': json.dumps(datas),
                       'clmns': clmns,
                       "add": True,
                       'murl': murl, })


@csrf_exempt
@login_required
def member_level_details(request, id):
    data = []
    cid = request.user.company.id
    cur = connection.cursor()
    return JsonResponse(
        {'data': json.dumps(data),
         'id': id,
         })


@csrf_exempt
def member_register(request):
    data = {'e': ''}
    cur = connection.cursor()
    vid = request.POST.get('vid')
    phone = request.POST.get('phone')
    cid = request.POST.get('cid')
    cur.execute("SELECT level,id FROM sales_memberlevel where company_id = '" + str(cid) + "' ORDER BY level")
    r = cur.fetchone()
    lev_id = r[1]

    cur.execute("select phone from sales_member where company_id=" + str(cid) + " and phone ='" + str(phone) + "'")
    r = cur.fetchone()
    if r:
        data['e'] = '该账号已注册'
        return JsonResponse(data)
    else:

        s = "insert into sales_member (name,gender,birthday,province,city,phone,exps,address," \
            "company_id,member_level_id,consumer_id)(select" + \
            " a.wx_nickname,a.gender,a.birthday,a.province,a.city," + str(phone) + ",0,a.address," + str(
            cid) + "," + str(lev_id) + "," + str(vid) + " from" + \
            " (SELECT wx_nickname,gender,birthday,province,city,phone,address FROM sales_consumeraccount" + \
            " where id ='" + str(vid) + "') A)"
        cur.execute(s)
        data['e'] = '注册成功'
        return JsonResponse(data)
    cur.close()
    return JsonResponse(data)


@csrf_exempt
def member_points(request):
    data = {}
    cur = connection.cursor()
    vid = request.POST.get('vid')
    cid = request.POST.get('cid')
    points = request.POST.get('points')
    s = "select id,exps from sales_member where consumer_id = " + str(vid) + " and company_id = " + str(cid)
    cur.execute(s)
    po = cur.fetchone()
    new_points = po[1] + int(points)
    up = "update sales_member set exps = " + str(new_points) + " where company_id = " + str(cid) + " and id = " + str(
        po[0])
    cur.execute(up)
    return JsonResponse(data)


@csrf_exempt
@login_required
def member_level_save(request, id=None):
    data = []
    cid = request.user.company.id
    cur = connection.cursor()
    m = apps.get_model('sales', 'MemberLevel')
    if id:
        obj = m.objects.get(id=int(id))
    else:
        obj = m(company=request.user.company, )
    if request.method == 'GET':
        form = MemberLevelForm(instance=obj)

    else:
        form = MemberLevelForm(request.POST, request.FILES, instance=obj)
        if form.is_valid():
            form.save()
            return redirect('/obj/set/memberlevel/')
    return render(request, 'sales/member/member_level_details.html',
                  {
                      "form": form,
                  })


@csrf_exempt
def birthday_messages(request):
    data = {'e': ''}
    cur = connection.cursor()
    cid = request.POST.get('cid')
    cur.execute("select name from company_company where id = " + str(cid))
    r = cur.fetchone()
    name = r[0]
    dtnow = datetime.datetime.now().strftime("%m-%d")
    s = "select name,birthday,phone from sales_member where to_char(birthday,'MM-DD') = '" + str(dtnow) + \
        "' and company_id = " + str(cid)
    cur.execute(s)
    members = cur.fetchall()
    for mem in members:
        text = '尊敬的' + str(mem[0]) + '今天是' + str(datetime.datetime.now().strftime(" %Y-%m-%d ")) + '日，' + str(
            name) + '祝您生日快乐！'
        # send_sms(text,mem[2])

    cur.execute("select name,dt,customize from sales_holiday where to_char(dt,'MM-DD')='" + str(
        dtnow) + "' and (company_id=" + str(cid) + "or company_id is null)")
    holidays = cur.fetchall()

    cur.execute("select name,phone from sales_member where (company_id=" + str(cid) + "or company_id is null)")
    phones = cur.fetchall()

    for holiday in holidays:
        for phone in phones:
            if holiday[2]:
                text = '尊敬的' + str(phone[0]) + '今天是' + str(
                    datetime.datetime.now().strftime(" %Y-%m-%d ")) + '日，' + str(
                    name) + '祝您于我司' + str(holiday[0]) + '快乐！'
            else:
                text = '尊敬的' + str(phone[0]) + '今天是' + str(
                    datetime.datetime.now().strftime(" %Y-%m-%d ")) + '日，' + str(
                    name) + '祝您' + str(holiday[0]) + '快乐！'
            send_sms(text, phone[1])
    return JsonResponse(data)


@csrf_exempt
@login_required
def holiday_list(request):
    data = {'e': '', 'data': [], 'clmns': [], 'dt': ''}
    cid = request.user.company.id
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    if dt_fr > dt_to:
        dt_fr, dt_to = dt_to, dt_fr
    else:
        dt_fr, dt_to = dt_fr, dt_to
    data["date_from"] = dt_fr
    data["date_to"] = dt_to

    data['clmns'] = [_('节日名称'), _('日期'), _('备注')]
    cur = connection.cursor()
    s = "select name,to_char(dt,'yyyy-mm-dd'),coalesce(remark,''),id from sales_holiday where company_id = " + str(
        cid) + "or company_id is null"
    cur.execute(s)
    r = cur.fetchall()
    for i in r:
        data['data'].append([i[0], i[1], i[2]])
    # WanNianRiLi('2021')
    return render(request, 'sales/member/holiday_list.html', data)


@csrf_exempt
@login_required
def holiday_edit(request, id=None):
    date = {'e': ''}
    m = apps.get_model('sales', 'Holiday')
    if id:
        obj = m.objects.get(id=int(id))
    else:
        obj = m(company=request.user.company, )
    is_saved = False
    if request.method == 'GET':
        form = HolidayForm(instance=obj)
    elif request.method == "POST":
        form = HolidayForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            return redirect('/holiday/list/')
            is_saved = True

    return render(request, 'sales/member/birthday_messages.html',
                  {
                      "form": form,
                  })


class WanNianRiLi(object):
    def __init__(self, year):
        self.year = year
        data = self.parseHTML()
        self.exportData(data)

    def parseHTML(self):
        url = 'https://wannianrili.51240.com/ajax/'
        s = requests.session()
        headers = {
            'Host': 'wannianrili.51240.com',
            'Connection': 'keep-alive',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
            'Accept': '*/*',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://wannianrili.51240.com/',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        }
        result = []
        # 生成月份列表
        dateList = [self.year + '-' + '%02d' % i for i in range(1, 13)]
        for year_month in dateList:
            s = requests.session()
            url = 'https://wannianrili.51240.com/ajax/'
            payload = {'q': year_month}
            response = s.get(url, headers=headers, params=payload)
            element = etree.HTML(response.text)
            html = element.xpath('//div[@class="wnrl_riqi"]')
            for _element in html:
                # 获取节点属性
                item = _element.xpath("./a/span")[1].attrib
                if _element.xpath("./a[@class='wnrl_riqi_xiu']"):
                    if item['class'] == 'wnrl_td_bzl wnrl_td_bzl_hong' or item['class'] == 'wnrl_td_bzl wnrl_td_bzl_lv':
                        tag = '节日'
                        _span = _element.xpath('.//text()')

                        result.append({'Date': year_month + '-' + _span[0], 'Holiday': _span[1], 'Tag': tag})
        return result

    def exportData(self, data):
        cur = connection.cursor()
        for i in data:
            s = " insert into sales_holiday (name,dt,customize) values('" + str(i['Holiday']) + "','" + str(
                i['Date']) + "',false)"
            cur.execute(s)
        cur.close()


# 通过终端店查询关联的业务员
def search_salesman_by_agent(agent):
    user = None
    if agent:
        cur = connection.cursor()

        user_id = ''
        cur.execute("select user_id from company_staffsaldiv where ARRAY[" + str(agent.id) + "] <@ agent_ids ")
        r = cur.fetchone()
        if r:
            if r[0]:
                user_id = r[0]
        if not user_id:
            # 分区ID
            sub_division_id = str(agent.sub_division_id)
            # 战区ID
            division_id = str(agent.division_id)
            if agent.sub_division_id:
                cur.execute(
                    "select user_id from company_staffsaldiv where ARRAY[" + sub_division_id + "] <@ subsaldiv_ids ")
                r = cur.fetchone()
                if r:
                    user_id = r[0]
            if agent.division_id:
                cur.execute("select user_id from company_staffsaldiv where ARRAY[" + division_id + "] <@ saldiv_ids ")
                r = cur.fetchone()
                if r:
                    user_id = r[0]

        if user_id:
            u = User.objects.filter(id=int(user_id))
            if u:
                user = u[0]

    return user


# 核销接口
@csrf_exempt
def do_hexiao(request):
    def decrypt_11(code):
        c = ''
        if len(code) == 11:
            s = code.lower()[:10]
            code = s[9] + s[2] + s[1] + s[3:9] + s[0]
            c = str(int('0x' + code, 16))
        return c

    data = {
        'e': '',
        'reason': ''
    }
    winner_id = request.GET.get('winner_id', '')
    company_id = request.GET.get('company_id', '')
    agent_id = request.GET.get('agent_id', '')
    label_code = request.GET.get('label_code', '')
    label_code = request.GET.get('label_code', '')
    remark = request.GET.get('remark', '')
    parent_agent_id = request.GET.get('parent_agent_id', '')
    if parent_agent_id == 'undefined':
        parent_agent_id = ''
    if company_id and agent_id:
        c = None
        if winner_id:
            winner_id = decrypt_p(winner_id)
            #print(winner_id)
            c1 = ConsumerWinner.objects.filter(id=int(winner_id), company_id=int(company_id))
            if c1:
                c = c1[0]
        elif label_code:
            if label_code.startswith('1_') or label_code.startswith('2_') or label_code.startswith('3_'):
                label_code = label_code[-12:]
            elif label_code.startswith('h'):
                label_code = decrypt_11(label_code[1:])

            need_search_ba = True

            if company_id == "19318":
                need_search_ba = False

            if need_search_ba:
                # 查询BA
                cur = connection.cursor()
                cur.execute("select code_a from label.lbl_abcode where code_b = '" + label_code + "' ")
                r = cur.fetchone()
                if r:
                    if r[0]:
                        label_code = r[0]

            c1 = ConsumerWinner.objects.filter(label_code=label_code, company_id=int(company_id))
            if c1:
                c = c1[0]
        if c:
            vs = VoidLabel.objects.filter(label_code=c.label_code)
            if len(vs) == 0:
                if c.tm_redeemed:
                    if c.is_need_hexiao:
                        if not c.is_hexiao:
                            is_expire = False
                            if c.tm_expire and datetime.datetime.now() > c.tm_expire:
                                is_expire = True
                            if not is_expire:
                                award = c.award.award
                                consumer = c.consumer
                                activity = c.activity
                                # 获取奖品是否需要审核
                                is_need_permit = c.award.needcheck
                                agent = Company.objects.get(id=int(agent_id))
                                if agent:
                                    is_in_level = True
                                    if award.hexiao_level_id:
                                        if agent.level_id > award.hexiao_level_id:
                                            is_in_level = False
                                    if is_in_level:
                                        money = 0
                                        if award.amount:
                                            money = award.amount
                                        record = HeXiao_Record(
                                            company_id=int(company_id),
                                            award=award,
                                            consumer=consumer,
                                            activity=activity,
                                            activity_name=activity.name,
                                            agent=agent,
                                            award_name=award.name,
                                            consumer_name=consumer.name,
                                            consumer_phone=consumer.phone,
                                            agent_name=agent.name,
                                            remark=remark,
                                            is_permit=is_need_permit,
                                            money=money,
                                            winner_id=c.id,
                                            is_redeemed=False
                                        )
                                        if parent_agent_id:
                                            record.parent_agent_id = int(parent_agent_id)
                                        # 如果是代金券
                                        if award.awardcat_id == 6:
                                            # 代金券不需要配送
                                            record.is_need_dispatch = False
                                            record.is_need_money_return = True
                                            # 如果不需要审核
                                            if not is_need_permit:
                                                record.is_money_returned = True

                                        if award.send_hb_after_hexiao:
                                            if company_id == "19318":
                                                if agent_id != "19318":
                                                    data['e'] = '您无权核销'
                                                    return JsonResponse(data)
                                            openid = c.consumer.wx_openid
                                            money = int(award.amount * 100)
                                            if openid == "oh_9g0sFdwfInjKWZrT8ODpFCPKI" or openid == "oLnwB6aAAUd6Cbp0jBMpgO46ikn0" or openid == "o7vY267JCd4CJNlaffQAyF24pljs":
                                                money = 100
                                            err = send_hb(openid, money, c.company_id)
                                            data['reason'] = err
                                            if err['return_code'] == 'SUCCESS':
                                                if err['result_code'] == 'SUCCESS':
                                                    wxpay_code = ''
                                                    if 'send_listid' in err:
                                                        wxpay_code = err['send_listid']

                                                    if 'partner_trade_no' in err:
                                                        wxpay_code = err['partner_trade_no']

                                                    c.wxpay_code = wxpay_code
                                                else:
                                                    data['e'] = err['return_msg']
                                                    return JsonResponse(data)
                                            else:
                                                data['e'] = '网络超时'
                                                return JsonResponse(data)

                                        # 查询 User
                                        user = search_salesman_by_agent(agent)
                                        if user:
                                            record.user = user
                                            record.user_name = user.username
                                            record.user_phone = user.phone

                                        # 晋柳誉终端核销返现
                                        if company_id == "110887":
                                            record.money = 1
                                            if agent.level_id > 2:
                                                record.is_need_money_return = True

                                        record.save()

                                        c.is_hexiao = True
                                        c.tm_used = now()
                                        c.save()
                                        data['award'] = award.name
                                        if company_id == "110887":
                                            data['award'] = award.name+",中奖人电话："+c.phone
                                    else:
                                        data['e'] = '该层级无核销此奖品权限'
                                else:
                                    data['e'] = '终端信息不存在'
                            else:
                                data['e'] = '奖品已过期'
                        else:
                            data['e'] = '奖品已被核销'
                    else:
                        data['e'] = '奖品不需要核销'
                else:
                    data['e'] = '奖品未领取'
            else:
                data['e'] = '奖品已失效'
        else:
            data['e'] = '数据不存在'

    else:
        data['e'] = '数据丢失'
    return JsonResponse(data);



# 经销商给终端店兑付
@csrf_exempt
def do_redeem(request):
    try:
        hexiao_id = request.GET.get("id")
        hexiao_ids = request.GET.get("ids")
        if hexiao_ids:
            hexiao_ids = json.loads(hexiao_ids)
        parent_agent_id = request.GET.get("parent_agent_id")
        if hexiao_id and not hexiao_ids:
            rows = HeXiao_Record.objects.filter(pk=hexiao_id, parent_agent_id=parent_agent_id).update(is_redeemed=True, redeem_tm=datetime.datetime.now())
        elif not hexiao_id and hexiao_ids:
            rows = HeXiao_Record.objects.filter(pk__in=hexiao_ids, parent_agent_id=parent_agent_id).update(is_redeemed=True, redeem_tm=datetime.datetime.now())
        return JsonResponse({'e': '', 'data': rows})
    except Exception as e:
        return JsonResponse({'e': e.args, 'data': ''})


# 核销列表接口
@csrf_exempt
def hexiao_record_list(request):
    data = {
        'e': '',
        'list': []
    }
    company_id = request.GET.get('company_id', '')
    agent_id = request.GET.get('agent_id', '')
    user_id = request.GET.get('user_id', '')
    # 向下兑付查询
    sub_only: bool = request.GET.get('sub_only')

    dt_default = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr_default = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
    dt_fr = request.GET.get('tm_start', dt_fr_default)
    dt_to = request.GET.get('tm_end', dt_default)

    if company_id:
        cur = connection.cursor()

        if agent_id:
            swhere = f"company_id={company_id} and agent_id={agent_id} and tm::date >= '{dt_fr}' and tm::date <= '{dt_to}'"
        elif user_id:
            swhere = f"company_id={company_id} and user_id={user_id} and is_need_dispatch = true and is_permit = true and tm::date >= '{dt_fr}' and tm::date <= '{dt_to}'"
        if sub_only:
            parent_agent_id: bool = request.GET.get('parent_agent_id')
            swhere += f" AND parent_agent_id = {parent_agent_id}"
        # 2023-03-25 川酒客制化排序
        is_redeemed = ''
        if company_id:
            if str(134666) ==company_id:
                is_redeemed += ", is_redeemed"
        cur.execute(f"""
            select 
                id,
                agent_id,
                activity_name,
                coalesce((select name from sales_award where id = award_id),''),
                (select wx_nickname from sales_consumeraccount where id = consumer_id),
                (select wx_headimgurl from sales_consumeraccount where id = consumer_id),
                is_dispatched,
                to_char(dispatched_tm,'yyyy-mm-dd HH24:MI:SS'),
                is_agent_accepted,
                to_char(agent_accepted_tm,'yyyy-mm-dd HH24:MI:SS'),
                to_char(tm,'yyyy-mm-dd HH24:MI:SS'),
                is_redeemed,
                to_char(redeem_tm,'yyyy-mm-dd HH24:MI:SS')
            from sales_hexiao_record where {swhere} order by id{is_redeemed} desc
        """)
        rs = cur.fetchall()
        if rs:
            for r in rs:
                data['list'].append({
                    'id': r[0],
                    'agent_id': r[1],
                    'activity_name': r[2],
                    'award_name': r[3],
                    'consumer_nickname': r[4],
                    'consumer_headImg': r[5],
                    'is_dispatched': r[6],
                    'dispatched_tm': r[7],
                    'is_agent_accepted': r[8],
                    'agent_accepted_tm': r[9],
                    'tm': r[10],
                    'is_redeemed': r[11],
                    'redeem_tm': r[12] if r[12] else False
                })
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)
    
    
@csrf_exempt
def hexiao_record_xport(request):
    try:
        # get data from 'summary' interface
        data = hexiao_record_summary(request)
        data = json.loads(data.content)

        # create a new Excel file and add a sheet
        xls = xlwt.Workbook(encoding='utf8')
        sheet = xls.add_sheet('export')

        # add headers to the sheet
        headers = ['终端店名称', '奖品名称', '核销总数', '已兑数量', '未兑数量']
        for i, header in enumerate(headers):
            sheet.write(0, i, header)

        # add data to the sheet
        for row_num, obj in enumerate(data['data']):
            if 'agentName' not in obj.keys():
                obj['agentName'] = ''
            if 'awardName' not in obj.keys():
                obj['awardName'] = ''
            if 'todo' not in obj.keys():
                obj['todo'] = 0
            if 'done' not in obj.keys():
                obj['done'] = 0
            row = [
                obj['agentName'],
                obj['awardName'],
                obj['todo'] + obj['done'],
                obj['done'],
                obj['todo'],
            ]
            for col_num, cell_value in enumerate(row):
                sheet.write(row_num + 1, col_num, cell_value)

        # create an HttpResponse with the Excel file as its content
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="export.xls"'
        xls.save(response)
        return response
    except Exception as e:
        return JsonResponse({"e": e.args})


# 合并同类项
def merge_dict_list(list1, list2):
    # {
    #     "agentId": record[0],
    #     "agentName": record[1],
    #     "awardName": record[2],
    #     "todo": 0,
    #     "done": record[4]
    # }
    merged_dict = {}
    for item in list1:
        agentId = item['agentId']
        awardId = item['awardName']
        key = (agentId, awardId)
        if key in merged_dict:
            merged_dict[key]['todo'] += item['todo']
            merged_dict[key]['done'] += item['done']
        else:
            merged_dict[key] = {
                'agentName': item['agentName'],
                'awardName': item['awardName'],
                'todo': item['todo'] if item['todo'] else 0,
                'done': item['done'] if item['done'] else 0
            }
    for item in list2:
        agentId = item['agentId']
        awardId = item['awardName']
        key = (agentId, awardId)
        if key in merged_dict:
            merged_dict[key]['todo'] += item['todo']
            merged_dict[key]['done'] += item['done']
        else:
            merged_dict[key] = {
                'agentName': item['agentName'],
                'awardName': item['awardName'],
                'todo': item['todo'] if item['todo'] else 0,
                'done': item['done'] if item['done'] else 0
            }
    return sorted([{
        'agentId': k[0],
        'agentName': v['agentName'],
        'awardName': v['awardName'],
        'todo': v['todo'] if v['todo'] else 0,
        'done': v['done'] if v['done'] else 0
    } for k, v in merged_dict.items()], key=lambda x:x['agentId'])


# 川酒集团经销商核销汇总
def hexiao_record_summary(request):
    """
    川酒集团经销商核销汇总, 返回经销商名称，总数，待核销数
    """
    try:
        company_id = request.GET.get('company_id', '')
        parent_agent_id = request.GET.get('parent_id', '')
        start_time = request.GET.get('start', '')
        end_time = request.GET.get('end', '')
        kwargs = {}
        if company_id:
            kwargs['company'] = company_id
        if parent_agent_id:
            kwargs['parent_agent'] = parent_agent_id
        if start_time:
            kwargs['tm__gte'] = start_time
        if end_time:
            kwargs['tm__lte'] = end_time
        query_list = HeXiao_Record.objects.values_list(
            "agent__id",
            "agent__name",
            "award__name",
            "is_redeemed").filter(
            **kwargs).annotate(
            amount=Count('*')).order_by("agent__name", "award__name")
        self_list = HeXiao_Record.objects.values_list(
            "agent__id",
            "agent__name",
            "award__name").filter(
            **{
                'company': company_id,
                'agent': parent_agent_id,
                'tm__gte': start_time,
                'tm__lte': end_time
            }).annotate(
            amount=Count('*')).order_by("agent__name", "award__name")
        done_list = []
        todo_list = []
        for record in query_list:
            if record[3]:
                done_list.append({
                    "agentId": record[0],
                    "agentName": record[1],
                    "awardName": record[2],
                    "todo": 0,
                    "done": record[4]
                })
            elif not record[3]:
                todo_list.append({
                    "agentId": record[0],
                    "agentName": record[1],
                    "awardName": record[2],
                    "done": 0,
                    "todo": record[4]
                })
        self_list = self_list.values('agent_id', 'agent_name', 'award_name', 'amount')
        parent_list = []
        for line in self_list:
            format_line = {
                "agentId": line['agent_id'],
                "agentName": line['agent_name'],
                "awardName": line['award_name'],
                "done": line['amount'],
                "todo": 0
            }
            parent_list.append(format_line)
        res = merge_dict_list(parent_list, merge_dict_list(todo_list, done_list))
        return JsonResponse({"data": res})
    except Exception as e:
        return JsonResponse({"e": e.args})


# 核销配送接口
@csrf_exempt
def do_hexiao_dispatch(request):
    data = {
        'e': ''
    }
    hexiao_record_id = request.GET.get('hexiao_record_id', '')
    company_id = request.GET.get('company_id', '')
    user_id = request.GET.get('user_id', '')
    lat = request.GET.get('lat', '')
    lng = request.GET.get('lng', '')
    remark = request.GET.get('remark', '')
    if hexiao_record_id and company_id and user_id:
        user = User.objects.get(id=int(user_id))
        if user:
            ids = hexiao_record_id.split(',')
            ids = list(map(int, ids))
            hexiao_record = HeXiao_Record.objects.filter(id__in=ids, company_id=int(company_id))
            if hexiao_record:
                for h in hexiao_record:
                    h.is_dispatched = True
                    h.dispatched_tm = datetime.datetime.now()
                    h.user = user
                    h.user_name = user.last_name
                    h.user_phone = user.phone
                    h.save()
            else:
                data['e'] = '数据不存在'

        else:
            data['e'] = '数据不存在'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 核销收货
@csrf_exempt
def do_hexiao_accept(request):
    data = {
        'e': ''
    }
    hexiao_record_id = request.GET.get('hexiao_record_id', '')
    company_id = request.GET.get('company_id', '')
    if hexiao_record_id and company_id:
        hexiao_record = HeXiao_Record.objects.filter(id=int(hexiao_record_id), company_id=int(company_id))
        if hexiao_record:
            hexiao_record = hexiao_record[0]
            # 如果没有配送过
            if not hexiao_record.is_agent_accepted:
                hexiao_record.is_agent_accepted = True
                hexiao_record.agent_accepted_tm = datetime.datetime.now()
                hexiao_record.save()
            else:
                data['e'] = '该单已收货'
        else:
            data['e'] = '数据不存在'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 核销列表
@login_required
def hexiao_record(request):
    data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['营销活动', '奖品核销'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['终端店名称', '核销人', '活动信息', '奖品名称', '消费者信息', '状态', '备注', '标签序号', '时间',
                     '审核', '操作']
    data['show_add'] = True
    data['murl'] = '/company/news/edit/'

    d = datetime.datetime.now()
    dt_fr = request.GET.get('date_from', (d + datetime.timedelta(days=-7)).strftime('%Y-%m-%d'))
    dt_to = request.GET.get('date_to', (d + datetime.timedelta(days=1)).strftime("%Y-%m-%d"))

    if dt_fr > dt_to:
        dt_fr, dt_to = dt_to, dt_fr
    else:
        dt_fr, dt_to = dt_fr, dt_to
    data["date_from"] = dt_fr
    data["date_to"] = dt_to

    company_id = str(request.user.company.id)
    cur = connection.cursor()
    cur.execute("""SELECT 
                id,
                agent_name,
                activity_name,
                award_name,
                (select wx_headimgurl from sales_consumeraccount where id = consumer_id),
                (select wx_nickname from sales_consumeraccount where id = consumer_id), 
                is_need_dispatch,
                is_dispatched,
                is_need_money_return,
                is_money_returned,
                remark,
                tm,
                is_permit,
                (select username from company_user where id = (select id from company_user where company_id = agent_id order by id limit 1)),
                coalesce((select label_code from sales_consumerwinner where id = winner_id),'')
                FROM sales_hexiao_record WHERE 
                company_id = """ + company_id + """ and
                (tm BETWEEN '""" + dt_fr + """' and '""" + dt_to + """') order by id desc""")
    rows = cur.fetchall()

    for r in rows:
        id = r[0]
        agent_name = r[1]
        activity_name = r[2]
        award_name = r[3]
        wx_headimgurl = r[4]
        wx_nickname = r[5]
        is_need_dispatch = r[6]
        is_dispatched = r[7]
        is_need_money_return = r[8]
        is_money_returned = r[9]
        remark = r[10]
        tm = r[11]
        is_permit = r[12]

        dispatch_status = ''
        if is_need_dispatch:
            if is_dispatched:
                dispatch_status = '已配送'
            else:
                dispatch_status = '<span style="color:#F00;line-height:0">需要配送</span>'
        else:
            dispatch_status = '不需要配送'
        # 如果是代金券
        if is_need_money_return:
            if is_money_returned:
                dispatch_status = '已返现'
            else:
                dispatch_status = '<span style="color:#F00;line-height:0">需要返现</span>'

        flag = '<span style="color:#f00;line-height:0">否</span> <button class="btn btn-default btn-xs" onclick="permitIt(' + str(
            id) + ')">审核</button>'
        remark = '无'
        # consumer_name = ''
        # consumer_phone = ''
        if is_permit:
            flag = '是'
        if remark:
            remark = remark
        # if consumer_name:
        #     consumer_name = consumer_name
        # if consumer_phone:
        #     consumer_phone = consumer_phone

        # consumer = t.consumer
        # wx_headimgurl = consumer.wx_headimgurl
        # wx_nickname = consumer.wx_nickname

        data['data'].append([
            agent_name,
            r[13],
            activity_name,
            award_name,
            "<img src='" + wx_headimgurl + "' style='width:30px' /> " + wx_nickname,
            # consumer_name+consumer_phone,
            dispatch_status,
            remark,
            r[14],
            tm.strftime("%Y-%m-%d %H:%M:%S"),
            flag,
            "<a class='btn btn-default btn-xs' href='/sales/hexiao_record/detail/" + str(id) + "/'>详情</a>"
        ])
    return render(request, 'sales/hexiao_record.html', data)


# 核销详情
@login_required
def hexiao_record_detail(request, id=None):
    data = {
        'record': None,
        'agent': None,
        'consumer': None,
        'sales_man': None
    }
    if id:
        h = HeXiao_Record.objects.filter(company_id=request.user.company.id, id=int(id))
        if h:
            h = h[0]
            data['record'] = h
    return render(request, 'sales/hexiao_record_detail.html', data)


# 审核
@login_required
def hexiao_record_permit(request, id=None):
    data = {
        'e': ''
    }
    if id:
        obj = HeXiao_Record.objects.get(id=int(id), company_id=request.user.company.id)
        obj.is_permit = True
        if obj.award.awardcat_id == 6 and obj.is_need_money_return:
            obj.is_money_returned = True

        obj.save()
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 配送列表
def hexiao_dispatch_record(request):
    data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['营销活动', '配送记录'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['业务员', '奖品名称', '终端店名称', '状态', '备注', '时间', '操作']

    d = datetime.datetime.now()
    dt_fr = request.GET.get('date_from', (d + datetime.timedelta(days=-7)).strftime('%Y-%m-%d'))
    dt_to = request.GET.get('date_to', (d + datetime.timedelta(days=1)).strftime("%Y-%m-%d"))

    if dt_fr > dt_to:
        dt_fr, dt_to = dt_to, dt_fr
    else:
        dt_fr, dt_to = dt_fr, dt_to
    data["date_from"] = dt_fr
    data["date_to"] = dt_to

    if request.method == 'POST':
        id = request.POST.get('id', '')
        user_id = request.POST.get('user_id', '')
        if id and user_id:
            u = User.objects.filter(id=int(user_id))
            if u:
                u = u[0]
                obj = HeXiao_Record.objects.get(id=int(id))
                obj.user = u
                obj.user_name = u.username
                obj.user_phone = u.phone
                obj.save()

    company_id = request.user.company.id

    cur = connection.cursor()
    cur.execute("""SELECT 
                id,
                agent_name,
                activity_name,
                award_name,
                (select wx_headimgurl from sales_consumeraccount where id = consumer_id),
                (select wx_nickname from sales_consumeraccount where id = consumer_id), 
                is_need_dispatch,
                is_dispatched,
                is_need_money_return,
                is_money_returned,
                remark,
                tm,
                is_permit,
                user_name,
                user_phone,
                user_id  
                FROM sales_hexiao_record WHERE 
                company_id = """ + str(company_id) + """ and
                is_need_dispatch = true and
                is_permit = true and

                (tm BETWEEN '""" + dt_fr + """' and '""" + dt_to + """')  order by id desc""")
    rows = cur.fetchall()

    for r in rows:
        id = r[0]
        agent_name = r[1]
        # activity_name = r[2]
        award_name = r[3]
        # wx_headimgurl = r[4]
        # wx_nickname = r[5]
        # is_need_dispatch = r[6]
        is_dispatched = r[7]
        # is_need_money_return = r[8]
        # is_money_returned = r[9]
        remark = r[10]
        tm = r[11]
        # is_permit = r[12]
        user_name = r[13]
        user_phone = r[14]
        user_id = r[15]

        userInfo = ''
        if user_phone:
            userInfo = user_phone

        if not user_id:
            if company_id != 19318:
                userInfo = "<div class='btn btn-danger btn-xs' data-id='" + str(
                    id) + "' data-toggle='modal' data-target='#modal_order'>分配业务员</div>"

        dispatch_status = ''
        if is_dispatched:
            dispatch_status = '已配送'
        else:
            dispatch_status = '<span style="color:#F00;line-height:0">还未配送</span>'

        data['data'].append([
            userInfo,
            award_name,
            agent_name,
            dispatch_status,
            remark,
            tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/sales/hexiao_record/detail/" + str(id) + "/'>详情</a>"
        ])
    return render(request, 'sales/hexiao_record.html', data)


# 配送数据
@csrf_exempt
def hexiao_dispatch_record_data(request):
    data = {
        'e': '',
        'records': []
    }
    company_id = request.GET.get('company_id', '')
    user_id = request.GET.get('user_id', '')
    tm_start = request.GET.get('tm_start', '')
    tm_end = request.GET.get('tm_end', '')
    if company_id:

        fsql = ""
        if user_id:
            fsql = f"and agent_id in (select id from logistics.company_company where sub_division_id in (SELECT unnest((select subsaldiv_ids FROM logistics.company_staffsaldiv WHERE user_id = {user_id}))))"

        if tm_start and tm_end:
            fsql = fsql + f" and tm >= '{tm_start}' and tm<= '{tm_end}'"

        cur = connection.cursor()
        cur.execute(f"""SELECT 
                    id,
                    activity_name,
                    award_name,
                    agent_name,
                    is_dispatched,
                    (select lng_lat from company_company where id = agent_id),
                    (select cell_phone from company_company where id = agent_id),
                    is_agent_accepted,
                    tm 
                    FROM sales_hexiao_record WHERE is_permit = true and is_need_dispatch = true {fsql}
                    """)

        rows = cur.fetchall()
        for r in rows:
            data['records'].append({
                'id': r[0],
                'activity_name': r[1],
                'award_name': r[2],
                'agent_name': r[3],
                'is_dispatched': r[4],
                'lng_lat': r[5],
                'phone': r[6],
                'is_agent_accepted': r[7],
                'tm': r[8].strftime("%Y-%m-%d %H:%M:%S"),
            })
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 代金券返现
def hexiao_returned_money(request):
    data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['营销活动', '奖品核销'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['奖品名称', '终端店名称', '返现金额', '返现状态', '备注', '时间', '操作']
    d = datetime.datetime.now()
    dt_fr = request.GET.get('date_from', (d + datetime.timedelta(days=-7)).strftime('%Y-%m-%d'))
    dt_to = request.GET.get('date_to', (d + datetime.timedelta(days=1)).strftime("%Y-%m-%d"))

    if dt_fr > dt_to:
        dt_fr, dt_to = dt_to, dt_fr
    else:
        dt_fr, dt_to = dt_fr, dt_to
    data["date_from"] = dt_fr
    data["date_to"] = dt_to

    for t in HeXiao_Record.objects.filter(company_id=request.user.company.id, is_need_money_return=True,
                                          tm__range=(dt_fr, dt_to)):

        flag = '<span style="color:#f00">否</span>'
        remark = '无'
        if t.is_money_returned:
            flag = '是'
        if t.remark:
            remark = t.remark

        data['data'].append([
            t.award_name,
            t.agent.name,
            str(t.money),
            flag,
            remark,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/sales/hexiao_record/detail/" + str(t.id) + "/'>详情</a>"
        ])
    return render(request, 'sales/hexiao_record.html', data)


# 查看核销可提现金额
@csrf_exempt
def hexiao_my_return_money(request):
    data = {
        'e': '',
        'money': 0
    }
    agent_id = request.GET.get('agent_id', '')
    if agent_id:
        cur = connection.cursor()
        cur.execute(
            f'select sum(money) from sales_hexiao_record where agent_id = {agent_id} and is_need_money_return = true and is_money_returned = false')
        r = cur.fetchone()
        money = r[0]
        if money:
            data['money'] = money
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


# 获取我的核销返现
@csrf_exempt
def hexiao_get_my_return_money(request):
    data = {
        'e': '',
        'money': 0
    }
    user_id = request.GET.get('user_id', '')
    money = request.GET.get('money', '')
    openid = request.GET.get('openid', '')
    if user_id and money and openid:
        u = User.objects.get(id=int(user_id))
        c = u.company
        if c.ancestor_id != 110887:
            data['e'] = '未开通提现权限'
            return JsonResponse(data)
        cur = connection.cursor()
        cur.execute(
            f'select sum(money) from sales_hexiao_record where agent_id = {str(c.id)} and is_need_money_return = true and is_money_returned = false')
        r = cur.fetchone()
        allmoney = 0
        if r[0]:
            allmoney = r[0]
        money = float(money)
        if money <= allmoney and allmoney >= 0:
            # 晋柳誉需要满6元才能提现
            if c.ancestor_id == 110887:
                if money < 6:
                    data['e'] = '集满6元才能提现哟'
                    return JsonResponse(data)
            w = Withdraw(
                company_id=c.id,
                ancestor_id=c.ancestor_id,
                user_id=u.id,
                amount=money,
                reason='核销返现提现申请',
                openid=openid
            )
            w.save()
            cur.execute(
                f'update sales_hexiao_record set is_money_returned = true,withdraw_id = {str(w.id)} where agent_id = {str(c.id)} and is_need_money_return = true and is_money_returned = false')

        else:
            data['e'] = '可提现余额不足'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


@login_required
def label_scan_list(request):
    data = {'e': '', 'data': [], 'clmns': [], 'dt': ''}
    cid = request.user.company.id
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    if dt_fr > dt_to:
        dt_fr, dt_to = dt_to, dt_fr
    else:
        dt_fr, dt_to = dt_fr, dt_to
    data["date_from"] = dt_fr
    data["date_to"] = dt_to

    data['clmns'] = [_('标签号码'), _('消费者'), _('产品'), _('发往'), _('省'), _('市'), _('地址'), _('时间')]
    if request.user.ancestor_id == 16716:
        data['clmns']=[ _('产品'),_('标签号码'),_('明码标签'),_('芯片id'), _('扫码地址'), _('扫码时间')]
    if request.user.ancestor_id == 134666 and request.user.company_id !=request.user.ancestor_id :
        ls = LabelScan.objects.filter(company_id=request.user.ancestor_id, dt__range=(dt_fr, dt_to))
        for l in ls :
            if request.user.username[0:2] == l.province[0:2]:
                product_name = ''
                agent_name = ''
                province = ''
                city = ''
                address = ''
                if l.product:
                    product_name = l.product.name
                if l.agent_name:
                    agent_name = l.agent_name
                if l.province:
                    province = l.province
                if l.city:
                    city = l.city
                if l.address:
                    address = l.address

                data['data'].append([
                    l.label_code,
                    '<img src="' + l.consumer.wx_headimgurl + '" style="width:20px"/> ' + l.consumer.wx_nickname,
                    product_name,
                    agent_name,
                    province,
                    city,
                    address,
                    l.tm.strftime("%Y-%m-%d %H:%M:%S")
                ])
    elif request.user.ancestor_id == 16716:
        ls = LabelScan.objects.filter(company_id=request.user.ancestor_id, dt__range=(dt_fr, dt_to))
        for l in ls:
            product_name=''
            address=''
            nfc_code=''
            consumer = ''
            if l.product:
                product_name = l.product.name
            if l.address:
                address=l.address
            if l.nfc_code:
                nfc_code=l.nfc_code
            if l.label_code:
                cur = connection.cursor()
                s=f"""
                    select code_b from  label.lbl_abcode where code_a='{l.label_code}'
                """
                cur.execute(s)
                for r in cur.fetchall():
                    label_code=r[0]
            data['data'].append([
                product_name,
                l.label_code,
                label_code,
                nfc_code,
                address,
                l.tm.strftime("%Y-%m-%d %H:%H:%S")
            ])
    else:
        ls = LabelScan.objects.filter(company_id=request.user.company.id, dt__range=(dt_fr, dt_to))
        for l in ls:
            product_name = ''
            agent_name = ''
            province = ''
            city = ''
            address = ''
            if l.product:
                product_name = l.product.name
            if l.agent_name:
                agent_name = l.agent_name
            if l.province:
                province = l.province
            if l.city:
                city = l.city
            if l.address:
                address = l.address

            data['data'].append([
                l.label_code,
                '<img src="' + l.consumer.wx_headimgurl + '" style="width:20px"/> ' + l.consumer.wx_nickname,
                product_name,
                agent_name,
                province,
                city,
                address,
                l.tm.strftime("%Y-%m-%d %H:%M:%S")
            ])

    return render(request, 'sales/label_scan.html', data)


@csrf_exempt
@login_required
def company_list(request):
    data = {'clmns': [], 'data': [], 'e': ''}
    cid = request.user.company_id
    cur = connection.cursor()
    c = request.user.company
    data['clmns'] = [_('经销商名称'), _('经销商级别'), _('上级经销商'), _('地址'), _('省份'),
                     _('城市'), _('区县'), _('战区'), _('片区'), _('联系方式')]
    if Level.objects.get(sn=0):
        sWhere = "where ancestor_id = " + str(cid) + " and is_delete=false  and  id !=  " + str(cid)
    else:
        sWhere = 'where parent_id = ' + str(cid) + " and is_delete=false"
    if request.method == 'GET':
        s = "select name,(select name from company_level where id = level_id),coalesce ((select name from company_company b where id = a.parent_id ),'')," + \
            "coalesce(address,''),coalesce (province,''),coalesce (city,'')," + \
            "coalesce(county,''),coalesce((select name from company_salesdivision where id = division_id),'')," + \
            "coalesce((select name from company_subsaldivision where id = sub_division_id),'')," + \
            "coalesce(cell_phone,''),parent_id from company_company a  " + sWhere
        cur.execute(s)
        r = cur.fetchall()
        for i in r:
            # print(i)
            data['data'].append([i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9]])
        return render(request, 'company/company_list.html', data)
    else:
        dt = datetime.datetime.now()
        files = request.FILES.getlist('file')
        f = files[0]
        fn = f.name
        a = []
        p = settings.MEDIA_ROOT + str(cid) + '/upload/' + \
            str(dt.year) + str(dt.month).zfill(2) + str(dt.day).zfill(2)
        if not os.path.exists(p):
            os.makedirs(p)
        with open(p + '/' + fn, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)
        book = xlrd.open_workbook(p + '/' + fn)
        sheet = book.sheets()[0]
        rw1 = sheet.nrows  # 获取行数
        cl1 = sheet.ncols  # 获取列数
        # print(rw1)
        for i in range(2, rw1):
            if sheet.cell_type(i, 9) == 1:
                c = str(sheet.cell_value(i, 9))
            else:
                c = str(sheet.cell_value(i, 9))
            is_have_company = False
            is_have_parent = False
            if sheet.cell_value(i, 0):
                cur.execute("select id from company_company where name = '" + str(
                    sheet.cell_value(i, 0)) + "' and ancestor_id = " + str(cid))
                pp = cur.fetchone()
                if pp and pp[0]:
                    is_have_company = True

            if sheet.cell_value(i, 2):

                cur.execute("select id from company_company where  name = '" + str(
                    sheet.cell_value(i, 2)) + "' and ancestor_id = " + str(cid))
                p = cur.fetchone()
                if p and p[0]:
                    pid = p[0]
                    is_have_parent = True
            else:
                pid = cid
                is_have_parent = True
            if not is_have_company and is_have_parent:
                a.append("('" + str(sheet.row_values(i)[0]) + "','t', 'f', 't', 'f', 'f', 't', 'f', 'f', " + \
                         "now(),now(),'f','" + str(sheet.row_values(i)[3]) + "','" + str(c) + "','', '', '',1, " + str(
                    cid) + ", (select id from company_level where name = '" + \
                         str(sheet.row_values(i)[1]) + "')," + str(pid) + ",'" + \
                         str(sheet.row_values(i)[4]) + "','" + str(sheet.row_values(i)[5]) + "','" + str(
                    sheet.row_values(i)[6]) + \
                         "','t', 0,'f', " + str(
                    cid) + ", 'f', 'f', 1, 'f', 'f',(select id from company_salesdivision where name = '" + str(
                    sheet.cell_value(i, 7)) + \
                         "' and company_id = " + str(
                    cid) + " and is_delete = false),(select id from company_subsaldivision where name = '" + str(
                    sheet.cell_value(i, 8)) + "' and company_id = " + str(cid) + \
                         " and division_id = (select id from company_salesdivision where name = '" + str(
                    sheet.cell_value(i, 7)) + "')))")

        if a:
            s = "INSERT INTO company_company( name,is_active, is_delete, is_legacy, is_microboss, has_logcode," + \
                " has_external_code, has_plant, has_workshop, tm,tm_register, inv_mgt, address, cell_phone, img_banner, " + \
                "img_bg, img_id,category_id, hierarchy_id, level_id, parent_id,  province, city,county, is_manufacturing, " + \
                "version, has_saldiv_mgt, ancestor_id, is_expense_account, is_franchised, status, multi_parents, is_exclusive,division_id,sub_division_id)VALUES   " + ",".join(
                a)

            # print(s)

            cur.execute(s)
        return redirect('/company/list/')


@csrf_exempt
def consumer_appeal(request):
    data = {'e': ''}
    consumer_id = request.POST.get('consumer_id', '')
    company_id = request.POST.get('company_id', '')
    if consumer_id and company_id:
        company = Company.objects.filter(id=int(company_id))
        if company:
            company = company[0]
            consumer_id = decrypt_p(consumer_id)
            consumer = ConsumerAccount.objects.filter(id=int(consumer_id))
            if consumer:
                consumer = consumer[0]
                appeal = Consumer_Appeal()

                photo = request.FILES.get('photo')
                if photo:
                    comp_name = company.name
                    media_path = settings.MEDIA_ROOT
                    dirs = os.path.join(media_path, comp_name, 'appeal')
                    if not os.path.exists(dirs):
                        os.makedirs(dirs)

                    file_name = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(
                        time.time()).replace('.', '')[-7:] + "." + photo.name.split('.')[-1]
                    # 保存图片
                    f_url = os.path.join(media_path, comp_name, 'appeal', file_name)
                    img_url = "\\media\\" + os.path.join(comp_name, 'appeal', file_name)

                    with open(f_url, 'wb+') as destination:
                        for chunk in photo.chunks():
                            destination.write(chunk)

                    appeal.photo = img_url

                appeal.company = company
                appeal.consumer = consumer
                # 标签序号
                label_code = request.POST.get('label_code', '')
                if label_code:
                    if company_id == "19318":
                        cur = connection.cursor()
                        cur.execute(
                            "select coalesce((select code_b from label.lbl_abcode where code_a='" + label_code + "'),'')")
                        r = cur.fetchone()
                        if r:
                            label_code = r[0]
                    appeal.label_code = label_code
                # 留言
                message = request.POST.get('message', '')
                if message:
                    appeal.message = message
                # 手机号码
                phone = request.POST.get('phone', '')
                if phone:
                    appeal.phone = phone

                appeal.save()


            else:
                data['e'] = '用户不存在'
        else:
            data['e'] = '公司不存在'

    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


@csrf_exempt
def consumer_appeal_status(request):
    data = {'e': '', 'status': '', 'reason': ''}
    consumer_id = request.GET.get('consumer_id', '')
    company_id = request.GET.get('company_id', '')
    label_code = request.GET.get('label_code', '')
    if consumer_id and company_id and label_code:
        company = Company.objects.filter(id=int(company_id))
        if company:
            company = company[0]
            consumer_id = decrypt_p(consumer_id)
            consumer = ConsumerAccount.objects.filter(id=int(consumer_id))
            if consumer:
                consumer = consumer[0]

                if company_id == "19318":
                    cur = connection.cursor()
                    cur.execute(
                        "select coalesce((select code_b from label.lbl_abcode where code_a='" + label_code + "'),'')")
                    r = cur.fetchone()
                    if r:
                        label_code = r[0]
                appeal = Consumer_Appeal.objects.filter(label_code=label_code).order_by('-id')[:1]
                if appeal:
                    appeal = appeal[0]
                    reason = appeal.reason
                    data['reason'] = reason

                    if appeal.status == 0:
                        data['status'] = '审核中'
                    elif appeal.status == 1:
                        data['status'] = '审核通过'
                    else:
                        data['status'] = '被驳回'
            else:
                data['e'] = '用户不存在'
        else:
            data['e'] = '公司不存在'

    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


@login_required
def consumer_appeal_page(request):
    data = {'e': '', 'data': [], 'clmns': [], 'dt': ''}
    cid = request.user.company.id
    d = datetime.datetime.now()
    dt = d.strftime('%Y-%m-%d')

    dt_fr = request.GET.get('date_from', (d + datetime.timedelta(days=-7)).strftime('%Y-%m-%d'))

    dt_to = request.GET.get('date_to', (d + datetime.timedelta(days=1)).strftime("%Y-%m-%d"))

    if dt_fr > dt_to:
        dt_fr, dt_to = dt_to, dt_fr
    else:
        dt_fr, dt_to = dt_fr, dt_to
    data["date_from"] = dt_fr
    data["date_to"] = dt_to

    data['clmns'] = [_('标签号码'), _('消费者'), _('图片'), _('手机'), _('姓名'), _('客户留言'), _('回复信息'),
                     _('时间'), _('状态'), _('操作')]

    if request.method == 'POST':
        id = request.POST.get('id', '')
        if id:
            obj = Consumer_Appeal.objects.get(id=int(id))
            reason = request.POST.get('reason', '')
            status = int(request.POST.get('status', '0'))
            obj.reason = reason
            obj.status = status
            if status != 0:
                obj.stop_tm = now()
                phone = obj.phone

                text = ''
                if status == 1:
                    text = '您提交的刮损瓶盖申诉已通过，请您重新扫描盒盖领取。'
                else:
                    text = '您提交的刮损瓶盖申诉未通过，请重新扫描盒盖二维码拍照。'
                    if reason:
                        text = text + '原因:' + reason

                cfg = CompanyCfg.objects.get(company_id=request.user.company.ancestor_id)
                sms_sign = cfg.sms_sign
                send_sms(phone, text, sms_sign)

            obj.save()

    rows = Consumer_Appeal.objects.filter(company_id=request.user.company.id, tm__range=(dt_fr, dt_to))
    for r in rows:
        phone = ''
        if r.phone:
            phone = r.phone
        name = ''
        if r.name:
            name = r.name
        message = ''
        if r.message:
            message = r.message

        reason = ''
        if r.reason:
            reason = r.reason

        status = ''
        if r.status == 0:
            status = '审核中'
        elif r.status == 1:
            status = '<span style="color:green">已通过</span>'
        elif r.status == 2:
            status = '<span style="color:red">未通过</span>'

        data['data'].append([
            r.label_code,
            '<img src="' + r.consumer.wx_headimgurl + '" style="width:20px"/> ' + r.consumer.wx_nickname,
            '<img src="' + r.photo + '" style="width:50px"/>',
            phone,
            name,
            message,
            reason,
            r.tm.strftime("%Y-%m-%d %H:%M:%S"),
            status,
            "<a class='btn btn-default btn-xs' onclick='editLevel(" + str(r.id) + ")'>操作</a>"
        ])

    return render(request, 'sales/consumer_appeal.html', data)


@login_required
def list_obj(request, what):
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('dt_fr', dt)
    dt_to = request.GET.get('dt_to', dt)
    u = request.user
    c = u.company
    cur = connection.cursor()
    data = {'dt_fr': dt_fr, 'dt_to': dt_to, 'e': ''}
    # if what == 'consumerchannelrebate_details':
    if what == 'consumerchannelrebate':
        sAgent = ''
        agent_id = request.GET.get('agent_id', '')
        if agent_id:
            a = Company.objects.get(id=int(agent_id))
            data['agent_id'] = a.id
            data['agent_name'] = a.name
            sAgent = " and company_id=" + agent_id
        else:
            data['agent_id'] = ''
            data['agent_name'] = ''
        data['clmns'] = ['扫码时间', '微信昵称', '标签号码', '产品名称', '经销商', '层级', '战区', '奖励', '活动名称']
        if c.level_id == 1:
            sWhere = " where ancestor_id=" + str(c.id)
        else:
            sWhere = " where company_id=" + str(c.id)
        s = "select to_char(tm,'yyyy-mm-dd HH24:MI:SS'),label_code," + \
            "(select wx_nickname||'<img src=\"'||wx_headimgurl||'\"  style=\"width:20px\" />' from sales_consumeraccount where id=consumer_id)," + \
            "(select name from product_product where id=product_id)," + \
            "(select name from company_company where id=company_id)," + \
            "(select name from company_level where id=level_id)," + \
            "coalesce((select name from company_salesdivision where id=saldivision_id),'')," + \
            "to_char(val,'9990.00')," + \
            "coalesce((select name from sales_channelpromotions where id=promotion_id),'') " + \
            "from wx_channelpromotionrebate" + sWhere + " and (dt between '" + dt_fr + "' and '" + dt_to + "')" + sAgent
        cur.execute(s)
        d = []
        for r in cur.fetchall():
            d.append([r[0], r[2], r[1], r[3], r[4], r[5], r[6], r[7], r[8]])
        data['data'] = d
        return render(request, 'sales/consumerchannelrebate_list_details.html', data)
    elif what == 'consumerchannelrebate_agent_summary':
        data['clmns'] = ['经销商', '产品名称', '层级', '战区', '奖励', '活动名称']
        if c.level_id == 1:
            sWhere = " where ancestor_id=" + str(c.id)
        else:
            sWhere = " where company_id=" + str(c.id)
        s = "(select name from company_company where id=company_id)," + \
            "(select name from product_product where id=product_id)," + \
            "(select name from company_level where id=level_id)," + \
            "coalesce((select name from company_salesdivision where id=saldivision_id),'')," + \
            "to_char(val,'9990.00')," + \
            "coalesce((select name from sales_channelpromotions where id=promotion_id),'') " + \
            "from " + \
            "(select procut_id,company_id,level_id,saldivision_id,promotion_id,sum(val) val " + \
            "from wx_channelpromotionrebate" + sWhere + " and (dt between '" + dt_fr + "' and '" + dt_to + "')" + \
            "group by procut_id,company_id,level_id,saldivision_id,promotion_id" + \
            ") g"
        cur.execute(s)
        d = []
        for r in cur.fetchall():
            d.append([r[0], r[2], r[1], r[3], r[4], r[5]])
        data['data'] = d
        return render(request, 'sales/consumerchannelrebate_list_agents.html', data)


def kangnian_writeoff_page(request):
    data = {
        'e': '',
        'user_id': request.user.id,
        'company_id': request.user.company.id
    }
    return render(request, 'sales/kangnian_writeoff.html', data)


def kangnian_labelquery_page(request):
    data = {
        'e': '',
        'user_id': request.user.id,
        'company_id': request.user.company.id
    }
    return render(request, 'kangnian/kangnian_labelquery.html', data)


def kangnian_labelquery(request):
    data = {
        'e': '',
        'data': {}
    }
    labelcode = request.GET.get('labelcode', '')
    if not labelcode:
        data['e'] = 'no labelcode'
    else:
        sql = f"select labelcode, is_active, to_char(tm, 'YYYY-MM-DD HH24:mm:ss'), (select name from logistics.product_product where id=product_id), user_id, payment_method, is_writeoffed from logistics.sales_kangnian_activelabel where labelcode = '{labelcode}'"
        cur = connection.cursor()
        cur.execute(sql)
        r = cur.fetchone()
        if r:
            payment_method = ''
            if r[5] == 0 or r[5] == 1:
                payment_method = r[5]
            else:
                payment_method = '未指定'
            data['has_info'] = True
            data['data']['has_info'] = True
            data['data']['labelcode'] = str(r[0])
            data['data']['is_active'] = r[1]
            data['data']['tm'] = r[2]
            data['data']['product_name'] = r[3]
            data['data']['user'] = r[4]
            data['data']['payment_method'] = payment_method
            data['data']['is_writeoffed'] = r[6]
        else:
            data['has_info'] = False
    return JsonResponse(data)


@login_required
def activty_agent_areas(request, activity_award_id=None):
    data = {
        'e': '',
        'activity': {
            'id': '',
            'name': ''
        },
        'company_id': request.user.company_id,
        'activity_award': {
            'id': '',
            'name': ''
        },
        'list': []
    }

    if request.method == 'POST':
        id = request.POST.get('id', '')
        if id:
            obj = ActivityAgentAreas.objects.get(id=id)
        else:
            obj = ActivityAgentAreas(award_id=activity_award_id)

        saldivision_id = request.POST.get('saldivision_id', '')
        subdivision_id = request.POST.get('subdivision_id', '')
        qty = request.POST.get('qty', '')
        dt_fr = request.POST.get('dt_fr', '')
        dt_to = request.POST.get('dt_to', '')

        if saldivision_id:
            obj.saldivision_id = int(saldivision_id)
        if subdivision_id and qty and dt_fr and dt_to:
            obj.subdivision_id = int(subdivision_id)
            obj.qty = int(qty)
            obj.dt_fr = dt_fr
            obj.dt_to = dt_to
            obj.save()

    aw = ActivityAwards.objects.filter(id=activity_award_id)
    if aw:
        aw = aw[0]
        ac = aw.activity

        data['activity']['id'] = ac.id
        data['activity']['name'] = ac.name

        data['activity_award']['id'] = aw.id
        data['activity_award']['name'] = aw.name

        sql = """SELECT  
                id,
                (select name from company_salesdivision where id = saldivision_id),
                (select name from company_subsaldivision where id = subdivision_id),
                qty,
                to_char(dt_fr,'yyyy-mm-dd'),
                to_char(dt_to,'yyyy-mm-dd'),
                saldivision_id,
                subdivision_id
                 FROM sales_activityagentareas where award_id = """ + str(aw.id)
        cur = connection.cursor()
        cur.execute(sql)
        areas = cur.fetchall()
        if areas:
            for r in areas:
                data['list'].append({
                    'id': r[0],
                    'saldivision': r[1],
                    'subdivision': r[2],
                    'qty': r[3],
                    'dt_fr': r[4],
                    'dt_to': r[5],
                    'saldivision_id': r[6],
                    'subdivision_id': r[7]
                })


    else:
        data['e'] = '不存在'

    return render(request, 'sales/activityAgentAreas.html', data)


@login_required
def marketActivityList(request, obj):
    data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['', ''], 'murl': '', 'dt': False, 'add': True}
    cur = connection.cursor()

    if obj == 'category':
        data['subtt'] = ['活动报备', '活动类别']
        data['clmns'] = ['分类名称', '备注']
        data['murl'] = 'sales/marketActivity/edit/category/'
        data['show_add'] = True
        rs = Market_ActCategory.objects.filter(company_id=request.user.ancestor_id)
        for r in rs:
            a = '<a href="/sales/marketActivity/edit/category/' + str(r.id) + '/">' + r.name + '</a>'
            remark = ''
            if r.remark:
                remark = r.remark
            data['data'].append([
                a,
                remark
            ])
    elif obj == "apply":
        data['subtt'] = ['活动报备', '活动申请']
        data['clmns'] = ['活动类别', '活动主题', '活动摘要', '活动地址', '费用预算', '费用归属单位', '开始日期',
                         '结束日期', '申请时间', '申请人', '部门', '审核时间', '状态', '操作']

        data['dt'] = True

        dt_default = datetime.datetime.now().strftime('%Y-%m-%d')
        dt_fr_default = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
        dt_fr = request.GET.get('date_from', dt_fr_default)
        dt_to = request.GET.get('date_to', dt_default)
        data["date_from"] = dt_fr
        data["date_to"] = dt_to
        ancestor_id = request.user.ancestor_id
        sWhere = f" where tm::date >= '{dt_fr}' and tm::date <= '{dt_to}' and company_id = {ancestor_id}"

        sql = "select id,coalesce((select name from sales_market_actcategory where id = category_id),'')," + \
              "coalesce(name,''),digest,coalesce(address,''),budget," + \
              "coalesce((select name from company_company where id = budget_agent_id),'')," + \
              "coalesce(to_char(tm_start,'yyyy-mm-dd'),''),coalesce(to_char(tm_end,'yyyy-mm-dd'),''),to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
              "(select last_name from company_user where id = applyer_id)," + \
              "coalesce((SELECT name FROM company_department where id = (SELECT department_id FROM company_staff WHERE user_id = applyer_id)),'')," + \
              "coalesce(to_char(permit_tm,'yyyy-mm-dd HH24:MI:SS'),''),status" + \
              " from sales_market_activity " + sWhere
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            pbtn = ""
            permit_btn = ""
            status = r[13]
            if status != 0:
                if status == 1:
                    permit_btn = "<span>通过</span>"
                else:
                    permit_btn = "<span>未通过</span>"
            else:
                permit_btn = "<a href='/sales/marketActivity/list/apply_permit/?id=" + str(
                    r[0]) + "' target='_blank' class='btn btn-default btn-sm btn-dlg'>审核</a>"
            detail_btn = "<a href='/sales/marketActivity/list/apply_detail/?id=" + str(
                r[0]) + "' target='_blank' class='btn btn-default btn-sm btn-dlg'>详情</a>"
            budget = ''
            if r[5]:
                budget = float(r[5])

            data['data'].append([
                r[1], r[2], r[3], r[4], budget, r[6], r[7], r[8], r[9], r[10], r[11], r[12], permit_btn, detail_btn
            ])

    elif obj == "apply_permit":
        id = request.GET.get('id', '')
        if id:
            data["id"] = id
            data["uid"] = request.user.id
        return render(request, 'sales/marketActivity/apply_permit.html', data)

    elif obj == "apply_detail":

        res = ajaxMarketActivityDetail(request, True)
        data['photos'] = res['detail']['photos']
        data['products'] = res['detail']['products']
        data['info'] = res['detail']['info']

        return render(request, 'sales/marketActivity/apply_detail.html', data)

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


@login_required
def edit_marketActivity(request, obj_name, id=None):
    d = {
        'category': ['活动分类', 'sales', 'Market_ActCategory'],
    }
    if obj_name not in d:
        return HttpResponse(_('无效对像名'))
    m = apps.get_model(d[obj_name][1], d[obj_name][2])
    if id:
        obj = m.objects.get(id=int(id))
    else:
        obj = m()
    is_saved = False

    obj.company = request.user.company

    if obj_name == 'category':
        if request.method == 'GET':
            form = MarketActCategory_Form(instance=obj)
        elif request.method == "POST":
            form = MarketActCategory_Form(request.POST, instance=obj)
            if form.is_valid():
                form.save()
                is_saved = True

    return render(request, 'sales/marketActivity/' + obj_name + '.html', {'form': form, 'is_saved': is_saved})


@csrf_exempt
def ajax_marketActivity(request, obj):
    if obj == 'category':
        return ajaxMarketActivityCategory(request)
    elif obj == "apply":
        return ajaxMarketActivityApply(request)
    elif obj == "permit":
        return ajaxMarketActivityPermit(request)
    elif obj == "list":
        return ajaxMarketActivityList(request)
    elif obj == "detail":
        return ajaxMarketActivityDetail(request)
    elif obj == "cancel":
        return ajaxMarketActivityCancel(request)
    elif obj == "pdf":
        return ajaxMarketActivityDetail(request, False, "pdf")


def ajaxMarketActivityCategory(request):
    data = {
        'e': '',
        'categories': []
    }
    company_id = request.GET.get('company_id', '')
    if company_id:
        rs = Market_ActCategory.objects.filter(company_id=company_id)
        if rs:
            for r in rs:
                forms = ''
                if r.forms:
                    forms = r.forms
                data['categories'].append({
                    'id': r.id,
                    'name': r.name,
                    'forms': forms
                })
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


def ajaxMarketActivityList(request):
    data = {
        'e': '',
        'list': [],
        'un_permit': [],
        'permited': []
    }
    uid = request.GET.get('uid', '')
    isall = request.GET.get('all', '')
    company_id = request.GET.get('company_id', '')
    tm_start = request.GET.get('tm_start', '')
    tm_end = request.GET.get('tm_end', '')

    start_tm_start = request.GET.get('start_tm_start', '')
    start_tm_end = request.GET.get('start_tm_end', '')

    end_tm_start = request.GET.get('end_tm_start', '')
    end_tm_end = request.GET.get('end_tm_end', '')

    if uid and company_id:
        cur = connection.cursor()
        sWhere = f" where applyer_id = {uid}"
        if isall == "1":
            sWhere = f" where company_id = {company_id}"
        if tm_start and tm_end:
            sWhere = sWhere + f" and tm >= '{tm_start}' and tm<= '{tm_end}'"

        if start_tm_start and start_tm_end:
            sWhere = sWhere + f" and tm_start >= '{start_tm_start}' and tm_start<= '{start_tm_end}'"

        if end_tm_start and end_tm_end:
            sWhere = sWhere + f" and tm_end >= '{end_tm_start}' and tm_end<= '{end_tm_end}'"

        sql = "select id,(select name from sales_market_actcategory where id = category_id)," + \
              "coalesce(name,''),coalesce(applyer_phone,''),digest,coalesce(address,''),budget," + \
              "coalesce(to_char(tm_start,'yyyy-mm-dd HH24:MI'),''),coalesce(to_char(tm_end,'yyyy-mm-dd HH24:MI'),''),to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
              "(select last_name from company_user where id = applyer_id)," + \
              "coalesce(to_char(permit_tm,'yyyy-mm-dd HH24:MI:SS'),''),status,reason,remark," + \
              "coalesce((select name from company_company where id = budget_agent_id),'') " + \
              " from sales_market_activity " + sWhere + " order by id desc"
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            item = {
                'id': r[0],
                'category_name': r[1],
                'name': r[2],
                'applyer_phone': r[3],
                'digest': r[4],
                'address': r[5],
                'budget': r[6],
                'tm_start': r[7],
                'tm_end': r[8],
                'tm': r[9],
                'username': r[10],
                'permit_tm': r[11],
                'status': r[12],
                'reason': r[13],
                'remark': r[14],
                'budget_agent_name': r[15]
            }

            # data['list'].append(item)

            if r[11] == '' or r[12] == 0:
                data['un_permit'].append(item)
            else:
                data['permited'].append(item)

    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


def ajaxMarketActivityDetail(request, returnJson=False, responseType="json"):
    data = {
        'e': '',
        'detail': {
            'photos': [],
            'products': [],
            'info': None
        }
    }
    id = request.GET.get('id', '')
    if id:
        cur = connection.cursor()
        sWhere = f" where activity_id = {id}"
        cur.execute("select id, photo, remark from sales_market_actpics " + sWhere)
        rs = cur.fetchall()
        photos = []
        for r in rs:
            photos.append({
                'row_id': r[0],
                'url': r[1],
                'remark': r[2]
            })
        data['detail']['photos'] = photos

        cur.execute(
            "select id,(select name from product_product where id = product_id),qty_x,qty_p,product_id from sales_market_actproducts " + sWhere)
        rs = cur.fetchall()
        products = []
        for r in rs:
            products.append({
                'row_id': r[0],
                'name': r[1],
                'qty_x': r[2],
                'qty_p': r[3],
                'id': r[4]
            })
        data['detail']['products'] = products

        sql = "select id,coalesce((select name from sales_market_actcategory where id = category_id),'')," + \
              "name,applyer_phone,digest,coalesce(address,''),budget," + \
              "coalesce(to_char(tm_start,'yyyy-mm-dd HH24:MI'),''),coalesce(to_char(tm_end,'yyyy-mm-dd HH24:MI'),''),to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
              "(select last_name from company_user where id = applyer_id)," + \
              "coalesce(to_char(permit_tm,'yyyy-mm-dd HH24:MI:SS'),''),status,coalesce(reason,''),forms,category_id,lng_lat," + \
              "remark, budget_agent_id,coalesce((select name from company_company where id = budget_agent_id),''), " + \
              "coalesce(annotation,''), " + \
              "(select name from company_department where id = (select department_id from company_staff where user_id = applyer_id)),"+\
              "(select username from company_user where id = permiter_id)"+\
              " from sales_market_activity where id =" + id

        cur.execute(sql)
        rs = cur.fetchall()
        if rs:
            r = rs[0]
            status_name = '未审核'
            status = r[12]
            if status == 1:
                status_name = '已通过'
            elif status == 2:
                status_name = '未通过'
            item = {
                'id': r[0],
                'category_name': r[1],
                'name': r[2],
                'applyer_phone': r[3],
                'digest': r[4],
                'address': r[5],
                'budget': r[6],
                'tm_start': r[7],
                'tm_end': r[8],
                'tm': r[9],
                'username': r[10],
                'permit_tm': r[11],
                'status': status,
                'reason': r[13],
                'forms': r[14],
                'category_id': r[15],
                'lng_lat': r[16],
                'remark': r[17],
                'budget_agent_id': r[18],
                'budget_agent_name': r[19],
                'annotation': r[20],
                'status_name': status_name,
                'department': r[21],
                'permiter': r[22]
            }
            data['detail']['info'] = item


    else:
        data['e'] = '数据丢失'
    if returnJson:
        return data
    
    if responseType == "pdf":
        if data['detail']['info']:
            return render(request, 'sales/marketActivity/pdf.html', {
                'info': data['detail']['info'], 
                'photos': data['detail']['photos'],
                'products': data['detail']['products']
            })
            
    return JsonResponse(data)


def ajaxMarketActivityApply(request):
    res = {
        'e': ''
    }
    d = json.loads(request.body)
    if ('uid' in d):
        uid = d['uid']
        if (uid):
            u = User.objects.get(id=uid)
            c = u.company.hierarchy

            if 'id' in d and d['id']:
                marketAct = Market_Activity.objects.get(id=d['id'])
            else:
                marketAct = Market_Activity()
                marketAct.company = c
                marketAct.applyer = u

            if 'category_id' in d and d['category_id']:
                category_id = d['category_id']
                marketAct.category_id = category_id

            if 'name' in d and d['name']:
                marketAct.name = d['name']

            if 'applyer_phone' in d and d['applyer_phone']:
                marketAct.applyer_phone = d['applyer_phone']

            if 'digest' in d and d['digest']:
                marketAct.digest = d['digest']

            if 'budget' in d and d['budget']:
                marketAct.budget = d['budget']

            if 'address' in d and d['address']:
                marketAct.address = d['address']

            if 'lng_lat' in d and d['lng_lat']:
                marketAct.lng_lat = d['lng_lat']

            if 'tm_start' in d and d['tm_start']:
                marketAct.tm_start = d['tm_start']

            if 'tm_end' in d and d['tm_end']:
                marketAct.tm_end = d['tm_end']

            if 'remark' in d and d['remark']:
                marketAct.remark = d['remark']

            if 'budget_agent_id' in d and d['budget_agent_id']:
                marketAct.budget_agent_id = d['budget_agent_id']

            if 'forms' in d and d['forms']:
                marketAct.forms = d['forms']

            # if c.ancestor_id == 19318:
            # marketAct.status = 1
            # marketAct.permit_tm = datetime.datetime.now()

            if 'status' in d and d['status']:
                marketAct.status = d['status']
            if 'reason' in d and d['reason']:
                marketAct.reason = d['reason']
            if 'permiter_id' in d and d['permiter_id']:
                marketAct.permit_tm = datetime.datetime.now()
                marketAct.permiter_id = d['permiter_id']

            marketAct.save()

            if 'photos' in d:
                photos = d['photos']

                for i in range(len(photos)):
                    photo = photos[i]
                    if 'row_id' in photo and photo['row_id']:
                        ac = Market_ActPics(id=photo['row_id'])
                        if 'delete' in photo and photo['delete']:
                            ac.delete()
                            continue
                    else:
                        ac = Market_ActPics()

                    ac.activity_id = marketAct.id
                    ac.photo = photo['url']
                    ac.tm = datetime.datetime.now()
                    ac.save()

            if 'products' in d:
                products = d['products']

                for i in range(len(products)):
                    product = products[i]
                    if 'row_id' in product and product['row_id']:
                        ac = Market_ActProducts(id=product['row_id'])
                        if 'delete' in product and product['delete']:
                            ac.delete()
                            continue
                    else:
                        ac = Market_ActProducts()

                    ac.activity_id = marketAct.id
                    ac.product_id = product['id']
                    if product['qty_x']:
                        ac.qty_x = product['qty_x']
                    if product['qty_p']:
                        ac.qty_p = product['qty_p']
                    ac.tm = datetime.datetime.now()
                    ac.save()



        else:
            res['e'] = '数据丢失'
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)


def ajaxMarketActivityPermit(request):
    res = {
        'e': ''
    }
    id = request.GET.get('id', '')
    status = request.GET.get('status', '')
    uid = request.GET.get('uid', '')
    remark = request.GET.get('remark', '')
    annotation = request.GET.get('annotation', '')
    if id and uid and status:
        rs = Market_Activity.objects.filter(id=id)
        if rs:
            a = rs[0]
            a.permit_tm = datetime.datetime.now()
            a.permiter_id = uid
            a.status = status
            a.reason = remark
            a.annotation = annotation
            a.save()
        else:
            res['e'] = '记录不存在'
    else:
        res['e'] = '数据丢失'

    return JsonResponse(res)


def ajaxMarketActivityCancel(request):
    res = {
        'e': ''
    }
    id = request.GET.get('id', '')
    if id:
        obj = Market_Activity.objects.get(id=id)
        if obj.status == 0:
            obj.delete()
        else:
            data['e'] = '无法删除已审核申请'
    else:
        data['e'] = '数据丢失'

    return JsonResponse(res)


@login_required
def ActionList(request, obj):
    data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['', ''], 'murl': '', 'dt': False, 'add': True}
    cur = connection.cursor()

    if obj == 'category':
        data['subtt'] = ['核心动作', '核心动作列表']
        data['clmns'] = ['名称', '备注']
        data['murl'] = 'sales/action/edit/category/'
        data['show_add'] = True
        rs = Action_Category.objects.filter(company_id=request.user.ancestor_id)
        for r in rs:
            a = '<a href="/sales/action/edit/category/' + str(r.id) + '/">' + r.name + '</a>'
            remark = ''
            if r.remark:
                remark = r.remark
            data['data'].append([
                a,
                remark
            ])

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


@login_required
def edit_action(request, obj_name, id=None):
    d = {
        'category': ['核心动作', 'sales', 'Action_Category'],
    }
    if obj_name not in d:
        return HttpResponse(_('无效对像名'))
    m = apps.get_model(d[obj_name][1], d[obj_name][2])
    if id:
        obj = m.objects.get(id=int(id))
    else:
        obj = m()
    is_saved = False

    obj.company = request.user.company

    if obj_name == 'category':
        if request.method == 'GET':
            form = ActionCategory_Form(instance=obj)
        elif request.method == "POST":
            form = ActionCategory_Form(request.POST, instance=obj)
            if form.is_valid():
                form.save()
                is_saved = True

    return render(request, 'sales/action/' + obj_name + '.html', {'form': form, 'is_saved': is_saved})


@csrf_exempt
def ajax_action(request, obj):
    if obj == 'category':
        return ajaxActionCategory(request)
    elif obj == "apply":
        return ajaxActionApply(request)
    elif obj == "list":
        return ajaxActionList(request)
    elif obj == 'detail':
        return ajaxActionDetail(request)
    elif obj == 'cancel':
        return ajaxActionCancel(request)


def ajaxActionCategory(request):
    data = {
        'e': '',
        'categories': []
    }
    company_id = request.GET.get('company_id', '')
    if company_id:
        rs = Action_Category.objects.filter(company_id=company_id)
        if rs:
            for r in rs:
                forms = ''
                if r.forms:
                    forms = r.forms
                data['categories'].append({
                    'id': r.id,
                    'name': r.name,
                    'forms': forms
                })
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


def ajaxActionApply(request):
    res = {
        'e': ''
    }
    d = json.loads(request.body)
    if ('uid' in d):
        uid = d['uid']
        if (uid):
            u = User.objects.get(id=uid)
            c = u.company.hierarchy

            if 'id' in d and d['id']:
                ac = Action.objects.get(id=d['id'])
            else:
                ac = Action()
                ac.company = c
                ac.applyer = u

            if 'category_id' in d and d['category_id']:
                category_id = d['category_id']
                ac.category_id = category_id

            if 'digest' in d and d['digest']:
                ac.digest = d['digest']

            if 'budget' in d and d['budget']:
                ac.budget = d['budget']

            if 'address' in d and d['address']:
                ac.address = d['address']

            if 'lng_lat' in d and d['lng_lat']:
                ac.lng_lat = d['lng_lat']

            if 'remark' in d and d['remark']:
                ac.remark = d['remark']

            if 'agent_id' in d and d['agent_id']:
                ac.agent_id = d['agent_id']

            if 'product_series' in d and d['product_series']:
                ac.product_series = d['product_series']

            if 'forms' in d and d['forms']:
                ac.forms = d['forms']

            if 'status' in d and d['status']:
                ac.status = d['status']
            if 'reason' in d and d['reason']:
                ac.reason = d['reason']
            if 'annotation' in d and d['annotation']:
                ac.annotation = d['annotation']
            if 'permiter_id' in d and d['permiter_id']:
                ac.permit_tm = datetime.datetime.now()
                ac.permiter_id = d['permiter_id']

            ac.save()

            if 'photos' in d:
                photos = d['photos']

                for i in range(len(photos)):
                    photo = photos[i]
                    if 'row_id' in photo and photo['row_id']:
                        ap = Action_Picture(id=photo['row_id'])
                        if 'delete' in photo and photo['delete']:
                            ap.delete()
                            continue
                    else:
                        ap = Action_Picture()

                    ap.action_id = ac.id
                    ap.photo = photo['url']
                    ap.tm = datetime.datetime.now()
                    ap.save()


        else:
            res['e'] = '数据丢失'
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)


def ajaxActionList(request):
    data = {
        'e': '',
        'list': [],
        'un_permit': [],
        'permited': []
    }
    uid = request.GET.get('uid', '')
    isall = request.GET.get('all', '')
    company_id = request.GET.get('company_id', '')
    tm_start = request.GET.get('tm_start', '')
    tm_end = request.GET.get('tm_end', '')
    if uid and company_id:
        cur = connection.cursor()
        sWhere = f" where applyer_id = {uid}"
        if isall == "1":
            sWhere = f" where company_id = {company_id}"
        if tm_start and tm_end:
            sWhere = sWhere + f" and tm >= '{tm_start}' and tm<= '{tm_end}'"

        sql = "select id,(select name from sales_action_category where id = category_id)," + \
              "digest,coalesce(address,''),budget," + \
              "to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
              "(select last_name from company_user where id = applyer_id)," + \
              "coalesce(to_char(permit_tm,'yyyy-mm-dd HH24:MI:SS'),''),status,reason,remark," + \
              "coalesce((select name from company_company where id = agent_id),''), " + \
              "array_to_string(array(select name from product_series where id in (select unnest(product_series))),','),annotation " + \
              " from sales_action " + sWhere
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            item = {
                'id': r[0],
                'category_name': r[1],
                'digest': r[2],
                'address': r[3],
                'budget': r[4],
                'tm': r[5],
                'username': r[6],
                'permit_tm': r[7],
                'status': r[8],
                'reason': r[9],
                'remark': r[10],
                'agent_name': r[11],
                'product_series_name': r[12],
                'annotation': r[13]
            }

            # data['list'].append(item)

            if r[7] == '' or r[8] == 0:
                data['un_permit'].append(item)
            else:
                data['permited'].append(item)

    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


def ajaxActionDetail(request):
    data = {
        'e': '',
        'detail': {
            'photos': [],
            'info': None
        }
    }
    id = request.GET.get('id', '')
    if id:
        cur = connection.cursor()
        sWhere = f" where action_id = {id}"
        cur.execute("select id, photo, remark from sales_action_picture " + sWhere)
        rs = cur.fetchall()
        photos = []
        for r in rs:
            photos.append({
                'row_id': r[0],
                'url': r[1],
                'remark': r[2]
            })
        data['detail']['photos'] = photos

        sql = "select id,(select name from sales_action_category where id = category_id)," + \
              "digest,coalesce(address,''),budget," + \
              "to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
              "(select username from company_user where id = applyer_id)," + \
              "coalesce(to_char(permit_tm,'yyyy-mm-dd HH24:MI:SS'),''),status,reason,forms,category_id,lng_lat," + \
              "remark, agent_id,coalesce((select name from company_company where id = agent_id),''),product_series, " + \
              "array_to_string(array(select name from product_series where id in (select unnest(product_series))),','),annotation " + \
              " from sales_action where id =" + id

        cur.execute(sql)
        rs = cur.fetchall()
        if rs:
            r = rs[0]
            item = {
                'id': r[0],
                'category_name': r[1],
                'digest': r[2],
                'address': r[3],
                'budget': r[4],
                'tm': r[5],
                'username': r[6],
                'permit_tm': r[7],
                'status': r[8],
                'reason': r[9],
                'forms': r[10],
                'category_id': r[11],
                'lng_lat': r[12],
                'remark': r[13],
                'agent_id': r[14],
                'agent_name': r[15],
                'product_series': r[16],
                'product_series_name': r[17],
                'annotation': r[18]
            }
            data['detail']['info'] = item


    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)


def ajaxActionCancel(request):
    res = {
        'e': ''
    }
    id = request.GET.get('id', '')
    if id:
        obj = Action.objects.get(id=id)
        if obj.status == 0:
            obj.delete()
        else:
            data['e'] = '无法删除已审核申请'
    else:
        data['e'] = '数据丢失'

    return JsonResponse(res)


# 2022-05-05
def bugsell_sms(request, method='sms'):
    data = {'e': '', 'users': []}
    record_id = request.GET.get('record_id', '')
    ancestor_id = request.GET.get('ancestor_id', '')
    cs = Company.objects.filter(id=int(ancestor_id))

    if not cs:
        data['e'] = 'ancestor_id is error'
    else:
        c = cs[0]
        schemas = CompanyCfgOpt.objects.filter(company_id=int(ancestor_id), configure_id=1)
        if not schemas:
            data['e'] = '企业为设置窜货预警授权方案'
            return JsonResponse(data)

        opt = schemas[0].option
        cur = connection.cursor()
        s = "select c.name,to_char(b.tm,'yyyy-mm-dd hh24:mi:ss'),b.address,label_code," + \
            "(select name from product_product where id=product_id)," + \
            "array_to_string(array(select name from gis.adm where array[id] @> (select adm_ids)),',')," + \
            "coalesce(division_id,0),coalesce(sub_division_id,0) " + \
            "from " + \
            "(select label_code,address,tm,product_id,agent_id FROM sales_bugsell where id=" + record_id + ") b " + \
            "left outer join " + \
            "(select id,name,adm_ids,division_id,sub_division_id from company_company where ancestor_id=" + ancestor_id + ") c " + \
            "on b.agent_id=c.id"
        cur.execute(s)
        r = cur.fetchone()

        # print(r)

        if r:
            agent = r[0]
            tm = r[1]
            address = r[2]
            label = r[3]
            product = r[4]
            area = r[5]
            div_id = r[6]
            subdiv_id = r[7]
            users = []

            # 1;"按产品管理" #3;"按战区分区管理" #6;"按经销商" #8;"按产品系列管理"
            if opt.id == 3:
                # SELECT id, module, module_name, code, name  FROM logistics.company_configure;
                # 1;"sales";"营销管理";"bugsell";"窜货预警"
                s = "select o.user_id,u.last_name,coalesce(u.phone),coalesce(u.wx_openid) " + \
                    "from " + \
                    "(select user_id from company_usercfgopt where company_id=" + ancestor_id + " and configure_id=1 and " + \
                    "(" + \
                    "value->'divs' @> '[{\"id\":\"" + str(div_id) + "\"}]' " + \
                    " or " + \
                    "value->'subdivs' @> '[{\"id\":\"" + str(subdiv_id) + "\"}]' " + \
                    ")" + \
                    ") o " + \
                    "left outer join " + \
                    "(select id,username,last_name,phone,wx_openid from company_user where company_id=" + ancestor_id + ") u " + \
                    "on o.user_id=u.id"
                cur.execute(s)
                for r in cur.fetchall():
                    users.append({"name": r[1], "phone": r[2]})
            if not users:
                data['e'] = '找不到对应稽察人员，请检查稽察授权设置是否正确。'
            else:
                #if int(ancestor_id) == 16687:
                #    method = 'wx'
                # 手机短信通知
                if method == 'sms':
                    for u in users:
                        if u['phone']:
                            phone = u['phone']
                            msg = "发经销商 " + agent + "(授权区域" + area + ") " + product + ",被消费者在 " + address + \
                                  " 扫码. 标签:" + label + ",时间:" + tm
                            status = send_sms(phone, msg)
                            if status == 200:
                                data['users'].append(u['name'])
                # 微信模板通知
                elif method == 'wx':
                    res = send_wechat_message_template()
                    wx_res = json.loads(res.content)
                    if res.status_code ==200 :
                        if   wx_res['errcode'] == 0:
                            data['e'] =''
                        else:
                            data['e'] = '请检查稽查人员授权信息！'
                    else:
                        data['e'] = '请检查稽查人员授权信息！'

        cur.close()
    return JsonResponse(data)


# 2022-06-11
def sms_ancestor(request, what, ancestor_id, record_id):
    data = {'e': '', 'users': []}
    cs = Company.objects.filter(id=int(ancestor_id))
    method = request.GET.get('method', 'wx')
    # 目只发窜货预警，假货预警微信模板消息
    objs = ['bugsell', 'fakelabel']

    if what == 'bugsell':
        w = '窜货'
    elif what == 'fakelabel':
        w = '假货'
    else:
        data['e'] = 'object error'
        return JsonResponse(data)

    if not cs:
        data['e'] = 'ancestor_id is error'
    else:
        c = cs[0]
        schemas = CompanyCfgOpt.objects.filter(company_id=int(ancestor_id), configure_id=1)
        if not schemas:
            data['e'] = '企业为设置' + w + '预警授权方案'
            return JsonResponse(data)

        opt = schemas[0].option
        cur = connection.cursor()
        s = "select c.name,to_char(b.tm,'yyyy-mm-dd hh24:mi:ss'),b.address,label_code," + \
            "coalesce((select name from product_product where id=product_id),'')," + \
            "array_to_string(array(select name from gis.adm where array[id] @> (select adm_ids)),',')," + \
            "coalesce(division_id,0),coalesce(sub_division_id,0) " + \
            "from " + \
            "(select label_code,address,tm,product_id,agent_id FROM sales_" + what + " where id=" + record_id + ") b " + \
            "left outer join " + \
            "(select id,name,adm_ids,division_id,sub_division_id from company_company where ancestor_id=" + ancestor_id + ") c " + \
            "on b.agent_id=c.id"
        cur.execute(s)
        r = cur.fetchone()
        if r:
            agent = r[0]
            tm = r[1]
            address = r[2]
            label = r[3]
            product = r[4]
            area = r[5]
            div_id = r[6]
            subdiv_id = r[7]
            users = []

            # 1;"按产品管理" #3;"按战区分区管理" #6;"按经销商" #8;"按产品系列管理"
            if opt.id == 3:
                # SELECT id, module, module_name, code, name  FROM logistics.company_configure;
                # 1;"sales";"营销管理";"bugsell";"窜货预警"
                s = "select o.user_id,u.last_name,coalesce(u.phone),coalesce(u.wx_openid) " + \
                    "from " + \
                    "(select user_id from company_usercfgopt where company_id=" + ancestor_id + " and configure_id=1 and " + \
                    "(" + \
                    "value->'divs' @> '[{\"id\":\"" + str(div_id) + "\"}]' " + \
                    " or " + \
                    "value->'subdivs' @> '[{\"id\":\"" + str(subdiv_id) + "\"}]' " + \
                    ")" + \
                    ") o " + \
                    "left outer join " + \
                    "(select id,username,last_name,phone,wx_openid from company_user where company_id=" + ancestor_id + ") u " + \
                    "on o.user_id=u.id"
                cur.execute(s)
                for r in cur.fetchall():
                    users.append({"name": r[1], "phone": r[2]})
            if not users:
                data['e'] = '找不到对应稽察人员，请检查稽察授权设置是否正确。'
            else:
                # 手机短信通知
                if method == 'sms':
                    if what == 'bugsell':
                        msg = "发经销商 " + agent + "(授权区域" + area + ") " + product + ",被消费者在 " + address + \
                              " 扫码. 标签:" + label + ",时间:" + tm
                    elif what == 'fakelabel':
                        if product:
                            product = '产品名称:' + product
                        msg = "标签:" + label + " " + product + ",疑似假冒标签。被消费者在 " + address + \
                              " 扫码. 扫码时间:" + tm
                    for u in users:
                        if u['phone']:
                            phone = u['phone']
                            status = send_sms(phone, msg)
                            if status == 200:
                                data['users'].append(u['name'])
                # 微信模板通知
                elif method == 'wx':
                    template_id = 'vwqWmmgLZQ48f3lW75mHu7ZZAVfnW3_Ark2yvrCoSGs'
                    message_data = {
                        "first": {
                            "value": "系统检测到在" + city + "有疑似" + w + "数据出现，请查看。",
                            "color": "#66CC33"
                        },
                        "keyword1": {
                            "value": "云平台" + w + "预警系统",
                            "color": "#272525"
                        },
                        "keyword2": {
                            "value": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                            "color": "#272525"
                        },
                        "keyword3": {
                            "value": "中",
                            "color": "#272525"
                        },
                        "remark": {
                            "value": u"请及时处理",
                            "color": "#272525"
                        }
                    }
                    miniprogram = {
                        'appid': 'wxe9a919e0d3c419ee',
                        'pagepath': 'pages/fakeLabel/fakeLabel'
                    }
                    # 目前演示阶段，只发送表内指定openid
                    s = f"""select openid,wx_account_id from company_userwechatopenids 
                        where company_id = {ancestor_id}
                        and user_id in (SELECT id FROM company_user a WHERE ancestor_id = {ancestor_id} 
                        AND ( 1 IN ( SELECT group_id FROM company_user_groups WHERE user_id = a.ID ) ))
                        """

                    cur.execute(s)
                    rs = cur.fetchall()
                    for r in rs:
                        wechat_message_template_send(r[1], r[0], template_id, message_data, miniprogram)

        cur.close()
    return JsonResponse(data)


# 2022-07-07
def coupon_scan(request):
    # 活动码、瓶盖扫码检查
    data = {'e': '', 'data': {'award': {'name': '', 'points': 0}}}
    e = time_key_check(request, sK)
    e = ''
    if e:
        data['e'] = e
    else:
        label = request.GET.get('label', '')
        uid = request.GET.get('user_id', '')
        agent_id = request.GET.get('agent_id', '')

        if not label or not uid or not agent_id:
            data['e'] = 'label/user id/agent id missing'
            return JsonResponse(data)
        cur = connection.cursor()
        # 检查user_id
        cur.execute("select ancestor_id,company_id from company_user where id=" + uid)
        r = cur.fetchone()
        if not r:
            data['user id error']
            return JsonResponse(data)
        aid = str(r[0])
        cid = r[1]
        s = "select (select name from company_company where id=company_id)," + \
            "(select coalesce(last_name,username) from company_user where id=user_id)," + \
            "to_char(tm,'yyyy-mm-dd HH24:MI:SS') from sales_couponscan " + \
            "where label_code='" + label + "' and ancestor_id=" + aid
        cur.execute(s)
        r = cur.fetchone()
        if r:
            data['e'] = '此码已被扫码'
            d = {'company': r[0], 'user': r[1], 'time': r[2]}
            data['data'] = d
        else:

            # 取标签信息
            q = LabelQuery(int(aid), label)
            if not q.infor['label_pk_id']:
                data['e'] = '标签号码错误'
                return JsonResponse(data)
            p = q.get_product()
            if not p['id']:
                data['e'] = '未知产品'
                return JsonResponse(data)

            i = q.infor

            d = get_activity(aid, label, 0, 0)
            if d['activity']:
                activity = d['activity']
                act_id = activity.id
                activity_award = None
                if d['award']:
                    activity_award = d['award']
                else:
                    activity_award = d['activity'].draw()

                if activity_award:
                    award = activity_award.award

                    award_id = award.id
                    val = str(award.points)
                else:
                    award_id = 0
                    val = '0'

                s = "INSERT INTO sales_couponscan(" + \
                    "val,label_code,label_pkg,label_id,label_pk_id,activity_id," + \
                    "ancestor_id,award_id,company_id,product_id,user_id" + \
                    ") VALUES (" + \
                    val + ",'" + label + "'," + str(q.package['id']) + "," + str(i['label_id']) + "," + str(
                    i['label_pk_id']) + "," + str(activity.id) + "," + \
                    aid + "," + str(award_id) + "," + agent_id + "," + str(p['id']) + "," + uid + \
                    ") returning id"
                cur.execute(s)

                # 更新经销商积分
                update_member_points_agent(int(agent_id), int(val), '在' + activity.name + '活动中获得')
                data['data']['award'] = {'name': award.name, 'point': val}

            else:
                s = "INSERT INTO sales_couponscan(" + \
                    "val,label_code,label_pkg,label_id,label_pk_id," + \
                    "ancestor_id,company_id,product_id,user_id" + \
                    ") VALUES (0,'" + label + "'," + str(q.package['id']) + "," + str(i['label_id']) + "," + str(
                    i['label_pk_id']) + "," + \
                    aid + "," + agent_id + "," + str(p['id']) + "," + uid + \
                    ") returning id"
                cur.execute(s)

    return JsonResponse(data)


def ajaxCouponScanList(request):
    res = {
        'e': '',
        'list': [],
    }
    company_id = request.GET.get('company_id', '')
    uid = request.GET.get('uid', '')
    ancestor_id = request.GET.get('ancestor_id', '')
    tm_start = request.GET.get('tm_start', '')
    tm_end = request.GET.get('tm_end', '')
    use_tm_start = request.GET.get('use_tm_start', '')
    use_tm_end = request.GET.get('use_tm_end', '')

    if ancestor_id:

        sWhere = f" where ancestor_id = {ancestor_id}"
        if company_id:
            sWhere = sWhere + f" and company_id = {company_id}"
        if uid:
            sWhere = sWhere + f" and user_id = {uid}"
        if tm_start and tm_end:
            sWhere = sWhere + f" and tm >= '{tm_start}' and tm<= '{tm_end}'"

        cur = connection.cursor()
        sql = "select id,label_code,(select name from sales_activities where id = activity_id)," + \
              "to_char(tm,'yyyy-mm-dd HH24:MI:SS')," + \
              "(select name from product_product where id = product_id)," + \
              "(select name from sales_award where id = award_id) " + \
              "from sales_couponscan " + sWhere + " order by id desc"
        cur.execute(sql)
        rs = cur.fetchall()
        if rs:
            for r in rs:
                item = {
                    'id': r[0],
                    'label_code': r[1],
                    'activity_name': r[2],
                    'tm': r[3],
                    'product_name': r[4],
                    'award_name': r[5],
                }

                res['list'].append(item)
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)


def get_activity(company_id, label_code, lng=0, lat=0):
    data = {
        'label_type': '',
        'activity': None,
        'award': None,
        'seeds_id': None,
        'package_id': 0,
        'product_name': '',
        'product_id': 0,
        'agent_id': '',
        'batch_no': '',
        'e': ''
    }

    company_id = str(company_id)
    cur = connection.cursor()
    ancestor_id = get_ancestorId(company_id)
    # 抽奖活动
    cur.execute("select inv_mgt from company_companycfg where company_id=" + company_id)
    r = cur.fetchone()
    # 消费者抽奖活动，
    product_id = 0
    package_id = 0
    pk_id = '0'
    if r and r[0]:
        objs = Company.objects.filter(id=int(company_id))
        if objs:
            company = objs[0]
            d = label_sys_info(label_code, company, has_price=False)
            product_id = d['product']['id']
            package_id = d['package']['id']
            data['product_id'] = d['product']['id']
            data['package_id'] = package_id
            data['product_name'] = d['product']['name']
            data['batch_no'] = d['qc']
            data['e'] = d['e']
            pk_id = str(d['label_pk_id'])

            stock_dev = d['stock_dev']
            stock_dev_len = len(stock_dev)
            if stock_dev_len > 0:
                agent = stock_dev[stock_dev_len - 1]['company_id']
                if agent:
                    data['agent_id'] = agent

    tm = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    sWhere = " where company_id=" + company_id + " and status=1 and target =2 and ('" + tm + "' between tm_start and tm_end) " + \
             " and lblpkg_id=" + str(package_id) + " "

    s = "select id,priority from sales_activities " + sWhere + \
        "and case when array_length(products,1) is null then true else ARRAY[" + str(
        product_id) + "] <@ products end " + \
        "and case when array_length(agents,1) is null then true else " + \
        "array(select company_to_id from stkdetails.c" + ancestor_id + " where ancestor_id=" + company_id + " and label_pk_id=" + pk_id + ") && agents end " + \
        "order by priority desc limit 1"

    cur.execute(s)
    r = cur.fetchone()
    if r:
        data['activity'] = Activities.objects.get(id=r[0])
    cur.close()

    return data


@login_required
def withdrawList(request, obj):
    data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['', ''], 'murl': '', 'dt': False, 'add': True}
    cur = connection.cursor()

    if obj == "apply":

        data['subtt'] = ['营销活动', '提现管理']
        data['clmns'] = ['申请单位', '申请人', '金额', '原因', '备注', '状态', '申请时间', '操作']

        data['dt'] = True

        dt_default = datetime.datetime.now().strftime('%Y-%m-%d')
        dt_fr_default = (datetime.datetime.now() - datetime.timedelta(days=15)).strftime('%Y-%m-%d')
        dt_fr = request.GET.get('date_from', dt_fr_default)
        dt_to = request.GET.get('date_to', dt_default)
        data["date_from"] = dt_fr
        data["date_to"] = dt_to
        ancestor_id = request.user.ancestor_id
        sWhere = f" where tm::date >= '{dt_fr}' and tm::date <= '{dt_to}' and ancestor_id = {ancestor_id}"

        sql = f"""
            select id,
                   (select name from company_company where id = company_id),
                   (select last_name from company_user where id = user_id),
                   amount,
                   coalesce(reason,''),
                   coalesce(remark,''),
                   to_char(tm,'yyyy-mm-dd HH24:MI:SS'),
                   state
            from sales_withdraw 
            {sWhere}
        """
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            state = r[7]
            btn = ''
            if state == 0:
                state = '未审核'
                btn = "<a target='_blank' class='btn btn-default btn-sm btn-permit' data-id='" + str(r[0]) + "'>通过</a>"
            elif state == 1:
                state = '通过'
            elif state == 2:
                state = '未通过'
            money=f"<a href='/sales/withdraw/list/hexiaoRecord/?withdrawId={str(r[0])}' target='_blank' class='btn-dlg'>{str(r[3])}</a>"
            data['data'].append([
                r[1],
                r[2],
                money,
                r[4],
                r[5],
                state,
                r[6],
                btn
            ])
    
    elif obj == 'hexiaoRecord':
        data['subtt'] = ['营销活动', '提现管理','核销详情']
        data['clmns'] = ['经销商名称', '活动名称', '奖品名称', '消费者名称', '消费者手机', '核销时间']
        withdrawId = int(request.GET.get('withdrawId', '0'))
        if withdrawId:
            ancestor_id = request.user.ancestor_id
            sWhere = "company_id = "+str(ancestor_id)+" and withdraw_id = "+str(withdrawId)
            sql = f"""
                select 
                    agent_name,
                    activity_name,
                    award_name, 
                    coalesce(consumer_name,''), 
                    coalesce(consumer_phone,''), 
                    to_char(tm,'yyyy-mm-dd HH24:HI:SS')
                from sales_hexiao_record where {sWhere}
            """
            cur.execute(sql)
            rs = cur.fetchall()
            for r in rs:
                data['data'].append([
                    r[0],
                    r[1],
                    r[2],
                    r[3],
                    r[4],
                    r[5]
                ])
        return render(request, 'sales/list_withdraw_hexiao.html', data)
    
    return render(request, 'sales/list_withdraw.html', data)


@login_required
def withdrawEdit(request, obj):
    data = {
        'e': ''
    }

    if obj == 'review':
        id = request.GET.get('id', '')
        _all = request.GET.get('all', '')
        state = request.GET.get('state', '0')
        ancestor_id = request.user.ancestor_id
        cur = connection.cursor()

        if _all == '1' and state != '0':
            cur.execute(
                f'select amount,openid from sales_withdraw where state = 0 and ancestor_id = {str(ancestor_id)}')
            rs = cur.fetchall()
            transfer_detail_list = []
            for r in rs:
                money = int(r[0] * 100)
                openid = r[1]
                order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace(
                    '.', '')[-7:]
                transfer_detail_list.append({
                    "out_detail_no": order_no,
                    "transfer_amount": money,
                    "transfer_remark": "商家转帐",
                    "openid": openid})

        elif id and state:
            w = Withdraw.objects.get(id=int(id))
            if w.state == 0 and state == '1':
                money = int(w.amount * 100)
                order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace(
                    '.', '')[-7:]
                transfer_detail_list = [{
                    "out_detail_no": order_no,
                    "transfer_amount": money,
                    "transfer_remark": "商家转帐",
                    "openid": w.openid}]
                app_id = ''
                if ancestor_id == 110887:
                    app_id = 'wxe9a919e0d3c419ee'
                code, message = transfer_batch(w.openid, money, ancestor_id, app_id)
                if code == 200:
                    cur.execute(
                        "update sales_hexiao_record set money_returned_tm = now() where withdraw_id = " + str(w.id))
                    w.state = 1
                else:
                    msg = json.loads(message)
                    data['e'] = msg['message']
            w.save()
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '对象不存在'
    return JsonResponse(data)


def set_AwardcatLog(request,obj,money,open_id,remark):
    data={'e':''}
    al = AwardcatLog(consumer=obj.consumer,award_name = obj.award_name,amount=money,open_id=open_id,winner_id=obj.id,remark=remark,company=obj.company,activity_name =obj.activity.name)
    al.save()
    return JsonResponse(data)
    
    
# 当前积分
@login_required
def award_money_list(request):
    data = {'data': [], 'clmns': ['动作', '活动名称', '奖品名称', '金额', '操作人', '操作时间', '备注'], 'e': [],
            'subtt': ['渠道促销', '积分'],   'date_from': '', 'date_to': '', 'amount': 0,
            'show_add': False}
    # data['murl'] = '/company/bonusPoints/edit/'
    cur = connection.cursor()
    company_id = request.user.company_id
    ancestor_id = request.user.ancestor_id
    if ancestor_id == company_id:
        bps = BonusPoints.objects.filter(ancestor_id=ancestor_id)
    else:
        bps = BonusPoints.objects.filter(company_id=company_id)

    dt_default = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr_default = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt_fr_default)
    dt_to = request.GET.get('date_to', dt_default)
    data["date_from"] = dt_fr
    data["date_to"] = dt_to
    sDt = " and  dt between '"+dt_fr+"' and '"+dt_to+"' "
    amount = 0
     
    s = "select a.amount-COALESCE (b.MONEY ,0) from (SELECT sum(amount)amount,company_id from logistics.sales_wallet_amount " +\
        "WHERE company_id = "+str(company_id)+" GROUP BY company_id)A "+\
        "left outer  join (SELECT sum(amount)money,company_id from logistics.sales_awardcatlog WHERE company_id = "+str(company_id)+" GROUP BY company_id)B "+\
        "on b.company_id = a.company_id "
    cur.execute(s)
    money = cur.fetchone()
    if money:
        amount = money[0]
        data['amount']= str(amount)
    s =  "SELECT '消费者领取',coalesce(a.activity_name,''),a.tm,a.remark,a.amount,coalesce(b.wx_nickname,'')," +\
         "coalesce(a.award_name,'') from (select award_name,amount,consumer_id,TO_CHAR(tm,'yyyy-mm-dd HH24:MI:ss')tm,activity_name,remark,winner_id " +\
         "FROM logistics.sales_awardcatlog where company_id = "+str(company_id)+sDt+" )a "+\
        "left outer  join ( SELECT id, wx_nickname  from  sales_ConsumerAccount) b on a.consumer_id = b.id "+\
         " union SELECT '手动调整', case  when amount > 0 then '充值' else '扣减' end, TO_CHAR(tm, 'yyyy-mm-dd HH24:MI:SS')"+\
        " tm, remark, amount, (select last_name from logistics.company_user where id = user_id), ''"+\
        " from logistics.sales_wallet_amount    WHERE company_id = "+str(company_id)+sDt +" order by tm desc"
    cur.execute(s)
    r = cur.fetchall()
    for i in r:
        data['data'].append([i[0],i[1],i[6],str(i[4]),i[5],i[2],i[3]])
    return render(request, 'obj/list_money.html', data)

@login_required
def Wallet_amount_update(request):
    data={'e':''}
    r = json.loads(request.body)
    u_id = request.user.id
    c = request.user.company
    c_id = c.id
    a_id = c.ancestor_id
    if r:
        remark = r['remark']
        value_type = r['value_type']
        amount = int(r['amount'])
        if value_type == '1':
            wa = Wallet_amount(ancestor_id=a_id,company_id=c_id,remark=remark,amount=amount,user_id=u_id)
        else:
            wa = Wallet_amount(ancestor_id=a_id, company_id=c_id, remark=remark, amount=-amount, user_id=u_id)
        wa.save()
    return  JsonResponse(data)





# 2023-05-06
def consumer_channel_rebate(obj):
    '''
    传LabelScan对像,判断并写入消费者扫码渠道返利
    '''
    company_id=obj.company_id
    consumer_id=obj.consumer_id
    product_id=obj.product_id
    label_code=obj.label_code
    if obj.label_pkg:
        label_pkg = obj.label_pkg
    else:
        label_pkg=0
    pk_id=obj.label_pk_id
    aVals=[]     
    cur=connection.cursor()
    tb='stkdetails.c'+str(company_id)
    # 取最后一次发货记录
    s="select company_to_id,parent_id,level_id,is_terminal,"+\
        "(select level_id from company_company where id=s.parent_id) from "+\
        "(select company_to_id,parent_id from "+tb+" where vtype_id=2 and label_pk_id="+str(pk_id)+\
            " and is_delete=false order by id desc limit 1"+\
        ") s "+\
        "left outer join "+\
        "(select id,level_id,is_terminal from company_company where ancestor_id="+str(company_id)+") c "+\
        "on s.company_to_id=c.id"
    cur.execute(s)
    r=cur.fetchone()
    if r:  
        c_id=r[0]
        p_id=r[1]
        #1;"公司";0   #2;"一级";1    #4;"二级";2    #5;"三级";3
        # 一级：经销商(平台商);     二级：分销商;       三级：终端(门店) 
        lv_id=r[2]
        t=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 先不考虑战区，分区，指定经销商，发货时间 限制
        s="select id,name,awardcategory_id,package_unit,dt_delivery,rebates "+\
            "from sales_channelpromotions p "+\
            "where company_id="+str(company_id)+" and status=1 and scan_type=2 "+\
            "and ('"+t+"' between tm_start and tm_end) "+\
            "and case when array_length(products,1) is null then true else ARRAY["+str(product_id)+"] <@ products end "+\
            "order by priority desc"
        cur.execute(s)
        rr=cur.fetchone()        
        if rr:    
            pid=rr[0]
            rebates=rr[5]
            rebates = json.loads(rebates)
            if lv_id==2:
                # 最后一笔发货是发给一级经销商
                for rb in rebates:
                    if rb['id']==lv_id:
                        aVals.append("("+str(company_id)+","+str(c_id)+","+str(pid)+","+str(obj.id)+","+\
                            str(lv_id)+",'"+label_code+"',"+str(label_pkg)+","+str(rb['value'])+")")
            else:
                # 最后笔发货是发给终端或三级
                if lv_id==5 or r[3]:
                    lv_id=5
                    p_lv_id=r[4]                    
                    for rb in rebates:
                        # 终端返利
                        if rb['id']==lv_id:                                             
                            aVals.append("("+str(company_id)+","+str(c_id)+","+str(pid)+","+str(obj.id)+","+\
                                str(lv_id)+",'"+label_code+"',"+str(label_pkg)+","+str(rb['value'])+")") 
                        # 上级返利
                        if rb['id']==p_lv_id:                                             
                            aVals.append("("+str(company_id)+","+str(p_id)+","+str(pid)+","+str(obj.id)+","+\
                                str(p_lv_id)+",'"+label_code+"',"+str(label_pkg)+","+str(rb['value'])+")") 
    if aVals:
        sIns="INSERT INTO sales_channelrebateconsumer(company_id,agent_id,"+\
            "promotion_id,labelscan_id,level_id,label_code,label_pkg,val)"  
        s=sIns+" values "+",".join(aVals)
        cur.execute(s)
    cur.close()
    return   




# 2023-09-10
from wx.views import gcj02_to_bd09
@csrf_exempt
def label_scan(request,company_id,what=None):
    data={'e':''}    
    scan_types={
        'image':1,          #防伪查询
        'consumer':2,       #消费者扫码
        'inspector':3,      #市场稽查
        'tj':4,             #内部查询
        'app':5,            #android/苹果 app扫码
    }
    scan_type=2
    r = json.loads(request.body)    
    flds=['label_code','label_id','label_pk_id', 'product_id', 'lng_lat']
    e=[]
    for f in flds:
        if f not in r:
            e.append("'f'")
    nfc_code=None
    if what=='nfc':
        scan_type=5
        if 'nfc_code' not in r:
            e.append('nfc_code')
        else:
            nfc_code=r['nfc_code']
    if e:
        data[e]="parameters "+",".join(e)+" required"
        return JsonResponse(data)

    province=None
    city=None
    address=None
    lng_lat=None
    lng=None
    lat=None
    lat_lng=None
    consumer_id=None      
    pos_permission=False
    if r['lng_lat']:
        ll=r['lng_lat'].split(',')
        lng=ll[0]
        lat=ll[1]
        lng_lat = [lng, lat]
    if lng and lat:
        lng_lat = gcj02_to_bd09(float(lng), float(lat))
        headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'}
        url_base = "https://api.map.baidu.com/geocoder/v2/?ak=ASl2xmUaYpjwdWy3GPBQbpUK"
        url = url_base + "&location=" + str(lng_lat[1]) + "," + str(lng_lat[0]) + "&output=json"
        location_result = requests.get(url, headers=headers)
        p = json.loads(location_result.text)   
        if p["status"] == 0:
            province = p['result']['addressComponent']['province']
            city = p['result']['addressComponent']['city']
            district = p['result']['addressComponent']['district']
            address = p['result']['formatted_address']
            pos_permission=True  

    # 是否上传了消费者id
    if 'consumer_id' in r:
        consumer_id=int(r['consumer_id'])   
    label_id=None
    if r['label_id']:
        label_id=int(r['label_id'])
    label_pk_id=None
    if r['label_pk_id']:
        label_pk_id=int(r['label_pk_id'])
    label_pkg_id=None
    if r['label_pkg_id']:
        label_pkg_id=int(r['label_pkg_id'])
    l=LabelScan(
        label_code =r['label_code'], 
        label_pkg = label_pkg_id,
        label_id = label_id,
        label_pk_id = label_pk_id,
        product_id = int(r['product_id']),            
        nfc_code=r['nfc_code'],
        consumer_id=consumer_id, 
        company_id = int(company_id),      
        province = province,
        city = city,
        address = address,
        pos_permission = pos_permission,
        lng_lat = lng_lat,
        scan_type=scan_type
    )
    l.save()    


    # 2023-05-06 判断并处理渠道返利
    try:
        consumer_channel_rebate(l)
    except Exception:
        # 忽略异常
        pass

    return JsonResponse(data)

#2023-06-29
#返利领取明细
def rebate_claim(request,rebate_batch_id):
    data = {'e': '',
            'data': []}
    e = time_key_check(request, sK)
    if e:
        data['e'] = e
        return JsonResponse(data)
    batch_id=rebate_batch_id
    cur = connection.cursor()
    s=f"""
        select label_code,label_pkg,val,
        (select name from  product_product where product_id=id limit 1) from sales_channelrebatedetails 
         where rebate_batch_id={batch_id}   
    """
    cur.execute(s)
    for r in cur.fetchall():
        data['data'].append({
            'code': r[0],       #标签
            'label_pkg': r[1],  # 标签类型
            'val' : r[2] ,     #返利
            'product' :r[3]    #产品名称
        })
    return JsonResponse(data)

# 终端奖池布奖
@login_required
def promotionseeds(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['营销活动', '终端奖池布奖'], 'murl': '', 'dt': True, 'add': True, 'clmns2': [], 'cnts': [],
            'clmns3': [], 'cnts2': []}
    data['clmns'] = ['标签序号', '活动方案', '终端金额', '备注', '时间']
    data['show_add'] = True
    data['murl'] = '/sales/terminal/'
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', dt)
    data["date_from"] = dt_fr
    data["date_to"] = dt_to
    dt_to = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    f = "company_id = " + str(request.user.company.id) + " and tm>='" + dt_fr + "' and tm <='" + dt_to + "'"
    cur = connection.cursor()
    s=f"""select label_code,(select name from sales_channelpromotions where id=promotion_id limit 1),
    terminal_rebate::TEXT,coalesce(remark,''),to_char(tm,'yyyy-mm-dd HH24:MI:SS')
    from sales_promotionseeds  where {f}
    """
    cur.execute(s)
    rs = cur.fetchall()
    for r in rs:
        data['data'].append([
            r[0],
            r[1],
            r[2],
            r[3],
            r[4]
        ])
    data['clmns2'] = ['活动方案', '终端金额', '数量']
    s=f"""
        select promotion_id,terminal_rebate::TEXT,count(id),(select name from sales_channelpromotions where id=promotion_id limit 1)
        from sales_promotionseeds where {f} group by promotion_id,terminal_rebate
    """
    cur.execute(s)
    rs = cur.fetchall()
    for r in rs:
        data['cnts'].append([
            r[3],
            r[1],
            r[2]
        ])
    data['clmns3'] = ['批次', '经销商', '金额', '数量', '合计']

    return render(request, 'sales/promotionseeds.html', data)

# 终端布奖页面
@login_required
def terminal(request, id=None):
    data = {
        'activites': [],
        'promotions':[]
    }
    promotions=ChannelPromotions.objects.filter(company_id=request.user.company.id)
    activites = Activities.objects.filter(company_id=request.user.company.id)
    if activites:
        for a in activites:
            data['activites'].append({
                'name': a.name,
                'id': a.id
            })
    if promotions:
        for a in promotions:
            data['promotions'].append({
                'name':a.name,
                'id':a.id
            })
    return render(request, 'sales/terminal.html', data)


@tj_login_required
@csrf_exempt
def batch_terminal(request):
    data = {
        'e': '',
        'batch': [],
        'dataset': []
    }
    code = request.GET.get('code', '')
    batch_id = request.GET.get('batch_id', '')
    x = batch_id[0:-1]
    # 2022-10-29 stkdetails分表
    # aid=s

    cur = connection.cursor()
    if code:
        code = code.split(',')
        i = 0
        while i < len(code):
            s = f"""
                SELECT id,tm,(select name from company_company where id = company_fr_id),
                (select name from company_company where id = company_to_id),
                level_id,(select name from inventory_voucher where id = vtype_id),code FROM inventory_batch where code ='{code[i]}' and vtype_id=2
            """
            cur.execute(s)
            rs = cur.fetchall()
            i += 1
            if rs:
                for r in rs:
                    data['batch'].append({
                        'id': r[0],
                        'tm': r[1].strftime("%Y-%m-%d %H:%M:%S"),
                        'comp_fr': r[2],
                        'comp_to': r[3],
                        'level_id': r[4],
                        'vtype': r[5],
                        'now_code': r[6]
                    })
            else:
                data['e'] = '查询不到订单'
    elif batch_id:
        batch = batch_id.split(',')
        # 2022-10-29 stkdetails分表
        batch = Batch.objects.get(id=int(batch[0]))
        aid = str(batch.ancestor_id)
        tb_stk = "stkdetails.c" + aid
        s = f"""
            select count(*) from {tb_stk} where batch_id in ({x}) and label_pkg = 3
        """
        # cur.execute("select count(*) from "+tb_stk+" where batch_id in "+batch_id +" and label_pkg = 3")
        cur.execute(s)
        r = cur.fetchone()
        data['box_num'] = r[0]
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)

# 终端进行布奖
@tj_login_required
@csrf_exempt
def PromotionSeeds_lottery(request):
    data = {
        'e': ''
    }
    activity_id = request.POST.get('activity_id', '')
    promotion_id = request.POST.get('promotions_id','')
    batch_id = request.POST.get('batch_id', '')
    batch = batch_id.split(',')
    batch_id = batch_id[0:-1]
    awards_ = request.POST.get('awards', '')
    remark = request.POST.get('remark', '')
    lotteryMethod = request.POST.get('lotteryMethod', '')
    abcode = request.POST.get('abcode', 'A')
    company_id = request.user.company.id
    ancestor_id = get_ancestorId(company_id)
    # is_terminal_rebate = request.POST.get('is_terminal_rebate', '')

    if activity_id and batch_id and awards_:
        awards = json.loads(awards_)
        cur = connection.cursor()
        if lotteryMethod == "1":
            codesql = "code"
            if abcode == 'B':
                codesql = "(select code_b from label.lbl_abcode where code_a = code)"
            cur.execute(
                f"""
                select {codesql},id,package_id,parent_id,
                (select code from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.id)),
                 (select company_to_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.id)),
                 (select product_id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.id)),
                 (select id from logistics.inventory_batch where id=(select batch_id from stkdetails.c{ancestor_id} where batch_id in({batch_id}) and label_id=a.id))
                 from label.labelinfo a where id in (SELECT label_id from stkdetails.c{ancestor_id} WHERE batch_id in({batch_id})) and package_id=3
                """);
            rs = cur.fetchall()
            shuffle(rs)
            i = 0
            for r in awards:
                award_id = r['award_id']
                num = r['num']
                for n in range(0, num):
                    s=f"""
                        select  amount  from sales_award where id=(select award_id from sales_activityAwards  where id={award_id} )              
                    """
                    cur.execute(s)
                    x=cur.fetchone()
                    s = PromotionSeeds(
                        company_id=company_id,
                        # activity_id=activity_id,
                        terminal_rebate=x[0],
                        # award_id=award_id,
                        label_code=rs[i][0],
                        label_pkg=rs[i][2],
                        label_id=rs[i][1],
                        label_pk_id=rs[i][3],
                        product_id=rs[i][6],
                        remark=remark,
                        promotion_id=promotion_id,
                        # agent_id=rs[i][5],
                        # batch_no=rs[i][4],
                        # batch_id=rs[i][7],
                    )
                    s.save()
                    i = i + 1

    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)