# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#from rest_framework import viewsets
# from rest_framework import permissions
from .serializers import *
from .models import *
import json
from django.utils.translation import gettext_lazy as _
import psycopg2

from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from utils import *
from datacenter.settings import JG_K,SPECIAL_COMPANIES,WULIU_STR,SYNC_JG_TY,TY_WULIU_STR,MEDIA_ROOT
from django.apps import apps
from utils.views import *
from sales.models import Activities, Action
from django.contrib.auth.decorators import login_required,user_passes_test
from django.contrib.auth import authenticate, login, logout
from .forms import *
from django.db import connection
from product.models import *
from product.forms import *
from django.utils.safestring import SafeString
from django.shortcuts import redirect

#from django.shortcuts import render_to_response
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.template import RequestContext
import requests
from django.db.models import Q

from django.shortcuts import redirect
from django.contrib.auth.models import Group
import os

from inventory.models import Batch

#2021-02-25
import uuid

from rbac.views import *
import xlrd
from xlrd import *

#from django.core.context_processors import csrf
#from django.template.context_processors import csrf


# from django.forms.models import inlineformset_factory, formset_factory

from urllib.parse import quote


# 2023-08-25 8月25号以后，行政区划不再查询 gis.adm 而是使用 gis.adm_map_cn
tb_gis='gis.adm_map_cn'


# 2022-10-27
def check_enterprise_tb(company_id):
    """
    为保障查询速度，一些大数据要分表操作    建立企业帐号时，运行此函数    
    """
    cur=connection.cursor()
    id=str(company_id)
    # 指定schema下，查看以该企业ID命名的表，不存在则创建表及其索引
    
    # stock		库存期结明细
    t='stock'    
    s="select count(*) from information_schema.tables where table_schema='"+t+"' and table_type='BASE TABLE' and table_name='c"+id+"'"
    cur.execute(s)
    r=cur.fetchone()
    

    
    
    # batchlot		产品生产批次（保质期）明细
    
    # stkdetails	出入库明细



    cur.close()
    return








# 扫码枪MD5前缀
sK = 'fgfdvgu$#&3t@j'
'''
class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer


class CompanyViewSet(TjViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer


class CategoryPropViewSet(viewsets.ModelViewSet):   
    queryset = CategoryProp.objects.all()
    serializer_class = CategoryPropSerializer
'''
def user_logout(request):
    logout(request)
    s = _('您已退出登录')

    #2020-10-13
    # response = HttpResponse(s)
    response = HttpResponseRedirect('/')

    if request.COOKIES.get('user_id',''):
        response.delete_cookie('user_id')
        #response.set_cookie('user_id', 0, expires=60 * 60 * 24 * 7)
    return response
    #return ('/')




# 扫码枪登录
def app_login(request,thirdparty=None):
    data = {'user_id':0, 'user_name':'','company_id':0, 'e':'','company_name':'','storehouse':[],
            'is_manufacturing':False,'has_plants':False,'roles':[],'ancestor_id':0 }
    
    # 2023-09-01 第三方APP登录 
    if thirdparty:
        if thirdparty in settings.THIRDPARTY_KEYS:
            k=settings.THIRDPARTY_KEYS[thirdparty]
        else:            
            return JsonResponse({'e': '无效的第三方'})
    else:
        k = sK
    


    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    usr = request.GET.get('user', '')
    pwd = request.GET.get('password', '')
    user = authenticate(username=usr, password=pwd)
    if user is not None and user.is_active:
        for o in user.storehouse_set.all():
            data['storehouse'].append({'id':o.id,'name':o.name})            
        data['user_id'] = user.id
        data['user_name']=user.last_name
        data['level']=user.company.level.sn
        data['company_id'] = user.company.id
        data['company_name'] = user.company.name
        data['is_manufacturing']=user.company.is_manufacturing      
        data['has_plants']=user.company.has_plant
        data['ancestor_id']=user.company.ancestor_id
        for g in user.groups.all():
            data['roles'].append(g.name)

    else:
        data['e'] = '帐号或密码错误'
    return JsonResponse(data)


def tj_os_login(request):
    uid=request.GET.get('uid',0)
    users = User.objects.filter(legacy_id=int(uid))
    #tk='null'
    if users:
        user = users[0]
        uid = encrypt_p(str(user.id))
        #tk=csrf(request)["csrf_token"]  

        #2019-08-21
        login(request,user)
        
    #return render(request, 'tj_os_login.html', {'uid': uid,'csrftoken':tk})
    #print('csrftoken:',request.META['CSRF_COOKIE'])
    #print('sessionid:',request.session.session_key)
    #tk=request.META['CSRF_COOKIE']
    #sk=request.session.session_key


    #return render(request, 'tj_os_login.html', {'uid': uid,'csrftoken':tk,'sessionid':sk})
    return render(request, 'tj_os_login.html', {'uid': uid})


def accounts_login(request):
    e = ''
    if request.method == 'GET':
        nxt = request.GET.get('next', '')
    else:
        nxt = request.POST.get('next', '')
        usr = request.POST.get('usr', '')
        pwd = request.POST.get('pwd', '')
        user = authenticate(username=usr, password=pwd)
        if user is not None and user.is_active:
            # 2023年7月18日起，天鉴系统禁用掉内参销售公司旗下经销商、终端店全部用户的小程序和后台账号登录权限。总部登录权限不受影响。
            if user.ancestor_id==1644 and user.company_id!=1644:               
                e='当前帐号登录受限'
            else:
                login(request, user)
                return HttpResponseRedirect(nxt)            
        else:
            e = _('用户帐号或密码错误!')
   
    return render(request, 'login.html', {'next': nxt, 'e': e})


def user_login(request):
    
    uid = request.GET.get('uid',0)
    e = []
    if uid:
        #return render(request, 'login.html', {'next': '/'})
        users =User.objects.filter(legacy_id=int(uid))
        response = HttpResponse('')
        if users:
            user = users[0]
            login(request, user)
            #request.user = user
            ck = encrypt_p(str(user.id))
        else:
            ck = ""
        response["P3P"] = 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'
        response.set_cookie('user_id', ck, expires=60 * 60 * 24 * 7) 

        
        

        return response
    else:
        usr = request.POST.get('usr', '')
        pwd = request.POST.get('pwd', '')
        user = authenticate(username=usr, password=pwd)
        if user:
            if user.check_password(pwd):
                if user.is_active:
                    login(request, user)
                else:
                    e = [_('此帐号已失效!!!!!')]
            else:
                e = [_('用户名或密码不正确!'), ]
        else:
            e = [_('用户名或密码不正确!'), ]

    
    return HttpResponse(json.dumps({'e': e}, ensure_ascii=False))


@login_required
@csrf_exempt
def user_chgpwd(request):
    e = ''
    if request.method == 'GET':
        nxt = request.GET.get('next', '')
    else:
        u = request.user
        oldpassword = request.POST.get('pwd0', '')
        newpassword = request.POST.get('pwd1', '')
        nxt = request.POST.get('next', '')
        user = authenticate(username=u.username, password=oldpassword)
        if user is not None and user.is_active:
            user.set_password(newpassword)
            user.pwd_changed=True
            user.save()

            # 写入SQLSERVER
            #cn = pyodbc.connect(WULIU_STR)
            #cur = cn.cursor()
            #s = "update TJMarketingSystemYin.dbo.TJ_User set PassWords='" + md5_password(newpassword)+ "' " + \
            #    "where pg_stk_id=" + str(u.id)
            #cur.execute(s)
            #cn.commit()
            
            return HttpResponseRedirect(nxt)
        else:
            e = _('用户帐号或原密码错误!')
    return render(request, 'chgpwd.html', {'next': nxt, 'e': e})


#@login_required
@tj_login_required
def home(request):
    is_os = False;    
    
    #tk=csrf(request)["csrf_token"]
    tk = request.COOKIES.get('user_id', '')
    if tk:
        if not tk.isdigit():
            is_os = True
    c=request.user.company
    #return render(request, 'home.html',{'is_os': is_os,'csrftoken':tk})
    company_logo=''
    cur = connection.cursor()
    a_id=0
    if c:
        a_id=c.ancestor_id
    cur.execute("select img_logo from company_company where id="+str(a_id))
    r=cur.fetchone()
    if r:
        if r[0]:
            company_logo=r[0]
        else:
            company_logo="logo/logo_tj.png"
    else:
        company_logo="logo/logo_tj.png"
    
    
    #sys_admin
    #if request.user.id==3506:
    #    html='sys_admin.html'
    #jg_maketing
    #elif request.user.id==4752:
    #    html="marketing_home.html"
    #else:
    #    html='home.html'



    




    #2021-09-16
    menuitems=[]
    cfg=CompanyCfg.objects.get(company_id=a_id)
    #sys_admin
    if request.user.id==3506:
        html='sys_admin.html'
    else:
        if cfg.menu_type==1:
            html='index.html'
            m=MenuCompany(company_id=a_id,cgroup_id=None,user_id=request.user.id)
            only_authorized=True
            if request.user.has_perm('company.sys_admin'):
                only_authorized=False
            menuitems=m.get_user_menu(only_authorized=only_authorized)     
        else:
            if request.user.id==4752:
                html="marketing_home.html"
            else:
                html='home.html'
    
    #2021-04-19
    is_salesman=False
    
    u=request.user
    #用户组别
    group_ids=[]

    cur.execute("select group_id FROM company_user_groups where user_id="+str(request.user.id))
    for r in cur.fetchall():
        group_ids.append(r[0])
    #8;"业务员" 12;"销售助理"  4;"系统管理员"
    if 4 not in group_ids:
        if 8 in group_ids:   
            is_salesman=True
    cur.close()
        
    return render(request, html,{'is_os':is_os,'company_logo':company_logo,'is_salesman':is_salesman,'menuitems':menuitems})


#2021-05-04
@login_required
def index(request):   
    u=request.user
    c=request.user.company
    #return render(request, 'home.html',{'is_os': is_os,'csrftoken':tk})
    company_logo=''
    cur = connection.cursor()
    a_id=0
    if c:
        a_id=c.ancestor_id
    cur.execute("select img_logo from company_company where id="+str(a_id))
    r=cur.fetchone()
    if r:
        if r[0]:
            company_logo=r[0]
        else:
            company_logo="logo/logo_tj.png"
    else:
        company_logo="logo/logo_tj.png"    
    
    #sys_admin
    if request.user.id==3506:
        html='sys_admin.html'    
    else:
        html='index.html'
    
   
    #m=RbacMenu(company=None,cgroup=None,user=request.user)
    #menuitems=m.get_menu()     

    only_authorized=True
    if u.has_perm('company.sys_admin'):
        only_authorized=False
    m=MenuCompany(company_id=a_id,user_id=u.id)

    menuitems=m.get_user_menu(only_authorized=only_authorized) 

   
    cur.close()          
    return render(request, html,{'company_logo':company_logo,'menuitems':menuitems})






def get_obj_special(company_id, obj):
    data = {'e': '', 'data': []}
    # 酒鬼内参ID:2011, 经销商使用酒鬼经销商，产品使用酒鬼酒的产品名称内含“内参”字样; 酒鬼公司ID=1
    if company_id == 2011:
        cur = connection.cursor()
        if obj == 'product':
            cur.execute("select id,name,coalesce(external_code,'') from logistics.product_product " + \
                        "where (company_id=1 and name like '%内参%') or company_id=2011 order by name")
            for r in cur.fetchall():
                data['data'].append({
                    'id':r[0],
                    'name':r[1],
                    'code':r[2]
                })
        elif obj == 'agent':
            cur.execute("select id,name,coalesce(external_code,'') from logistics.company_company " + \
                        "where parent_id in (1,2011) order by name")
            for r in cur.fetchall():
                data['data'].append({
                    'id': r[0],
                    'name': r[1],
                    'code': r[2]
                })
    return JsonResponse(data)


def get_obj_list(request, company_id, obj, thirdparty=None):
    """
    扫码枪数据同步接口
    :param request:
    :param company_id: 公司ID
    :param obj: 对像名
    :return: {'e':'', 'data':[]}
    """
    data = {'e': '', 'data': []}
    d = {
        'product': ['产品', 'product', 'Product'],
        'store': ['仓库', 'inventory', 'Storehouse'],
        'agent': ['经销商', 'company', 'Company'],
        'salesman': ['业务员', 'company', 'User'],
        'terminal': ['终端店', 'company', 'Company'],
        
        'plant': ['厂区', 'company', 'PrdPlant'],
        'prd_workshop': ['车间', 'company', 'PrdWorkshop'],
        'prd_line': ['生产线', 'company', 'PrdLine'],
        'prd_team': ['班组', 'company', 'PrdTeam'],
        
        'qc': ['质检员', 'company', 'PrdQc'],
        'vendor': ['供应商', 'mes', 'Vendor'],
        'activities': ['营销活动', 'sales', 'Activities']
    }

    

    # 2023-09-01 第三方APP登录 
    if thirdparty:
        if thirdparty in settings.THIRDPARTY_KEYS:
            k=settings.THIRDPARTY_KEYS[thirdparty]
        else:            
            return JsonResponse({'e': '无效的第三方'})
    else:
        k = sK


    e = time_key_check(request, k)

    if e:
        data['e'] = e
        return JsonResponse(data)
    if obj not in d:
        data['e'] = _('无效对像名')
        return JsonResponse(data)
    m = apps.get_model(d[obj][1], d[obj][2])
    search_dict = dict()
    photo = request.GET.get('photo','')
    if obj == 'agent':
        c=Company.objects.get(id=int(company_id))
        sWhere=''
        sOrder=' order by name'
        sOrder=' '
        if c.level.sn == 0:
            #2021-05-24 企业取客户信息，不应包含自己,未打删除标记
            sWhere=" where ancestor_id="+str(c.ancestor_id)+" and id<>"+str(c.id)+" and is_delete=false"
            #2021-11-05
            if c.cfg_company.scanner_only_lv1:
                #只同步一级经销商
                sWhere=" where ancestor_id="+str(c.ancestor_id)+" and level_id=2 and is_delete=false"

            if c.id in [20324]: #江口醇：要求把一级经销商放前面
                sOrder=" order by level_id,name"

            # 2022-11-26 山西成兆兴酒业有限公司 100425，工厂发货只发给下面三家经销商
                # 114557;"山西樊王商贸有限公司" 114556;"山西樊王农业科技发展有限公司" 108845;"山西樊王电子商务有限公司" 134480;"山西樊王电子商务体验馆"
            # 2022-12-05 又加3家 2023-01-03 留样室
                #134508;"销售"  134510;"其他"   104617;"赵总"   104618;"留样室"     
            #2023-06-16 又加1家
                #165368;"山西成兆兴销售有限公司"    
            #2023-07-03 客户要求取消部分指定厂家发给经销商，只保留 134508;"销售"  134510;"其他"   104617;"赵总"  104618;"留样室"  165368; "山西成兆兴销售有限公司"
            #2023-07-13 禅道:需添加对应的二级经销商名称为：山西樊王电子商务有限公司
            #2023-09-01 客户要求添加一级经销商名称为：化验室176462
            if c.id==100425:
                sWhere=" where id in (134508,134510,104617,104618,165368, 108845 ,176462)"  
        else:
            # sWhere=" where (parent_id="+str(c.id)+" and id<>"+str(c.id)+")"
            # 2022-11-07
            sWhere=" where (parent_id="+str(c.id)+" or (select parent_id from company_company where id=c.parent_id)="+str(c.id)+") "+\
                "and  id<>"+str(c.id)
            #企业定义了1个下级经销商可以有多个父级
            if c.hierarchy.cfg_company.multi_parents:                
                sWhere=sWhere+" or parents @> '[{\"id\":\""+str(c.id)+"\"}]'"

            # 2022-11-26 山西成兆兴酒业有限公司 100425，下面三家经销商发货，可选成兆兴下所有经销商            
            # 114557;"山西樊王商贸有限公司"
            # 114556;"山西樊王农业科技发展有限公司"
            # 108845;"山西樊王电子商务有限公司"
            # 134480;"山西樊王电子商务体验馆"
            if c.id in (114557,114556,108845,134480):
                sWhere=" where ancestor_id="+str(c.ancestor_id)+" and id not in ("+str(c.id)+","+str(c.ancestor_id)+") and is_delete=false"
        
        cur=connection.cursor()
        saleman_id = request.GET.get('saleman_id','')
        detail = request.GET.get('detail','')
        is_terminal = request.GET.get('is_terminal','')
        if saleman_id:
            cur.execute("SELECT DISTINCT(unnest(user_ids)) FROM company_usersharegroup where ARRAY["+saleman_id+"] <@user_ids")
            rs = cur.fetchall()
            user_ids = []
            for r in rs:
                user_ids.append(r[0])
            uids = ','.join(str(i) for i in user_ids)
            if user_ids:
                sWhere = sWhere + " and id in (select unnest(agent_ids) from company_staffsaldiv where user_id in ("+uids+")) "
            else:
                sWhere = sWhere + " and id in (select unnest(agent_ids) from company_staffsaldiv where user_id = "+saleman_id+") "
        if is_terminal:
            if is_terminal == "1":
                sWhere = sWhere + " and is_terminal = true "
            else:
                sWhere = sWhere + " and is_terminal = false "
        queryThing = ""
        if detail == "1":
            queryThing = ",cell_phone,lng_lat,is_terminal,to_char(tm,'yyyy-mm-dd HH24:MI:SS'),contacts, "+\
                        "(SELECT name from company_channel where id = channel_id),"+\
                        "Array(select name from company_channel_level where id in (select unnest(channel_level_ids))),"+\
                        "Array(select name from product_series where id in (select unnest(series_more))) "
        
        s="select id,name,coalesce(external_code,''),coalesce(log_code,''),"+\
            "(select sn from company_level where id=level_id),address "+queryThing+\
            "from company_company c "+sWhere+sOrder
        
        cur.execute(s)
        for r in cur.fetchall():
            if detail == "1":
                data['data'].append({'id':r[0],
                                    'name':r[1],
                                    'code':r[2],
                                    'level':r[4],
                                    'log_code':r[3],
                                    'address':r[5],
                                    'cell_phone':r[6],
                                    'lng_lat':r[7],
                                    'is_terminal':r[8],
                                    'tm':r[9],
                                    'contacts':r[10],
                                    'channel_name':r[11],
                                    'channel_levels':r[12],
                                    'product_series':r[13]
                                    })
            else:
                data['data'].append({'id':r[0],'name':r[1],'code':r[2],'level':r[4],'log_code':r[3],'address':r[5]})
            
            
        #2020-06-02 张轩：麻烦一下，一级商都添加团购和零售   
        if c.id==1644:
            data['data'].append({'id':11013,'name':'零售','code':'','level':10000,'log_code':''})     
            data['data'].append({'id':11014,'name':'团购','code':'','level':10001,'log_code':''})    
        cur.close()
        return JsonResponse(data)
        #2019-11-14
        #company=Company.objects.get(id=int(company_id))
        #if company.level.sn == 0:
        #    search_dict['hierarchy_id'] = company.hierarchy_id
        #    search_dict['version'] = company.version
        #else:
        #    search_dict['parent_id'] = int(company_id)   


            
    elif obj == 'product':
        is_banquet = request.GET.get('is_banquet','')
        c=Company.objects.get(id=int(company_id))
        cur = connection.cursor()

        """
        if c.is_exclusive:
            s="select id,coalesce(external_code,''),name,coalesce(barcode,''),"+\
                "() "+\
                " from product_product where company_id="+str(c.ancestor_id)
            
            if photo == '1':
                s = "select id,coalesce(external_code,''),name,coalesce(barcode,''),photo,"+\
                    " from product_product where company_id="+str(c.ancestor_id)
            
            if is_banquet == "1":
                s = s + " and is_banquet = true"
               
                
            cur.execute(s)       
            rs=cur.fetchall()
        else:                     
            #s="select a.product_id,b.external_code,b.name from "+\
            #    "(SELECT product_id FROM logistics.company_authorizedproducts where company_id="+str(c.id)+") a "+\
            #"left outer join "+\
            #"(select id,name,external_code from logistics.product_product where company_id="+str(c.ancestor_id)+") b "+\
            #"on a.product_id=b.id"
            #cur.execute(s)       
            #rs=cur.fetchall()
            rs=[]
        if rs:
            d=[]
            if photo == '1':
                for r in rs:
                    d.append({'id':r[0],'code':r[1],'name':r[2],'barcode':r[3],'photo':r[4]})
            else:
                for r in rs:
                    d.append({'id':r[0],'code':r[1],'name':r[2],'barcode':r[3]})
        """        
        #s = "select id,coalesce(external_code,''),name,coalesce(barcode,''),coalesce(photo,''),"+\
        #    "coalesce((select value from product_productprop where id=("+\
        #        "SELECT prd_property_id FROM product_prdprops where product_id=p.id and categoryprop_id=5 and company_id=p.company_id)"+\
        #    "),'') "+\
        #    "from product_product p where company_id="+str(c.ancestor_id)+" and is_delete=false"

    
        # 2022-11-18 categoryprop_id 不同企业类型包装规格ID不同，不能写死
        aid=str(c.ancestor_id)
        s = "select id,coalesce(external_code,''),name,coalesce(barcode,''),coalesce(photo,''),"+\
            "coalesce((select value FROM product_productprop where company_id="+aid+" and categoryprop_id=(SELECT id FROM company_categoryprop where name='package' "+\
                "and  category_id=(select category_id from company_company where id="+aid+")) "+\
	        "and id in (select prd_property_id from product_prdprops where  product_id=p.id)),'') "+\
            ",components from product_product p where company_id="+aid+" and is_delete=false"
        if is_banquet == "1":
            s = s+ ' and is_banquet = true '
            
        cur.execute(s)       
        rs=cur.fetchall()
        if rs:
            d=[]    
            
            for r in rs:
                # 2022-12-10                
                if type(r[6])=='str':
                    cps=json.loads(r[6])
                else:
                    cps=r[6]  
                d.append({'id':r[0],'code':r[1],'name':r[2],'barcode':r[3],'photo':r[4],'specification':r[5],'components':cps})  
            data['data'] = d
            #if is_banquet == "1":   
                
            return JsonResponse(data,safe=False)
            
            #else:
            #    return JsonResponse(data,safe=False)

        else:
            search_dict['company_id']=c.ancestor_id
            search_dict['is_delete']=False
            if is_banquet == "1":
                search_dict['is_banquet']=True
    # 2022-07-07
    elif obj=='activities':  
        c=Company.objects.get(id=int(company_id))
        cur = connection.cursor()
        s="SELECT id,name,priority,to_char(tm_start,'YYYY-mm-dd HH24:MI:SS'),to_char(tm_end,'YYYY-mm-dd HH24:MI:SS') "+\
            "FROM sales_activities where company_id="+str(c.ancestor_id) 
        cur.execute(s)
        d=[]
        for r in cur.fetchall():
            d.append({"id":r[0],"name":r[1],"start_time":r[3],"end_time":r[4]})
        cur.close()
        return JsonResponse(d,safe=False)    
    elif obj == 'salesman':
        cur = connection.cursor()
        cur.execute(f"SELECT id, last_name FROM logistics.company_user where ancestor_id = {company_id} and id in (select user_id from logistics.company_user_groups where group_id=8)")
        rs = cur.fetchall()
        data = []
        if rs:
            for r in rs:
                data.append({
                    'id':r[0],
                    'name':r[1]
                })
        return JsonResponse(data,safe=False)
    #2021-04-25
    #elif obj=='store':
    #    cur = connection.cursor()
    #    cur.execute("select id,name,external_code from inventory_storehouse where company_id="+company_id)
    #    d=[]
    #    for r in cur.fetchall():
    #        d.append({'id':r[0],'name':r[1],'code':r[2]})
    #    cur.close()
    #    return JsonResponse(d,safe=False)
    elif obj == 'terminal':
        search_dict['parent_id'] = int(company_id)
        #search_dict['level_id'] = 3
    else:
        search_dict['company_id'] = int(company_id)
    
    #2019-11-05
    #屏蔽删除标志的记录
    if obj!='plant':
        search_dict['is_delete'] =False

    # 是否需要特殊处理：
    #if int(company_id) in SPECIAL_COMPANIES and obj in ['product','agent']:
    #    return get_obj_special(int(company_id),obj)

    #print('begin')
    for o in m.objects.filter(**search_dict).order_by('id'):
        dct = dict()
        dct['id'] = o.id
        dct['name'] = o.name
        dct['code'] = o.external_code
        #2019-12-23
        if obj=='agent':
            dct['level']=o.level.sn
            dct['log_code']=''
            if o.log_code:
                dct['log_code']=o.log_code
        if obj=='product':
            c=''
            if o.barcode:
                c=o.barcode
            dct['barcode']=c
            
            if photo == '1':
                p = ''
                if o.photo:
                    p = o.photo.url
                dct['photo']=p
        data['data'].append(dct)
    #print('end')
    #2020-05-07 张轩：一级经销商如果没有子级，把团购和零售加上
    #if not data['data'] and obj == 'agent':
    #    data['data']=[
    #        {'id':11013,'name':'零售','code':'','level':10000,'log_code':''},     
    #        {'id':11014,'name':'团购','code':'','level':10001,'log_code':''},   
    #    ]

    
    #2020-06-02 张轩：麻烦一下，一级商都添加团购和零售
    if obj == 'agent':
        data['data'].append({'id':11013,'name':'零售','code':'','level':10000,'log_code':''})     
        data['data'].append({'id':11014,'name':'团购','code':'','level':10001,'log_code':''})     
    # 2022-06-25
    elif obj=='store':
        if not data['data']:
            data['data']={'id':0,'name':'默认仓库','code':''}
        
        # 2022-11-26 山西成兆兴酒业有限公司 100425，下面三家经销商发货，可选成兆兴下仓库            
        # 114557;"山西樊王商贸有限公司"
        # 114556;"山西樊王农业科技发展有限公司"
        # 108845;"山西樊王电子商务有限公司"    
        # 134480;"山西樊王电子商务体验馆"
        if int(company_id) in (114557,114556,108845,134480):
            d=[]
            for o in m.objects.filter(company_id=100425).order_by('id'):
                dct = dict()
                dct['id'] = o.id
                dct['name'] = o.name
                dct['code'] = o.external_code
                d.append(dct)
            data['data']=d
    
    return JsonResponse(data)



#@login_required
@tj_login_required
def list_obj(request, obj):
    categories = []
    plants = []
    workshops = []
    divisions = []
    page = 1
    d = {
        'product': ['产品', 'product', 'Product'],
        'series':['产品系列','product','Series'],
        'store': ['仓库', 'inventory', 'Storehouse'],
        'agent': ['经销商', 'company', 'Company'],
        'terminal': ['终端店', 'company', 'Company'],
        'productprop': ['产品属性', 'product', 'ProductProp'],
        'prd_plant': ['工厂/厂区', 'company', 'PrdPlant'],
        'prd_line': ['生产线', 'company', 'PrdLine'],
        # 'prd_workshop': ['生产班组', 'company', 'PrdWorkshop'],
        'prd_team': ['生产班组', 'company', 'PrdTeam'],
        'prd_qc': ['质检员', 'company', 'PrdQc'],
        'sal_division': ['营销战区', 'company', 'SalesDivision'],
        'sal_subdivision': ['营销分区', 'company', 'SubSalDivision'],
        #2021-01-24
        'wxwalletapp': ['经销商绑定微信钱包申请', 'company', 'WxWalletApplication'],
    }
    if obj not in d:
        return HttpResponse('无效对像名')
    disable_link = False
    company = request.user.company
    company_id = company.id
   

    search_dict = dict()

    if obj== 'sal_subdivision':
        for dv in SalesDivision.objects.filter(company_id=int(company_id)):
            divisions.append([dv.id, dv.name])
        search_dict['company_id'] = int(company_id)
    elif obj == 'agent':        
        if company.level.sn == 0:
            search_dict['hierarchy_id'] = company.hierarchy_id
            search_dict['version'] = company.version
            search_dict['level_id__lte']=12
            #2020-01-13
            search_dict['is_delete'] = False
        else:
            search_dict['parent_id'] = int(company_id)        
    elif obj=='product':
        search_dict['is_delete'] = False
        search_dict['company_id'] = int(company_id)
    #2021-01-24 移到 listobj.views
    #elif obj=='wxwalletapp': 
    #    u=request.user
    #    #权限检查
    #    clmns=["申请时间","申请人","当前状态","上级经销商","所属大区","经销商","收款人微信","手机号码","收款人实名","操作"]
    #    d=[]
    #    if company.level_id==1:
    #        sWhere=" where ancester_id="+str(company.id)
    #    elif company.level_id==2:
    #        sWhere=" where company_id="+str(company.id)+" or (select parent_id from company_company where id=company_id)="+str(company_id)
    #    else:
    #        sWhere=" where company_id="+str(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)        
    #    cur=connection.cursor()
    #    s="select a.id,app_nickname,app_headimgurl,to_char(tm,'yyyy-mm-dd HH24:MI'),c.name,"+\
    #        "w.wx_nickname,w.wx_headimgurl,a.cellpahone,a.realname,"+\
    #        "(select name from company_wxwalletstatus where id=status_id),"+\
    #        "coalesce((select name from company_company where id=c.parent_id),''),"+\
    #        "coalesce((select name from company_salesdivision where id=c.division_id),''),"+\
    #        "(select username from company_user wehre id=app_user_id) "+\
    #        "from "+\
    #        "(select * from company_wxwalletapplication "+sWhere+") a "+\
    #        "left outer join "+\
    #        "(select id,name,parent_id,division_id,sub_division_id from company_company) c "+\
    #        "on a.company_id=c.id "+\
    #        "left outer join "+\
    #        "(select id,wx_nickname,wx_headimgurl from company_wxopenid) w "+\
    #        "on a.app_wxopenid_id=w.id"
    #    cur.execute(s)
    #    for r in cur.fetchall():
    #        d.append([r[0],r[3],r[12]+"<img src='"+r[2]+"'/>"+r[1],
    #            r[9],r[10],r[11],r[4],
    #            "<img src='"+r[6]+"' />"+r[5],
    #            r[7],r[8],''
    #        ])   
    #    return render(request,'/sales/channelrebate/list_wxwallet_application.html',{'clmns':clmns,'data':d})
    else: 
        search_dict['company_id'] = int(company_id)
    for q in request.GET:
        if q == 'page':
            page = request.GET.get(q)
        else:
            search_dict[q] = request.GET.get(q)
    if obj[:4] == 'prd_':
        for plt in PrdPlant.objects.filter(company_id=int(company_id)).order_by('name'):
            plants.append([plt.id, plt.name])
        for w in PrdWorkshop.objects.filter(company_id=int(company_id)).order_by('name'):
            workshops.append([w.id, w.name])
    m = apps.get_model(d[obj][1], d[obj][2])
    orders = ['name']
    if obj == 'productprop':
        categories = CategoryProp.objects.filter(category=company.category)
        objects = m.objects.filter(**search_dict).order_by('value')
    else:
        #2020-03-17
        if obj=='agent':
            objects = m.objects.filter(**search_dict).exclude(id=company_id).order_by(','.join(orders))
        else:
            objects = m.objects.filter(**search_dict).order_by(','.join(orders))
    page_list = Paginator(objects, request=request, per_page=10)
    p_obj = page_list.page(page)

    #传后端的参数，不包含is_delete
    if 'is_delete' in search_dict:
        search_dict.pop('is_delete')

    #return render(request, 'list/obj/' + obj + '_list.html',
    #    {'obj': p_obj, 'page_list': page_list, 'plants': plants, 'workshops': workshops, 'disable_link': disable_link,
    #     'divisions':divisions, 'categories': categories, 'murl': '/company/' + obj + '/', 'params': SafeString(search_dict)}
    #)
    
    #2020-05-01
    return render(request, 'list/obj/' + obj + '_list.html',
        {'obj': p_obj, 'page_list': page_list, 'plants': plants, 'workshops': workshops, 'disable_link': disable_link,
         'divisions':divisions, 'categories': categories, 'murl': '/company/' + obj + '/', 'params': SafeString(search_dict)}
    )


#@login_required
@tj_login_required
@csrf_exempt
def create_user(request):
    c = request.user.company
    company_src = []
    groups=[]    
    is_saved = False

    if request.method == 'GET':
        form = UserForm()          

    elif request.method == "POST":
        group_id = request.POST['group_id']
        form = UserForm(request.POST)        
        if form.is_valid():
            u_name = form.cleaned_data.get('username')
            u_pwd = form.cleaned_data.get('password')            
            u = User(username=u_name, company=Company.objects.get(name=form.cleaned_data.get('company_name'),ancestor_id=c.ancestor_id))
            u.set_password(u_pwd)
            u.save()
            u_id = str(u.id)
            
            gs=Group.objects.filter(id=int(group_id))
            if gs:
                u.groups.add(gs[0])    

            is_saved = True

    for g in Group.objects.all():
        groups.append({'id':g.id,'name':g.name}) 

    s = "select id,name from logistics.company_company where id=" + str(c.id) + " or parent_id=" + str(c.id)
    #2020-01-05
    s = "select id,name from logistics.company_company where ancestor_id=" +  str(c.ancestor_id) 
    cur = connection.cursor()
    cur.execute(s)
    for r in cur.fetchall():
        company_src.append({'label': r[1], 'value': r[0]})
    cur.close()
    return render(request, 'company/create_user.html', {
        'form': form,
        'groups':groups,
        'is_saved':is_saved,
        'company_src': SafeString(company_src)
    })



#@login_required
@tj_login_required
def list_user00(request):
    search_dict = dict()
    c = request.user.company
    page = 1
    cur = connection.cursor()
    a = []
    name_like = ''
    for q in request.GET:
        if q == 'page':
            page = request.GET.get(q)
        elif q == 'username__contains':
            search_dict[q] = request.GET.get(q)
            name_like = " and username like '%" + search_dict[q] + "%'"
    s = "select username,tm," + \
        "(select name from company_company where id=company_id),"+\
        "(select name FROM auth_group where id=(select group_id FROM company_user_groups where user_id=a.id limit 1)),"+\
        "(select cell_phone from company_company where id=company_id) "+\
        " from company_user a " + \
        " where company_id in (select id from company_company where id=" + str(c.id) + \
        " or parent_id=" + str(c.id) + ")" + name_like    
    cur.execute(s)
    for r in cur.fetchall():
        a.append([r[0], r[2], r[1].strftime('%Y-%m-%d %H:%M:%S'),r[3],r[4]])
    cur.close()
    page_list = Paginator(a, request=request, per_page=10)
    p_obj = page_list.page(page)

    return render(request, 'list/obj/user_list.html',
                  {'obj': p_obj, 'page_list': page_list, 'params': SafeString(search_dict)}
    )


@tj_login_required    
def list_user(request):
    data=[]   
    perm_pwd=False
    if request.user.has_perm('company.sys_admin'):
        perm_pwd=True    
    c = request.user.company    
    cur = connection.cursor()   
    sWhere=" where company_id in (select id from company_company where id=" + str(c.id) + " or parent_id=" + str(c.id) + ")"    
    if c.level.sn==0:
        sWhere=" where ancestor_id="+str(c.id)
    s = "select username,tm," + \
        "(select name from company_company where id=company_id),"+\
        "(select name from company_level where id=(select level_id from  company_company where id=company_id)),"+\
        "coalesce((select name FROM auth_group where id=(select group_id FROM company_user_groups where user_id=a.id limit 1)),''),"+\
        "coalesce((select cell_phone from company_company where id=company_id),''),"+\
        "id "+\
        "from company_user a " +sWhere
    cur.execute(s)
    for r in cur.fetchall():
        uname=r[0]
        if perm_pwd:
            uname='<a class="account" uid="'+str(r[6])+'">'+r[0]+'</a>'
        data.append([uname, r[2], r[1].strftime('%Y-%m-%d %H:%M:%S'),r[3],r[4],r[5]])
    cur.close()  
    return render(request, 'list/obj/user_list.html', {'data': SafeString(data)})

@tj_login_required
def json_sub_sal_division(request, division_id):
    data = {'e':'', 'details': []}
    for d in SubSalDivision.objects.filter(division_id=int(division_id)):
        data['details'].append([d.id,d.name])
    return JsonResponse(data)

#2019-12-31 
def json_children(request, company_id):
    data = {'e':'', 'details': []}
    for d in Company.objects.filter(parent_id=int(company_id)):
        data['details'].append([d.id,d.name])
    #团购，零售
    for d in Company.objects.filter(parent_id=None,ancestor_id=None):
        data['details'].append([d.id,d.name])
    return JsonResponse(data)


def child_level(request,company_id):
    data={'level':{},'e':''}
    cs=Company.objects.filter(id=int(company_id))
    if cs:
        data['level']=cs[0].child_level()
    else:
        data['e']=_('公司ID错误')
    return JsonResponse(data)






def wx_longin(request):
    data={
        'e':'',
        'user_id':0,
        'user_name':'',
        'company_id':0,
        'company_name':'',
        'msg':''
    }
    usr=request.GET.get('user','')
    pwd=request.GET.get('password','')
    pwd0=request.GET.get('password_old','')
    pwd1=request.GET.get('password_new','')
    wx_openid=request.GET.get('wx_openid','')
    user=None            
    if usr and pwd:
        user = authenticate(username=usr, password=pwd)
        if user:
            if user.check_password(pwd):
                if user.is_active:
                    user.wx_openid=openid
                    user.save()
                    login(request, user)   
                else:
                    data['e'] = [_('此帐号已失效!!!!!')]
            else:
                data['e'] = [_('用户名或密码不正确!'), ]
        else:
            data['e'] = [_('用户名或密码不正确!'), ]
    else:        
        us=User.objects.filter(wx_openid=wx_openid)
        if us:
            user=us[0]
    if user:
        data['user_id']=user.id
        data['user_name']=user.username
        data['company_id']=user.company.id
        data['company_name']=user.company.name
        if pwd0 and pwd1:
            #修改密码
            user = authenticate(username=usr, password=pwd0)
            if user:
                if user.check_password(pwd0):
                    if user.is_active:
                        user.set_password(pwd1)
                        user.save()
                        data['msg']=_('密码修改成功')  
                    else:
                        data['e'] = [_('此帐号已失效!!!!!')]
                else:
                    data['e'] = [_('用户名或密码不正确!'), ]
            else:
                data['e'] = [_('用户名或密码不正确!'), ]            
    return JsonResponse(data)



@tj_login_required
def InitPassword(request,uid):
    data={'e':''}
    d={
        1:'jg123456',
        1644:'nc123456',
        16716:'yg123456'
    }
    u0=request.user
    if not u0.has_perm('company.sys_admin'):        
        data['e']=_('您当前没有此操作权限')
        return JsonResponse(data)

    

    us=User.objects.filter(id=int(uid))
    if us:
        u=us[0]
        if u.ancestor_id!=u0.ancestor_id:
            data['e']=_('您当前帐号层级错误')
            return JsonResponse(data)

        if u0.ancestor_id in d:
            pwd=d[u0.ancestor_id]
        else:
            pwd='tj123456'
        u.set_password(pwd)
        u.save()
    else:
        data['e']=_('系统无此用户帐号')
    return JsonResponse(data)


#2020-05-15 终端店注册，返回一级经销商信息
def app_get_agent(request,company_id):
    data={'e':'','data':[]}
    k = sK   
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)   
    cur=connection.cursor()
    s="select id,name from logistics.company_company where parent_id="+company_id+" and is_delete=false"+\
        " and (right(name,2) not in ('片区','战区','费用')) and (left(name,4) not in  ('业务费用','业务用酒'))"+\
        " and (left(name,2) not in ('零售')) and level_id=2 and name<>'公司总部'"
    cur.execute(s)
    for r in cur.fetchall():    
        data['data'].append({'id':r[0],'name':r[1]})
    return JsonResponse(data)


@csrf_exempt
def upload_register_img(request,what):
    data={'e':''}
    e = time_key_check(request, sK)
    if e:
        data['e'] = e
        return JsonResponse(data)
    if what not in ['signboard','license']:
        data['e']='wrong url'
        return JsonResponse(data) 
    id=request.POST.get('id','')
    if not id:
        data['e']='id missing'
        return JsonResponse(data)

    ts=TerminalRegister.objects.filter(id=int(id))
    if not ts:
        data['e'] = 'id not exists'
        return JsonResponse(data)
    t=ts[0]
    name=t.name
    a=Company.objects.get(id=t.ancestor_id)
    p = settings.MEDIA_ROOT + '\\' + a.name + '\\register\\'+t.parent.name    
    if not os.path.exists(p):
        os.makedirs(p)
    fp = a.name + '/register/' + t.parent.name +"/"    
    #微信小程序每次只能传1张图片
    img=request.FILES.get('file','')
    if not img:   
        data['e']='未上传图片file'
        return JsonResponse(data)
    fn=name+'_'+what+'.'+img.name.split('.')[-1]
    with open(p +'\\'+ fn, 'wb+') as destination:
        for chunk in img.chunks():
            destination.write(chunk)
    cur=connection.cursor()
    cur.execute("update logistics.company_terminalregister set img_"+what+"='"+fp+fn+"' where id="+id)

    #2020-12-18
    if what=='license':        
        ancestor=a
        if ancestor.id==1644:
            if ancestor.cfg_company.terminal_register_automatic_approve:
                r=terminal_register_approve_automatic(id) 
                
    return JsonResponse(data) 


@csrf_exempt
def upload_img(request,what):
    data={'e':'','url':''}
    e = time_key_check(request, sK)
    if e:
        data['e'] = e
        return JsonResponse(data)
    if what not in ['sales']:
        data['e']='wrong url'
        return JsonResponse(data) 
    uid = request.POST.get('uid','')
    if not uid:
        data['e']='id missing'
        return JsonResponse(data)
    
    u = User.objects.get(id=uid)
    name=u.company.hierarchy.name 
    p = settings.MEDIA_ROOT + '\\' + name + '\\'+what    
    if not os.path.exists(p):
        os.makedirs(p) 
    #微信小程序每次只能传1张图片
    img=request.FILES.get('file','')
    if not img:   
        data['e']='未上传图片file'
        return JsonResponse(data)
    fn= datetime.datetime.now().strftime('%Y-%m-%d%H%M%S%f')+ '.'+img.name.split('.')[-1]
    with open(p +'\\'+ fn, 'wb+') as destination:
        for chunk in img.chunks():
            destination.write(chunk)  
    data['url'] = '/media/'+name+'/'+what+'/'+fn
                
    return JsonResponse(data) 



@csrf_exempt
def terminal_register(request):
    data={'e':'','id':0}
    errs_missing={
        'parent_id': '未指定上级公司',
        'name':'终端店名称不能为空',
        'contacts':'联系人不能为空',
        'cell_phone':'手机号码不能为空',
        'address':'终端店地址不能为空',
        'openid':'wx_openid不能为空'
    }  
    
    #e = time_key_check(request, sK)
    #if e:
    #    data['e'] = e
    #    return JsonResponse(data)



    err=[]
    r=json.loads(request.body)
    for k,v in errs_missing.items():
        if k not in r:
            err.append(v)
    if err:
        data['e']=",".join(err)
        return JsonResponse(data)      
    parent_id=r['parent_id']
    name=r['name']
    contacts=r['contacts']
    cell_phone=r['cell_phone'].replace(' ','')
    address=r['address']
    openid=r['openid']
    lng_lat=[]
    imgs=''
    if 'lng_lat' in r:
        lng_lat=r['lng_lat']
    license_number=None
    if 'license_number' in r:
        license_number=r['license_number']
    if 'img1s' in r:
        imgs=r['img1s']
    parents=Company.objects.filter(id=int(parent_id))   
    if not parents:
        data['e']='上级经销商ID不存在' 
        return JsonResponse(data)  
    parent=parents[0]    
    #2020-05-15 目前上级为一级经销商
    #if parent.level_id!=2:
    #    if parent.ancestor_id!=19318 and parent.ancestor_id!=19651 and parent.ancestor_id!=19257 and parent.ancestor_id!=113677 and parent.ancestor_id!=115486 and parent.ancestor_id!=115513:
    #        data['e']='上级经销商层级错误'  
    #        return JsonResponse(data) 
    ancestors=Company.objects.filter(id=parent.ancestor_id)
    if not  ancestors:
        data['e']='经销商族系错误'  
        return JsonResponse(data)
    if TerminalRegister.objects.filter(name=name,ancestor_id=parent.ancestor_id):
        data['e']='请不要重复注册！'
        return JsonResponse(data)
    #2020-05-15 确保公司族系内公司名称唯一
    if Company.objects.filter(name=name,ancestor_id=parent.ancestor_id):
        data['e']='您要申请注册的终端店名称已存在！'
        return JsonResponse(data)
    salesman_id = 0
    if 'salesman_id' in r:
        salesman_id = r['salesman_id']
    productSeries = []
    if 'productSeries' in r:
        for i in range(len(r['productSeries'])):
            productSeries.append(r['productSeries'][i])
        #productSeries = r['productSeries']
    parent_user_id=None
    if 'parent_user_id' in r:
        parent_user_id=int(r['parent_user_id'])
    t=TerminalRegister.objects.create(name=name,wx_openid=openid,contacts=contacts,address=address,lng_lat=lng_lat,ancestor_id=ancestors[0].id,
        cell_phone=cell_phone,parent_id=parent.id,license_number=license_number,salesman_id=salesman_id,product_series=productSeries,imgs=imgs,parent_user_id=parent_user_id)




    #if parent.ancestor_id==19318: 
    #    rs = Company.objects.filter(contacts=contacts,ancestor_id=parent.ancestor_id) | Company.objects.filter(cell_phone=cell_phone,ancestor_id=parent.ancestor_id)
    #    if not rs:
    #        terminal_register_approve_automatic(str(t.id)) 
    #if parent.ancestor_id==20445:
    #    terminal_register_approve_automatic(str(t.id)) 

    # 2022-07-20
    #19318;"重庆焱翕盛商贸有限公司"
    #20445;"贵州求真酒业有限公司"
    #100425;"山西成兆兴酒业有限公司"
    
    if parent.ancestor_id in [19318,20445,100425,19651,115486,113677,164626]: 
        rs = Company.objects.filter(contacts=contacts,ancestor_id=parent.ancestor_id) | Company.objects.filter(cell_phone=cell_phone,ancestor_id=parent.ancestor_id)
        if not rs:
            terminal_register_approve_automatic(str(t.id)) 
    
    

    data['id']=t.id  

    return JsonResponse(data)  


@tj_login_required
def list_agent_order(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)
    sWhere=" where (dt between '"+dt_fr+"' and '"+dt_to+"')"
    u=request.user
    c=u.company    
    if c.level_id==1:
        sWhere=sWhere+" and ancestor_id="+str(c.id)
        clmns=[_('下单时间'),_('订单号'),_('订货人'),_('订货公司名称'),_('供货公司名称'),_('产品名称及数量'),_('期望到货日期'),_('订单完结日期')]
        s="(select name from company_company where id=vendor_id),"
    else:
        sWhere=sWhere+" and vendor_id="+str(c.id)
        clmns=[_('下单时间'),_('订单号'),_('下单人'),_('下单公司名称'),_('产品名称及数量'),_('期望到货日期'),_('订单完结日期')]
        s=""   
    
    package_units = get_package_name(c.ancestor_id)
          
    sSql="select to_char(tm,'yyyy-mm-dd HH24:MI'),code,(select username from company_user where id=user_id),"+\
        "(select name from company_company where id=company_id),"+s+"array_to_string(array(select "+\
            "(select name from product_product where id=product_id)||"+\
                f"case when qty_box>0 then qty_box||'{package_units[2]}' else '' end||case when qty_h>0 then qty_h||'{package_units[1]}' else '' end||case when qty_bottle>0 then qty_bottle||'{package_units[0]}' else '' end "+\
            "from company_agentorderdetails where batch_id=a.id),','),"+\
        "coalesce(to_char(dt_expect,'yyyy-mm-dd'),''),coalesce(to_char(tm_complete,'yyyy-mm-dd'),''),id "+\
        "from company_agentorderbatch a"+sWhere
    cur=connection.cursor()
    cur.execute(sSql)
    data=[]    
    for r in cur.fetchall():
        if c.level_id==1:
            data.append([ r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7] ])
        else:
            #2020-05-28
            o=r[6] 
            if not r[6]:
                o="<a class='btn-close-order' order_id="+str(r[7])+" code='"+r[1]+"' href='#'>关闭订单</a>"
            data.append([ r[0],r[1],r[2],r[3],r[4],r[5],o])    
    return render(request,'company/list_agent_order.html',{'data':data,'clmns':clmns,'date_from':dt_fr,'date_to':dt_to})
      


@tj_login_required
def list_agent_order_review(request):
    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', dt)
    sWhere = " where (dt between '" + dt_fr + "' and '" + dt_to + "') and voucher_id=0"
    u = request.user
    c = u.company 
    sWhere = sWhere + " and ancestor_id=" + str(c.id)
    clmns = [_('下单时间'), _('订单类型'), _('订单号'), _('销售单号'), _('下单人'), _('下单方式'), _('下单公司名称'),
                 _('产品名称及数量'), _('期望到货日期'), _('订单完结日期'), _('审核信息'), _('审核状态'), _('操作')]
    sSql = (
        "select to_char(tm,'yyyy-mm-dd HH24:MI'),code, coalesce(voucher_code,''),(select username from company_user where id=user_id),"
        "(select name from company_company where id=company_id),"
        "array_to_string(array(select (select name from product_product where id=product_id)|| case when qty_box>0 then qty_box||'箱' else '' end||case when qty_bottle>0 then qty_bottle||'瓶' else '' end from company_agentorderdetails where batch_id=a.id ),','),"
        "coalesce(to_char(dt_expect,'yyyy-mm-dd'),''),"
        "coalesce(to_char(tm_complete,'yyyy-mm-dd'),''),id,review_company_id,"
        "(select name from company_company where id=review_company_id),voucher_id,(select username from company_user where id=helper_id),state"
        " from company_agentorderbatch a "+sWhere)
    cur = connection.cursor()
    cur.execute(sSql)
    data = []
    for r in cur.fetchall():
        o = r[7]
        if not o:
            o = '尚未完成'

        voucher_id = r[11]
        voucher_type = ''
        helper = r[12]
        if voucher_id:
            if voucher_id == 4:
                voucher_type = '退货' 
            elif voucher_id == 9:
                voucher_type = '换货'
            elif voucher_id == 0:
                voucher_type = '线上订单' 

        else:
            voucher_type = '线上订单'
        if helper:
            helper = helper + '代下单'
        else:
            helper = '自助下单'
        
        state = ''
        if r[13] == 1:
            state = '已通过'
        elif r[13] == 2:
            state = '已驳回'
        else:
            state = '待审核'


        review_company_id = r[9]
        order_id = r[8]
        s = r[10] 
        if not s:
            s = '已审核'
        else: 
            if c.id == review_company_id: 
                s = "<a class='btn-close-order btn btn-danger btn-xs' order_id=" +str(order_id) + " code='" + r[1] + "' href='#'>审核订单</a>"
                
        
        products = r[5] 

        data.append([r[0],voucher_type, r[1], r[2], r[3], helper, r[4], products, r[6], o, s, state,"<a class='btn btn-default btn-xs' onclick='viewDetail("+str(order_id)+")'>详情</a>"])
    return render(request, 'company/list_agent_order.html',
                  {'data': data, 'clmns': clmns, 'date_from': dt_fr, 'date_to': dt_to})



@tj_login_required
def list_agent_order_return(request):
    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', dt)
    sWhere = " where (dt between '" + dt_fr + "' and '" + dt_to + "') and (voucher_id=4 or voucher_id= 9)"
    u = request.user
    c = u.company 
    sWhere = sWhere + " and ancestor_id=" + str(c.id)
    clmns = [_('下单时间'), _('订单类型'), _('订单号'), _('销售订单号'), _('下单人'), _('下单方式'), _('下单公司名称'),
                 _('退货产品'), _('换货产品'), _('订单完结日期'), _('审核信息'), _('操作')]
    sSql = (
        "select to_char(tm,'yyyy-mm-dd HH24:MI'),code,(select username from company_user where id=user_id),"
        "(select name from company_company where id=company_id),"
        "array_to_string(array(select (select name from product_product where id=product_id)|| case when qty_box>0 then qty_box||'箱' else '' end||case when qty_bottle>0 then qty_bottle||'瓶' else '' end from company_agentorderdetails where batch_id=a.id and voucher_id!=9),','),"
        "coalesce(to_char(dt_expect,'yyyy-mm-dd'),''),"
        "coalesce(to_char(tm_complete,'yyyy-mm-dd'),''),id,review_company_id,"
        "(select name from company_company where id=review_company_id),voucher_id,(select username from company_user where id=helper_id),"
        "array_to_string(array(select (select name from product_product where id=product_id)|| case when qty_box>0 then qty_box||'箱' else '' end||case when qty_bottle>0 then qty_bottle||'瓶' else '' end from company_agentorderdetails where batch_id=a.id and voucher_id=9),',')"
        " from company_agentorderbatch a "+sWhere)
    cur = connection.cursor()
    cur.execute(sSql)
    data = []
    for r in cur.fetchall():
        o = r[6]
        if not o:
            o = '尚未完成'

        voucher_id = r[10]
        voucher_type = ''
        helper = r[11]
        if voucher_id:
            if voucher_id == 4:
                voucher_type = '退货' 
            elif voucher_id == 9:
                voucher_type = '换货'
            elif voucher_id == 0:
                voucher_type = '线上订单' 

        else:
            voucher_type = '线上订单'
        if helper:
            helper = helper + '代下单'
        else:
            helper = '自助下单'



        review_company_id = r[8]
        order_id = r[7]
        s = r[9] 
        if not s:
            s = '已审核'
        else: 
            if c.id == review_company_id: 
                s = "<a class='btn-close-order btn btn-danger btn-xs' order_id=" +str(order_id) + " code='" + r[1] + "' href='#'>审核订单</a>"
                
        
        products = r[4]
        product_change = r[12] 

        data.append([r[0],voucher_type, r[1], r[2], helper, r[3], products,product_change, o, s,"<a class='btn btn-default btn-xs' onclick='viewDetail("+str(order_id)+")'>详情</a>"])
    return render(request, 'company/list_agent_order.html',
                  {'data': data, 'clmns': clmns, 'date_from': dt_fr, 'date_to': dt_to})


#订单审核详情
@tj_login_required
def list_agent_order_review_detail(request,id=None): 
    data = {
        'e':'',
        'reviews':[],
        'review_person':{
            'company':'', 
            'phone':''
        },
        'tm_complete':'' 
    }
    if id:
        ag = AgentOrderBatch.objects.filter(id=int(id))
        if ag:
            ag = ag[0] 
            if ag.tm_complete:
                data['tm_complete'] = ag.tm_complete.strftime("%Y-%m-%d %H:%M:%S")
            if ag.review_company:
                data['review_person']['company'] = ag.review_company.name  
                data['review_person']['phone'] = ag.review_company.cell_phone 
            reviews = AgentOrderReview.objects.filter(batch_id=ag.id)
            if reviews: 
                for r in reviews:
                    data['reviews'].append({
                        'company':r.company.name,
                        'name':r.user.username,
                        'tm':r.tm.strftime("%Y-%m-%d %H:%M:%S")
                    })
            if ag.batch_code:
                cur = connection.cursor()
                cur.execute("select tm from inventory_batch where code = '"+ag.batch_code+"' ")
                r = cur.fetchone()
                if r and r[0]:
                    data['fh_tm'] = r[0].strftime("%Y-%m-%d %H:%M:%S")

    return render(request,"company/list_agent_order_detail.html",data)



@tj_login_required
def close_agent_order(request,id):
    if request.user.company.id == 19257 or request.user.company.id == 113677:
        ao = AgentOrderBatch.objects.filter(id=int(id))
        if ao:
            ao = ao[0]   
            ao.review_company_id = None
            a = AgentOrderReview(   
                batch=ao, 
                company_id=request.user.company.id,
                user_id=request.user.id
            )
            if ao.voucher_id == 4 or ao.voucher_id == 9:
                ao.tm_complete = now()
            
            state = request.POST.get('state','')
            voucher_code = request.POST.get('voucher_code','')
            remark = request.POST.get('remark','')
            if state:
                ao.state = state
            if voucher_code:
                ao.voucher_code = voucher_code
            #if remark:
                
                
                
            a.save() 
            ao.save()
        return JsonResponse({'e': '', 'cnt': 1})
    else: 
        cur = connection.cursor()
        cur.execute(
            "update company_agentorderbatch set tm_complete=now() where id=" + id)
        cnt = cur.rowcount
        cur.close()
        return JsonResponse({'e': '', 'cnt': cnt})



# 给扫码枪用的订单接口
@csrf_exempt
def list_agent_order_data(request):
    data = {
        'e':'',
        'records':[

        ]
    }
    company_id = request.GET.get('company_id','')
    if company_id:
        orders = AgentOrderBatch.objects.filter(vendor_id=int(company_id),review_company_id=None,voucher_id=0,batch_code=None ).order_by('-id')
        if orders:
            for order in orders:
                record = {
                    'code':'',
                    'company_name':'',
                    'company_id':'',
                    'user_name':'',
                    'tm':'',
                    'dt_expect':'',
                    'remark':'',
                    'products':[]
                }
                record['code'] = order.code
                record['company_name'] = order.company.name
                record['company_id'] = order.company_id
                record['user_name'] = order.user.username
                record['tm'] = order.tm.strftime("%Y-%m-%d %H:%M:%S")
                record['dt_expect'] = order.dt_expect.strftime("%Y-%m-%d")
                record['remark'] = order.remark

                products = AgentOrderDetails.objects.filter(batch_id=order.id)
                if products:
                    for p in products:
                        record['products'].append({
                            'id':p.product_id,
                            'name':p.product.name,
                            'qty_box':p.qty_box,
                            'qty_bottle':p.qty_bottle
                        })



                data['records'].append(record)
    else:
        data['e'] = '数据丢失'

    return JsonResponse(data)




'''
def agent_order(request,id=None):
    if not id:
        obj=AgentOrderBatch()
        obj.user = request.user
        obj.company = request.user.company
        obj.ancestor_id = request.user.company.ancestor_id
        obj.vendor=request.user.company.parent
    else:
        obj=AgentOrderBatch.objects.get(id=int(id))
    is_saved=False
    if request.method == 'GET':        
        form = AgentOrderBatchForm(instance=obj)
        formset = AgentOrderDetailsFormset(instance=obj)          
    else:
        form = AgentOrderBatchForm(request.POST, instance=obj)
        formset = AgentOrderDetailsFormset(request.POST, instance=obj)
        if form.is_valid() and formset.is_valid():
            form.save()
            formset.save()
            is_saved=True
    return render(request, 'company/agent_order.html', {'form': form, 'formset': formset, 'is_saved': is_saved})


@csrf_exempt
#wx_app
def app_agent_order(request):
    data={'e':''}
    k = sK   
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    err=[]
    #接收JSON数据
    r=json.loads((request.body).decode('utf-8'))
    if 'company_id' not in r or 'user_id' not in r or 'code' not in r:
        data['e']='code,company_id,user_id missing'
        return JsonResponse(data)

    if 'orders' not in r:
        data['e']='缺少订单明细数据:orders'
        return JsonResponse(data)    
    company_id=int(r['company_id'])
    user_id=int(r['user_id'])
    code=r['code']    
    cs=Company.objects.filter(id=int(company_id))
    if cs:
        c=cs[0]
    else:
        data['e']='company_id error'
        return JsonResponse(data)
    vendor_id=c.parent_id
    date_expect=None
    remark=None
    if 'vendor_id' in r['vendor_id']:
        vendor_id=int(r['vendor_id'])
    if 'date_expect' in r:
        dt_expect=r['date_expect']
    if 'remark' in r:
        remark=r['remark']
    order_batch=AgentOrderBatch.objects.create(code=code,compan_id=company_id,user_id=user_id,vendor_id=vendor_id,ancestor_id=c.ancestor_id,dt_expect=dt_expect,remark=remark)
    
    #订单明细
    a=[]
    for o in r['orders']:
        a.append("("+str(c.ancestor_id)+","+str(c.id)+str(vendor_id)+","+str(order_batch)+
            str(o.product_id)+","+str(o.qty)+")"
        )
    s="INSERT INTO logistics.company_agentorderdetails(ancestor_id,company_id,vendor_id,batch_id,product_id,qty) values "+",".join(a)
    cur=connection.cursor()
    cur.execute(s)
    return JsonResponse(data)
'''


@login_required
def list_terminal_register(request):
    data={
        'clmns':[],
        'data':[],
        'rejected':{'clmns':[],'data':[]}
    }
    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',dt)  
    data['date_from']=dt_fr
    data['date_to']=dt_to
    u=request.user
    c=u.company
    perm=False
    if u.has_perm('company.sys_admin'):
        perm=True 


    #2022-04-20 长宇酒业，14040;"助理"
    if u.id in [12110,14040]:
        perm=True 
        
    group_id_filter = ''
    cur=connection.cursor()
    #2023-06-20 川稻老窖 业务主管
    if c.ancestor_id==148119 or c.ancestor_id == 16687:
        cur.execute("SELECT array_to_string( ARRAY ( SELECT group_id FROM company_user_groups WHERE user_id = "+str(u.id)+" ), ',' )")
        r = cur.fetchone()
        if r[0]:
            if '11' in r[0]:
                group_id_filter=' and (select count(*) from company_user_groups where group_id = 8 and user_id = parent_user_id)>0'
                perm=True
            elif '10' in r[0]:
                group_id_filter=' and (select count(*) from company_user_groups where group_id = 11 and user_id = parent_user_id)>0'
                perm=True
        
    
    # 2022-09-14
    # 被驳回的终商店注册申请 
    rejs=[]
    if c.level_id==1:
        sWhere="where ancestor_id="+str(c.ancestor_id)+" and is_rejected=true"
    elif c.is_expense_account:        
        sWhere=" where is_rejected=true and (select division_id from company_company where id=a.parent_id)="+str(c.division_id)
    else:
        sWhere=" where is_rejected=true and parent_id="+str(c.id)    
    
    if group_id_filter:
        sWhere = sWhere + group_id_filter
    
    
    data['rejected']['clmns']=[_('终端店名称'),_('联系人'),_('手机号码'),_('详细地址'),_('营业执照编号'),_('父级公司'),_('业务员'),_('产品系列'),_('申请注册时间'),_('驳回时间')]
    s="select id,name,contacts,cell_phone,address,coalesce(license_number,''),"+\
        "(select name from company_company where id=a.parent_id),"+\
        "to_char(tm,'yyyy-mm-dd HH24:MI'),case when tm_aprv is null then '' else "+\
            "to_char(tm_aprv,'yyyy-mm-dd HH24:MI')||' ('||(select username  from company_user where id=user_aprv_id)||')' end, "+\
            "coalesce((select last_name from company_user where id = salesman_id),''),"+\
            "array_to_string(array(select name from product_series where id in (select unnest(product_series))),','),"+\
            "coalesce(to_char(tm_rejected,'yyyy-mm-dd hh24:mi'),'') FROM company_terminalregister a "+sWhere+" ORDER BY tm_aprv desc"
    cur.execute(s)
    for r in cur.fetchall():        
        data['rejected']['data'].append([ r[1],r[2],r[3],r[4],r[5],r[6],r[9],r[10],r[7],r[11] ])


    # 2022-09-15 正常的注册申请
    if c.level_id==1:
        sWhere="where ancestor_id="+str(c.ancestor_id)+" and is_rejected=false and (dt between '"+dt_fr+"' and '"+dt_to+"')"
    elif c.is_expense_account:        
        sWhere=" where is_rejected=false and (select division_id from company_company where id=a.parent_id)="+str(c.division_id)+\
            " and (dt between '"+dt_fr+"' and '"+dt_to+"')"
    else:
        sWhere=" where parent_id="+str(c.id)+" and is_rejected=false  and (dt between '"+dt_fr+"' and '"+dt_to+"')"    
    
    if group_id_filter:
        sWhere = sWhere + group_id_filter
    
    
    data['clmns']=[_('终端店名称'),_('联系人'),_('手机号码'),_('详细地址'),_('营业执照编号'),_('父级公司'),_('业务员'),_('产品系列'),_('申请注册时间'),_('审核通过时间')]
    s="select id,name,contacts,cell_phone,address,coalesce(license_number,''),"+\
        "(select name from company_company where id=a.parent_id),"+\
        "to_char(tm,'yyyy-mm-dd HH24:MI'),case when tm_aprv is null then '' else "+\
            "to_char(tm_aprv,'yyyy-mm-dd HH24:MI')||' ('||(select username  from company_user where id=user_aprv_id)||')' end, "+\
            "coalesce((select last_name from company_user where id = salesman_id),''),"+\
            "array_to_string(array(select name from product_series where id in (select unnest(product_series))),',')"+\
        "FROM company_terminalregister a "+sWhere+" ORDER BY tm_aprv desc"   
    cur.execute(s)
    for r in cur.fetchall():   
        if r[8]:
            #已通过审核            
            if perm:
                prv="<a reg_id='"+str(r[0])+"' class=' btn-approve'                       href='/company/register/approve/"+str(r[0])+"/?view=1' >"+r[8]+"</a>"                
            else:
                prv=r[8]               
        else:
            if perm:                
                prv="<a reg_id='"+str(r[0])+"' class='btn btn-xs btn-primary btn-approve' href='/company/register/approve/"+str(r[0])+"/' >现在审核</a>"+\
                    "<a reg_id='"+str(r[0])+"' class='btn btn-xs btn-danger  btn-reject'  href='/company/register/approve/"+str(r[0])+"/?rejected=1'>驳回注册</a>"
            else:
                prv=_("'未审核'")
        data['data'].append([ r[1],r[2],r[3],r[4],r[5],r[6],r[9],r[10],r[7],prv ]) 
    return render(request, 'company/list_terminal_register.html', data)    




#2020-12-18 终端店注册自动审核
def terminal_register_approve_automatic(termianl_reg_id,apprv_id=1):
    id=termianl_reg_id
    pwd='123456'
    data={'company':'','username':'','password':'','e':''}   
    obj=TerminalRegister.objects.get(id=int(id)) 
    try:    
        data['company']=obj.name
        u=obj.contacts
        phone=obj.cell_phone    
        c=Company(name=obj.name,parent=obj.parent,address=obj.address,license_number=obj.license_number,category_id=obj.parent.category_id,contacts=u,lng_lat=obj.lng_lat)
        c.is_terminal = True
        c.cell_phone = phone
        if obj.product_series:
            c.series_more = obj.product_series
        c.save()  
        
        if obj.salesman_id:
            sta = StaffSaldiv.objects.filter(user_id=obj.salesman_id)
            if sta:
                sta = sta[0] 
                if sta.agent_ids:
                    sta.agent_ids.append(c.id)
                else:
                    sta.agent_ids = [c.id]
                sta.save()
            else:
                sta = StaffSaldiv(
                    company_id=c.ancestor_id,
                    user_id=obj.salesman_id,
                    agent_ids=[obj.salesman_id]
                )
                sta.save()
            
        cur=connection.cursor()
        cur.execute("SELECT count(*) FROM company_user where username like '%"+phone+"%'")
        r=cur.fetchone()
        fx=''
        if r[0]:
            fx=chr(r[0]-1+ord('A'))    
        acc=phone+fx        
        uu=User(
            username=acc,
            last_name=u,
            company=c,
            ancestor_id=c.ancestor_id,
            phone=phone,
        )    
        uu.set_password(pwd)
        #创建帐号    
        uu.save()
        
            
        data={'company':obj.name,'username':acc,'password':pwd,'e':''}
        #添加经销商功能组别  5;"经销商"
        uu.groups.add(5)
        #修改审核状态，添加审核人
        obj.tm_aprv=datetime.datetime.now()        
        obj.user_aprv_id=int(apprv_id)
        obj.save() 
        
        #2021-01-16
        cfg=CompanyCfg.objects.get(company_id=c.ancestor_id)
        app_name=cfg.app_name
        sms_sign=cfg.sms_sign
        if c.ancestor_id != 113677:
            send_sms(phone,"您在"+app_name+"已成功注册终端店，帐号："+acc+", 密码："+pwd+"。" ,sms_sign)  
    except Exception:    
        data['e']='审核失败，请与系统管理员联系'
        send_sms('13976686507','终端店审核失败:'+obj.name,"天鉴防伪")
    return data

       
@login_required
def terminal_register_approve(request,id):   
    data={'company':'','username':'','password':'','e':''}
    obj=TerminalRegister.objects.get(id=int(id))    
    approved=request.GET.get('approved','')   
    rejected=request.GET.get('rejected','')  

    # 点击了 驳回注册 按钮
    if rejected:
        data={
            'company':obj.name,
            'reg_id':int(obj.id)
        }       
        # 更新注册申请状态
        obj.is_rejected=True
        obj.tm_rejected=datetime.datetime.now()  
        obj.save()
        return JsonResponse(data)


    if approved:  
        data=terminal_register_approve_automatic(id,request.user.id)   
        return JsonResponse(data)
    data = {
        'obj': obj,
        'imgs': []
    }
    if obj.imgs:
        data['imgs'] = obj.imgs.split(',')
    return render(request,'company/terminal_register.html', data) 





'''
@tj_login_required
def auth_product_query(request,id=None):    
    if id:
        obj=AuthQuery.objects.get(id=int(id))
    else:
        obj=AuthQuery()
    data={'e':'','obj':obj}
    if request.method=='POST':        
        u_id=request.POST.get('user_id')
        what=request.POST.get('what')
        content=request.POST.get('content')
        obj.what=what
        obj.user_id=int(u_id)
        obj.save()        
    else:
        if id:
            m = apps.get_model('product',what)
'''


#2020-09-10
@tj_login_required
def ajax_parent_levels(request,id):
    lv=Level.objects.get(id=int(id))
    ps=[]
    k=lv.sn-1
    while True:
        plv=Level.objects.filter(sn=k)
        if plv:
            p=plv[0]
            if p.id>1:
                ps.append({'id':p.id,'name':p.name,'sn':p.sn,'rec':lv.sn-p.sn})
            else:
                break
        else:
            break
        k=k-1
    return JsonResponse({"parents":ps})


#2020-11-24
@login_required
def create_enterprise(request):
    is_saved=False
    obj=Company()
    cats=[]
    for cat in Category.objects.all():
        cats.append([cat.id,cat.name])
    if request.method == 'GET':           
        form = AgentForm(instance=obj, user=request.user)           
    else:         
        form = AgentForm(request.POST, instance=obj, user=request.user)   
        if form.is_valid():
            c=form.save()
            c.hierarchy_id=c.id
            c.parent_id=c.id
            c.ancestor_id=c.id
            c.hierarchy_id=c.id
            c.level_id=1
            c.img_logo="logo/logo_tj.png"
            c.save()
            acc=request.POST.get('user_acc','')
            pwd=request.POST.get('user_pwd','')           
            u=User(company_id=c.id,ancestor_id=c.id,username=acc,last_name=acc)
            u.set_password(pwd)
            u.save()            
            g=Group.objects.get(id=4)                        
            u.groups.add(g)     

            cfg=CompanyCfg(company_id=c.id)
            cfg.save()

            #2021-04-24 写入企业功能组别
            for g in Group.objects.all():
                cg=CGroup(company_id=c.id,name=g.name,group_id=g.id)
                cg.save()

            #2021-09-11 系统管理员帐号添加企业功能组别 4;"系统管理员"
            ga=CGroup.objects.get(company_id=c.id,group_id=4)            
            u.cgroup_ids=[{'id':ga.id,'name':ga.name}]
            u.save()

                
            # 2022-10-29 创建企业的stkdetails分表
            stkdetails_init(c.id)



            return  redirect("/obj/list/companycfg/")   

    return render(request, 'obj/enterprise.html', {'form': form, 'is_saved':is_saved,'cats':cats})        
   
@login_required
def delete_demo_stk_batch(request):
    data={'e':'','data':[]}
    #酒企演示帐号
    id=16687
    
    cur=connection.cursor()
    
    for b in Batch.objects.filter(ancestor_id=id):
        s="select a.id,code,"+\
            "(select name from company_company where id=a.company_fr_id),"+\
            "(select name from company_company where id=a.company_to_id),"+\
            "(select name from inventory_voucher where id=a.vtype_id),"+\
            "(select name from product_product where id=a.product_id),"+\
            "to_char(tm,'yyyy-mm-dd HH24:MI:SS') from "+\
            "(select id,code,company_fr_id,company_to_id,vtype_id,user_id,product_id,tm "+\
                "from inventory_batch where id="+str(b.id)+") a"   
        cur.execute(s)
        r=cur.fetchone()        
        data['data'].append({
            'id':r[0],
            'code':r[1],
            'company':r[2],
            'agent':r[3],
            'voucher':r[4],
            'product':r[5],
            'time':r[6]
        })
        if request.method=='POST':
            b.delete()       
        
    cur.close()   
    return render(request, 'obj/delete_demo_stk_batch.html', {'data': data})  


@login_required
def edit_staffdiv(request,id=None,act=None):
    if act=='delete':
        if id:
            obj=StaffSaldiv.objects.get(id=int(id))
            obj.delete()
            return JsonResponse({'e':''})

    c=request.user.company
    is_saveed=False
    if id:
        obj=StaffSaldiv.objects.get(id=int(id))
    else:
        obj=StaffSaldiv(company_id=c.id)
    agents=[]
    subsaldivs=[]
    saldivs=[]

    sel_saldivs=[]

    if request.method == 'GET':
        for d in SalesDivision.objects.filter(company_id=c.id).order_by('name'):
            sel_saldivs.append([d.id,d.name])

        form = StaffSaldivForm(instance=obj)  
        if id:
            if obj.saldiv_ids:
                for i in obj.saldiv_ids:
                    objs=SalesDivision.objects.filter(id=i)
                    if objs:
                        o=objs[0]
                        saldivs.append([o.id,o.name])
            if obj.subsaldiv_ids:
                for i in obj.subsaldiv_ids:
                    objs=SubSalDivision.objects.filter(id=i)
                    if objs:
                        o=objs[0]
                        subsaldivs.append([o.id,o.name])
            if obj.agent_ids:
                for i in obj.agent_ids:
                    o=Company.objects.get(id=i)
                    agents.append([o.id,o.name])
    elif request.method == "POST":
        form = StaffSaldivForm(request.POST, instance=obj)
        if form.is_valid():
            o=form.save()
            is_saved = True
            return redirect('/company/list/staffdiv/')
    return render(request, 'company/staff_saldiv_edit.html', 
        {'form': form,'saldivs':saldivs,'agents':agents,'subsaldivs':subsaldivs,'sel_saldivs':sel_saldivs}) 


@login_required
def list_staffdiv(request,id=None):
    u=request.user
    cur=connection.cursor()
    data=[]
    clmns=[_('用户帐号'),_('用户姓名'),_('功能组别'),_('战区'),_('分区'),_('经销商')]
    s="select a.id,"+\
        "(select username from company_user where id=a.user_id),"+\
        "(select last_name from company_user where id=a.user_id),"+\
        "array_to_string(array(select name from auth_group where id in (select unnest(group_ids))),','),"+\
        "array_to_string(array(select name from company_salesdivision where id in (select unnest(saldiv_ids))),','),"+\
        "array_to_string(array(select name from company_subsaldivision where id in (select unnest(subsaldiv_ids))),','),"+\
        "array_to_string(array(select name from company_company where id in (select unnest(agent_ids))),',') "+\
        "from "+\
        "(select id,user_id,to_char(tm,'yyyy-mm-dd HH24:MI:SS') tm,"+\
            "group_ids,saldiv_ids,subsaldiv_ids,agent_ids from company_staffsaldiv "+\
            "where company_id="+str(u.company_id)+\
        ") a"

    s="select a.id,"+\
        "(select username from company_user where id=a.user_id),"+\
        "(select last_name from company_user where id=a.user_id),"+\
        "group_names,"+\
        "array_to_string(array(select name from company_salesdivision where id in (select unnest(saldiv_ids))),','),"+\
        "array_to_string(array(select name from company_subsaldivision where id in (select unnest(subsaldiv_ids))),','),"+\
        "array_to_string(array(select name from company_company where id in (select unnest(agent_ids))),',') "+\
        "from "+\
        "(select id,user_id,to_char(tm,'yyyy-mm-dd HH24:MI:SS') tm,"+\
            "array_to_string(array(select name from auth_group where id in "+\
                "(select group_id from company_user_groups where user_id=c.user_id)),',') group_names,"+\
            "saldiv_ids,subsaldiv_ids,agent_ids from company_staffsaldiv c "+\
            "where company_id="+str(u.company_id)+\
        ") a"


    cur.execute(s)
    for r in cur.fetchall():
        data.append([
            '<a href="/company/edit/staffdiv/'+str(r[0])+'/">'+r[1]+'</a>',
            r[2],r[3],r[4],r[5],r[6]
        ])
    #return JsonResponse(data)
    return render(request,'company/list_staff_saldiv.html',  {'data':data,'clmns':clmns})
    
#业务员管理 Jonathan
@login_required
def saleman_manage(request):

    obj = request.GET.get('obj','')
    if obj != "": 
        data = {'data': [], 'clmns': [], 'e': [],'subtt': ['', ''], 'murl': '', 'dt': False, 'add': True,'date_from':'','date_to':''}
        
        cur=connection.cursor() 
        if obj == "performance":
            uid = request.GET.get('uid','')
            if uid:
                ancestor_id = request.user.ancestor_id
                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=30)).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 
                
                sql = f"""SELECT
                            ( SELECT NAME FROM product_series WHERE ID = series_id ),
                            ( SELECT NAME FROM product_product WHERE ID = product_id ),
                            ( CASE label_pkg WHEN 3 THEN '箱' WHEN 2 THEN '盒' ELSE'瓶' END ),
                            cnt,
                            ( CASE label_pkg WHEN 3 THEN ( qty_p * cnt ) ELSE cnt END ) AS cnt_p,
                            COALESCE ( price, 0 ),
                            COALESCE ( ( CASE label_pkg WHEN 3 THEN ( ( qty_p * cnt ) * price ) ELSE ( cnt * price ) END ), 0 ) AS amount 
                        FROM
                            (
                            SELECT
                                product_id,
                                label_pkg,
                                ( SELECT series_id FROM product_product WHERE ID = product_id ),
                                ( SELECT qty_p FROM product_product WHERE ID = product_id ),
                                ( SELECT price FROM product_product WHERE ID = product_id ),
                                COUNT ( ID ) AS cnt 
                            FROM
                                inventory_stkdetails 
                            WHERE
                                ancestor_id = {str(ancestor_id)}
                                AND company_id IN ( SELECT ID FROM company_company WHERE ID IN ( SELECT UNNEST ( agent_ids ) FROM company_staffsaldiv WHERE user_id = {uid} ) AND is_terminal = TRUE ) 
                                AND vtype_id = 1 
                                AND dt >= '{dt_fr}' 
                                AND dt <= '{dt_to}' 
                                AND product_id IN ( SELECT ID FROM product_product WHERE series_id IN ( SELECT UNNEST ( product_series ) FROM company_user WHERE ID = {uid} ) ) 
                            GROUP BY
                                product_id,
                            label_pkg 
                            ) A ORDER BY product_id"""
                cur.execute(sql)
                rs = cur.fetchall()
                for r in rs: 
                    
                    data['data'].append([ 
                        r[0],
                        r[1],
                        r[2],
                        r[3],
                        r[4],
                        float(r[5]),
                        float(r[6])
                    ])
        elif obj == "agent":
            uid = request.GET.get('uid','')
            if uid:
                u = User.objects.get(id=uid)
                if request.method == "POST":
                    company_id = request.POST.get('company_id','')
                    company_ids = request.POST.get('company_ids', '')
                    delflag = request.POST.get('delflag','')
                    if company_ids:
                        companys = company_ids.split(',')
                        for c_id in companys:
                            sta = StaffSaldiv.objects.filter(user_id=uid)
                            if sta:
                                sta = sta[0]
                                isHave = False
                                index = 0
                                for r in sta.agent_ids:
                                    if r == int(c_id):
                                        isHave = True
                                        break
                                    index = index + 1
                                if not isHave:
                                    sta.agent_ids.append(int(c_id))
                                    sta.save()
                                else:
                                    if delflag == '1':
                                        del sta.agent_ids[index]
                                        sta.save()
                            else:
                                sta = StaffSaldiv()
                                sta.c_id = u.c_id
                                sta.agent_ids = [int(c_id)]
                                sta.user = u
                                sta.save()
                    if company_id:
                        sta = StaffSaldiv.objects.filter(user_id=uid)
                        if sta:
                            sta = sta[0]
                            isHave = False
                            index = 0
                            for r in sta.agent_ids:
                                if r == int(company_id):
                                    isHave = True
                                    break
                                index = index + 1
                            if not isHave:
                                sta.agent_ids.append(int(company_id))
                                sta.save()
                            else:
                                if delflag == '1':
                                    del sta.agent_ids[index]
                                    sta.save()
                        else:
                            sta = StaffSaldiv()
                            sta.company_id = u.company_id
                            sta.agent_ids = [int(company_id)]
                            sta.user = u
                            sta.save()
                                    
                                
                data['uid'] = uid
                data['subtt'] = ['业务员信息','授权终端']
                #data['clmns']=[_('名称'),_('父级'),_('营销层级'),_('所属战区'),_('所属分区'),_('地址'),_('联系电话'),_('终端店'),_('渠道'),'操作']
                sWhere=" where id in (select id from company_company where id in (select unnest(agent_ids) from company_staffsaldiv where user_id = "+ uid +" ))"
                s="select id,name,"+\
                "coalesce((select name from company_company where id=a.parent_id),''),"+\
                "coalesce((select name from company_level where id=a.level_id),''),"+\
                "coalesce((select name from company_salesdivision where id=division_id),''),"+\
                "coalesce((select name from company_subsaldivision where id=sub_division_id),''),"+\
                "coalesce(address,''),coalesce(cell_phone,''),"+\
                "case when is_terminal then '是' else '否' end, "+\
                "coalesce((select name from company_channel where id=channel_id),'') "+\
                "from company_company a "+sWhere
                
                cur.execute(s)
                rs = cur.fetchall()
                for r in rs: 
                    check_box = '<input  class="checkchild" value="'+str(r[0])+'" type="checkbox">'
                    btn = '<span class="btn btn-sm btn-danger btn-delete" data-id="'+str(r[0])+'">删除</span>'
                    data['data'].append([check_box,r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],btn ])
    
            return render(request,'company/saleman_agent.html',data)
        elif obj == "agent_performance":
            uid = request.GET.get('uid','')
            if uid:
                ancestor_id = request.user.ancestor_id
                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=30)).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
                
                sql = f"""
                    SELECT
                        s.product_id,
                        agent_id,
                        ( SELECT NAME FROM company_company WHERE ID = agent_id ),
                        ( SELECT NAME FROM product_series WHERE ID = product_series_id ),
                        ( SELECT NAME FROM product_product WHERE ID = s.product_id ),
                        ( CASE label_pkg WHEN 3 THEN '箱' WHEN 2 THEN '盒' ELSE'瓶' END ),
                        COUNT ( ID ) 
                    FROM
                        inventory_stkdetails s
                        INNER JOIN (
                        SELECT
                            product_series_id,
                            ( SELECT NAME FROM product_series WHERE ID = product_series_id ),
                            UNNEST ( ARRAY ( SELECT ID FROM product_product WHERE series_id = product_series_id ) ) product_id,
                            agent_id 
                        FROM
                            (
                            SELECT
                                UNNEST ( product_series ) AS product_series_id,
                                UNNEST ( agent_ids ) AS agent_id 
                            FROM
                                company_user u
                                INNER JOIN company_staffsaldiv d ON u.ID = d.user_id 
                            WHERE
                                user_id = {uid} 
                            ) A 
                        GROUP BY
                            product_series_id,
                            agent_id 
                        ) B ON company_id = B.agent_id 
                        AND s.product_id = B.product_id 
                    WHERE
                        vtype_id = 1 
                        AND ancestor_id = {str(ancestor_id)} 
                        AND dt > '{dt_fr}' 
                        AND dt < '{dt_to}' 
                        AND company_id IN ( SELECT ID FROM company_company WHERE is_terminal = TRUE AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM company_staffsaldiv WHERE company_id = {str(ancestor_id)} ) ) 
                    GROUP BY
                        s.product_id,
                        agent_id,
                        product_series_id,
                        label_pkg 
                    ORDER BY
                        agent_id,
                        product_id
                
                """
                
                cur.execute(sql)
                rs = cur.fetchall()
                for r in rs: 
                    
                    data['data'].append([ 
                        r[2],
                        r[3],
                        r[4],
                        r[5],
                        r[6]
                    ])
        elif obj == 'action_photos':
            action_id = request.GET.get('action_id','')
            if action_id:
                data['subtt'] = ['业务员信息','核心动作图片']
                data['clmns']=[_('图片'),_('备注')]
                sWhere=" where action_id = "+action_id
                s="select photo,COALESCE(remark,'') from sales_action_picture "+sWhere
                cur.execute(s)
                rs = cur.fetchall()
                for r in rs: 
                    img = f'<img src="{r[0]}" style="width:200px" />'
                    data['data'].append([img,r[1]])
        elif obj == "sharegroup":
            if request.method == 'POST':
                name = request.POST.get('name','')
                user_ids = request.POST.get('user_ids','')
                remark = request.POST.get('remark','')
                id = request.POST.get('id','')
                if name and user_ids:
                    m = None
                    if id:
                        m = UserShareGroup.objects.get(id=id)
                    else:
                        m = UserShareGroup()
                        m.company_id = request.user.company_id
                        m.sharethings = [1]
                    
                    m.name = name
                    m.user_ids = user_ids.split(',')
                    m.remark = remark
                    m.save()

            elif request.method == 'GET':
                id = request.GET.get('id','')
                if id:
                    m = UserShareGroup.objects.get(id=id)
                    cur = connection.cursor()
                    cur.execute(f"""
                        select id,last_name from company_user where id in 
                        (select unnest(user_ids) from company_usersharegroup where id = {id})
                    """)
                    rs = cur.fetchall()
                    data['users'] = rs
                    data['name'] = m.name
                    if m.remark:
                        data['remark'] = m.remark
                    data['id'] = id
                else:
                    data['id'] = ''


            return render(request, 'company/saleman_sharegroup.html', data)
        elif obj == "saleman_transfer":
            uid = request.GET.get('uid', '')
            to_uid = request.GET.get('to_uid', '')
            if uid:
                u = User.objects.get(id=uid)
                if request.method == "POST":
                    company_ids = request.POST.get('company_ids', '')
                    if company_ids:
                        companys = company_ids.split(',')
                        test = [1,2,3]

                        agent_ids = StaffSaldiv.objects.filter(user_id=uid)
                        if agent_ids:
                            for c_id in companys:
                                agent_id = agent_ids[0] 
                                agent_id.agent_ids.remove(int(c_id))
                                agent_id.save()
                        to_agent_ids = StaffSaldiv.objects.filter(user_id=to_uid)
                        if to_agent_ids:
                            to_agent_id = to_agent_ids[0]
                            to_agent_ids[0].agent_ids.extend(companys)
                            to_agent_id.save()

                data['uid'] = uid
                data['subtt'] = ['业务员信息', '人员转移']
                # data['clmns'] = ['<input type="checkbox" name="checkboxes[]" value="on" onclick="selectAll(this,"checkboxes")" />',_('名称'), _('父级'), _('营销层级'), _('所属战区'), _('所属分区'), _('地址'),_('联系电话'), _('终端店'), _('渠道'), '操作']
                sWhere = " where id in (select id from company_company where id in (select unnest(agent_ids) from company_staffsaldiv where user_id = " + uid + " ))"
                s = "select id,name," + \
                    "coalesce((select name from company_company where id=a.parent_id),'')," + \
                    "coalesce((select name from company_level where id=a.level_id),'')," + \
                    "coalesce((select name from company_salesdivision where id=division_id),'')," + \
                    "coalesce((select name from company_subsaldivision where id=sub_division_id),'')," + \
                    "coalesce(address,''),coalesce(cell_phone,'')," + \
                    "case when is_terminal then '是' else '否' end, " + \
                    "coalesce((select name from company_channel where id=channel_id),'') " + \
                    "from company_company a " + sWhere
                cur.execute(s)
                rs = cur.fetchall()
                for r in rs:
                    check_box = '<input οnclick="selectList(this)" class="checkchild" value="' + str(r[0]) + '" type="checkbox">'
                    data['data'].append([check_box, r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9]])
            return render(request, 'company/saleman_transfer.html', data)
        return render(request, 'obj/list_obj_dlg.html', data)
            
    
    return render(request,'company/saleman.html')
    
@login_required
def saleman_manage_data(request,what):
    data={
        'e':'',
        'dt':False,
        'date_from':'',
        'date_to':'',
        'data':[]
    }
    u=request.user
    c=request.user.company
    cur=connection.cursor() 
    
    if what == "list":
        sql = "SELECT id,last_name,username, "+\
              "(SELECT name FROM company_department where id = (SELECT department_id FROM company_staff WHERE user_id = u.id)), "+\
              " array_to_string(array(select name from product_series where id in (select unnest(product_series))),','), "+\
              "phone,last_login "+\
              "FROM company_user as u where ancestor_id = "+str(c.ancestor_id)+" and "+\
              "((select count(id) from company_user_groups where user_id = u.id and group_id = 8)>0)" 
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            btns = f'<a class="btn btn-sm btn-default btn-dlg" href="/company/saleman/manage/?obj=performance&uid={r[0]}">业绩查询</a>'+\
                   f'<a class="btn btn-sm btn-default btn-dlg" href="/company/saleman/manage/?obj=agent&uid={r[0]}">授权终端</a>'+\
                   f'<a class="btn btn-sm btn-default btn-dlg" href="/company/saleman/manage/?obj=saleman_transfer&uid={r[0]}">人员转移</a>' + \
                   f'<a class="btn btn-sm btn-default btn-dlg" href="/company/saleman/manage/?obj=agent_performance&uid={r[0]}">对应终端业绩</a>'
            
            data['data'].append([ 
                '<a href="/obj/edit/user/'+str(r[0])+'/">'+r[1]+'</a>',
                r[2],
                r[3],
                r[4],
                r[5],
                r[6],
                btns
            ])
    elif what == "performance":
        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 
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        cur = connection.cursor()
        sql = f"""SELECT
                    product_id,
                    series_id,
                    user_name,
                    ( SELECT NAME FROM product_series WHERE ID = series_id ),
                    ( SELECT NAME FROM product_product WHERE ID = product_id ),
                    SUM ( qty ) qty,
                    price,
                    SUM ( amount ),
                    SUM ( x_r ) x_r,
                    SUM ( x_t ) x_t,
                    SUM ( p_r ) p_r,
                    SUM ( p_t ) p_t
                FROM
                    (
                    SELECT
                        product_id,
                        company_id,
                        (
                        SELECT
                            user_name 
                        FROM
                            logistics.company_staffsaldiv 
                        WHERE
                            ARRAY [ G.company_id ] <@agent_ids 
                            AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) limit 1
                        ),
                        C.NAME,
                        P.series_id,
                        P.NAME,
                        ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                        P.price,
                        ( ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) ) * P.price amount,
                        x_r,
                        x_t,
                        p_r,
                        p_t 
                    FROM
                        (
                        SELECT
                            product_id,
                            company_id,
                            SUM ( x_r ) x_r,
                            SUM ( p_r ) p_r,
                            SUM ( x_t ) x_t,
                            SUM ( p_t ) p_t 
                        FROM
                            (
                            SELECT
                                product_id,
                                company_id,
                            CASE
                                    
                                    WHEN label_pkg = 3 
                                    AND vtype_id in (1,2) THEN
                                        1 ELSE 0 
                                    END x_r,
                            CASE
                                    
                                    WHEN label_pkg = 1 
                                    AND vtype_id in (1,2) THEN
                                        1 ELSE 0 
                                    END p_r,
                            CASE
                                
                                WHEN label_pkg = 3 
                                AND vtype_id = 40 THEN
                                1 ELSE 0 
                                END x_t,
                            CASE
                                
                                WHEN label_pkg = 1 
                                AND vtype_id = 40 THEN
                                1 ELSE 0 
                                END p_t 
                            FROM
                                stkdetails.c{ancestor_id} 
                            WHERE
                                ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                                AND (
                                (
                                    company_id IN (
                                    SELECT ID 
                                    FROM
                                        logistics.company_company 
                                    WHERE
                                        is_terminal = TRUE 
                                        AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE company_id = {ancestor_id} ) 
                                    ) 
                                ) 
                                OR (
                                    company_id IN (
                                    SELECT ID 
                                    FROM
                                        logistics.company_company 
                                    WHERE
                                        level_id = 4 
                                        AND is_terminal = FALSE 
                                        AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE company_id = {ancestor_id} ) 
                                    ) 
                                    AND ( SELECT series_id FROM product_product WHERE ID = product_id ) = 150 
                                ) 
                            ) 
                    ) d 
                GROUP BY
                    product_id,
                    company_id 
                    )
                    G LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.
                    ID LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) C ON G.company_id = C.ID 
                    ) z 
                GROUP BY
                    product_id,
                    series_id,
                    user_name,
                    price
            """
        
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs: 
            data['data'].append([r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]]) 
    
    elif what == "performance_agent":
        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 
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        cur = connection.cursor()
        sql = f"""SELECT
                    product_id,
                    company_id,
                    (
                    SELECT
                        user_name 
                    FROM
                        logistics.company_staffsaldiv 
                    WHERE
                        ARRAY [ G.company_id ] <@agent_ids 
                        AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                        limit 1
                    ),
                    C.NAME,
                    ( SELECT NAME FROM product_series WHERE ID = P.series_id ),
                    P.NAME,
                    ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                    P.price,
                    (( x_r - x_t ) * P.qty_p + ( p_r - p_t ))* P.price amount,
                    x_r,
                    x_t,
                    p_r,
                    p_t,
                    e.name,
                    m.name
                FROM
                    (
                    SELECT
                        product_id,
                        company_id,
                        batch_id,
                        SUM ( x_r ) x_r,
                        SUM ( p_r ) p_r,
                        SUM ( x_t ) x_t,
                        SUM ( p_t ) p_t 
                    FROM
                        (
                        SELECT
                            product_id,
                            company_id,
                            batch_id,
                        CASE
                            WHEN label_pkg = 3 
                            AND vtype_id in(1,2) THEN
                                1 ELSE 0 
                            END x_r,
                        CASE
                            
                            WHEN label_pkg = 1 
                            AND vtype_id in(1,2) THEN
                            1 ELSE 0 
                            END p_r,
                        CASE
                            
                            WHEN label_pkg = 3 
                            AND vtype_id = 40 THEN
                            1 ELSE 0 
                            END x_t,
                        CASE
                            
                            WHEN label_pkg = 1 
                            AND vtype_id = 40 THEN
                            1 ELSE 0 
                            END p_t 
                        FROM
                            stkdetails.c{ancestor_id} 
                        WHERE
                            ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                            AND vtype_id IN ( 1, 40 ) 
                            AND (
                                (
                                    company_id IN (
                                    SELECT ID 
                                    FROM
                                        logistics.company_company 
                                    WHERE
                                        is_terminal = TRUE 
                                        AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE company_id = 19318 ) 
                                    ) 
                                ) 
                                OR (
                                    company_id IN (
                                    SELECT ID 
                                    FROM
                                        logistics.company_company 
                                    WHERE
                                        level_id = 4 
                                        AND is_terminal = FALSE 
                                        AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE company_id = 19318 ) 
                                    ) 
                                    AND ( SELECT series_id FROM product_product WHERE ID = product_id ) = 150 
                                ) 
                            )
                    ) d 
                GROUP BY
                    product_id,
                    company_id,
                    batch_id
                    )
                    G LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.
                    ID LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) C ON G.company_id = C.ID
                    left outer join  (SELECT company_fr_id ,id  from inventory_batch )f on f.id=g.batch_id
                    left outer join ( select id,name,level_id from company_company )e on e.id = f.company_fr_id  
                    left outer  JOIN	(SELECT id ,name FROM company_level)m on m.id = e.level_id            
        """
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs: 
            data['data'].append([r[2],r[3],r[-2],r[-1],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12]])
    
    elif what == "performance_level2":
        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
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        cur = connection.cursor()
        sql = f"""SELECT
                                product_id,
                                company_id,
                                coalesce((
                                SELECT
                                    user_name 
                                FROM
                                    logistics.company_staffsaldiv 
                                WHERE
                                    (ARRAY [ G.company_to_id ] <@agent_ids or ARRAY [ G.company_id ] <@agent_ids )
                                    AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                                    limit 1
                                ),''),
                                C.NAME,
                                ( SELECT NAME FROM product_series WHERE ID = P.series_id ),
                                P.NAME,
                                ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                                P.price,
                                (( x_r - x_t ) * P.qty_p + ( p_r - p_t ))* P.price amount,
                                x_r,
                                x_t,
                                p_r,
                                p_t,
                                e.name,
                                f.name
                            FROM
                                (
                                SELECT
                                    product_id,
                                    company_id,
                                    company_to_id,
                                    SUM ( x_r ) x_r,
                                    SUM ( p_r ) p_r,
                                    SUM ( x_t ) x_t,
                                    SUM ( p_t ) p_t 
                                FROM
                                    (
                                    SELECT
                                        product_id,
                                        company_id,
                                        company_to_id,
                                    CASE
                                        WHEN label_pkg = 3 
                                        AND vtype_id in(1,2) THEN
                                            1 ELSE 0 
                                        END x_r,
                                    CASE
                                        WHEN label_pkg = 1 
                                        AND vtype_id in(1,2) THEN
                                        1 ELSE 0 
                                        END p_r,
                                    CASE
                                        WHEN label_pkg = 3 
                                        AND vtype_id in(4,40)   THEN
                                        1 ELSE 0 
                                        END x_t,
                                    CASE
                                        WHEN label_pkg = 1 
                                        AND vtype_id in(4,40)  THEN
                                        1 ELSE 0 
                                        END p_t 
                                    FROM
                                        stkdetails.c{ancestor_id} 
                                    WHERE
                                        ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                                        AND vtype_id IN ( 2,40,4 ) 
                                        AND ( company_to_id not in( 115389,11013,11014)  or company_to_id is NULL)
                                    ) d 
                            GROUP BY
                                product_id,
                                company_id ,     
                                company_to_id
                                )G 
                                LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.ID 
                                LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id, level_id FROM logistics.company_company ) C ON G.company_id = C.ID
                                LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) e ON G.company_to_id = e.ID
    	                        LEFT OUTER JOIN ( SELECT ID, NAME FROM logistics.company_level ) f ON c.level_id = f.id
                                where level_id >= 2 
                        """
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            data['data'].append([r[2], r[3], r[13], r[14], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12]])
    elif what == "performance_level2_backup":
        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
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        cur = connection.cursor()
        sql = f"""SELECT
                            product_id,
                            company_id,
                            coalesce((
                            SELECT
                                user_name 
                            FROM
                                logistics.company_staffsaldiv 
                            WHERE
                                ARRAY [ G.company_to_id ] <@agent_ids 
                                AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                                limit 1
                            ),''),
                            C.NAME,
                            ( SELECT NAME FROM product_series WHERE ID = P.series_id ),
                            P.NAME,
                            ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                            P.price,
                            (( x_r - x_t ) * P.qty_p + ( p_r - p_t ))* P.price amount,
                            x_r,
                            x_t,
                            p_r,
                            p_t,
                            e.name,
                            f.name
                        FROM
                            (
                            SELECT
                                product_id,
                                company_id,
                                company_to_id,
                                SUM ( x_r ) x_r,
                                SUM ( p_r ) p_r,
                                SUM ( x_t ) x_t,
                                SUM ( p_t ) p_t 
                            FROM
                                (
                                SELECT
                                    product_id,
                                    company_id,
                                    company_to_id,
                                CASE
                                    WHEN label_pkg = 3 
                                    AND vtype_id in(1,2) THEN
                                        1 ELSE 0 
                                    END x_r,
                                CASE
                                    WHEN label_pkg = 1 
                                    AND vtype_id in(1,2) THEN
                                    1 ELSE 0 
                                    END p_r,
                                CASE
                                    WHEN label_pkg = 3 
                                    AND vtype_id = 40 THEN
                                    1 ELSE 0 
                                    END x_t,
                                CASE
                                    WHEN label_pkg = 1 
                                    AND vtype_id = 40 THEN
                                    1 ELSE 0 
                                    END p_t 
                                FROM
                                    stkdetails.c{ancestor_id} 
                                WHERE
                                    ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                                    AND vtype_id IN ( 2,40 ) 
                                    AND company_to_id not in( 115389,11013,11014) 
                                ) d 
                        GROUP BY
                            product_id,
                            company_id ,     
                            company_to_id
                            )G 
                            LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.ID 
                            LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id, level_id FROM logistics.company_company ) C ON G.company_id = C.ID
                            LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) e ON G.company_to_id = e.ID
	                        LEFT OUTER JOIN ( SELECT ID, NAME FROM logistics.company_level ) f ON c.level_id = f.id
                            where level_id = 2
                    """
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            data['data'].append([r[2], r[3],r[13],r[14], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12]])

    elif what == 'banquet':
        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
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        cur = connection.cursor()
        sql = f"""
            SELECT
                product_id,
                company_id,
                COALESCE (
                    (
                    SELECT
                        user_name 
                    FROM
                        logistics.company_staffsaldiv 
                    WHERE
                        ARRAY [ G.company_id ] <@agent_ids 
                        AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                        LIMIT 1 
                    ),
                    '' 
                ),
                C.NAME,
                ( SELECT NAME FROM product_series WHERE ID = P.series_id ),
                P.NAME,
                ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                P.price,
                ( ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) ) * P.price amount,
                x_r,
                x_t,
                p_r,
                p_t,
                b.user_name,
                b.user_phone,
                b.policy
            FROM
                (
                SELECT
                    product_id,
                    company_id,
                    company_to_id,
                    apply_id,
                    SUM ( x_r ) x_r,
                    SUM ( p_r ) p_r,
                    SUM ( x_t ) x_t,
                    SUM ( p_t ) p_t 
                FROM
                    (
                    SELECT
                        product_id,
                        company_id,
                        company_to_id,
                        (select apply_id from banquet_apply_codes where code = label_code ORDER BY id desc limit 1 ) as apply_id,
                    CASE
                            
                            WHEN label_pkg = 3 
                            AND vtype_id IN ( 1, 2 ) THEN
                                1 ELSE 0 
                            END x_r,
                    CASE
                        
                        WHEN label_pkg = 1 
                        AND vtype_id IN ( 1, 2 ) THEN
                        1 ELSE 0 
                        END p_r,
                    CASE
                        
                        WHEN label_pkg = 3 
                        AND vtype_id = 40 THEN
                        1 ELSE 0 
                        END x_t,
                    CASE
                        
                        WHEN label_pkg = 1 
                        AND vtype_id = 40 THEN
                        1 ELSE 0 
                        END p_t 
                    FROM
                        stkdetails.c19318 
                    WHERE
                        ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                        AND vtype_id IN ( 2, 40 ) 
                        AND ( ( company_id IN ( SELECT ID FROM logistics.company_company WHERE level_id = 2 ) AND ( company_to_id = 115389 ) ) ) 
                        ) d 
            GROUP BY
                product_id,
                company_id,
                company_to_id,
                apply_id
                )
                G LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.
                ID LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) C ON G.company_id = C.
                ID
                LEFT OUTER JOIN ( SELECT ID, user_name, user_phone, policy FROM logistics.banquet_apply ) b ON b.id = G.apply_id
        """
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            data['data'].append([r[13],r[14],r[15], r[3], r[14], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12]])

    elif what == 'group_purchase':
        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
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        cur = connection.cursor()
        sql = f"""SELECT
                                    product_id,
                                    company_id,
                                    coalesce((
                                    SELECT
                                        user_name 
                                    FROM
                                        logistics.company_staffsaldiv 
                                    WHERE
                                        ARRAY [ G.company_id ] <@agent_ids 
                                        AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                                        limit 1
                                    ),''),
                                    C.NAME,
                                    ( SELECT NAME FROM product_series WHERE ID = P.series_id ),
                                    P.NAME,
                                    ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                                    P.price,
                                    (( x_r - x_t ) * P.qty_p + ( p_r - p_t ))* P.price amount,
                                    x_r,
                                    x_t,
                                    p_r,
                                    p_t,
                                    e.name,
                                    f.name,
                                    coalesce((select customer_company from inventory_batch where id = batch_id),''),
                                    coalesce((select customer_name from inventory_batch where id = batch_id),''),
                                    coalesce((select customer_phone from inventory_batch where id = batch_id),'')
                                FROM
                                    (
                                    SELECT
                                        product_id,
                                        company_id,
                                        company_to_id,
                                        batch_id,
                                        SUM ( x_r ) x_r,
                                        SUM ( p_r ) p_r,
                                        SUM ( x_t ) x_t,
                                        SUM ( p_t ) p_t 
                                    FROM
                                        (
                                        SELECT
                                            product_id,
                                            company_id,
                                            company_to_id,
                                            batch_id,
                                        CASE
                                            WHEN label_pkg = 3 
                                            AND vtype_id in(1,2) THEN
                                                1 ELSE 0 
                                            END x_r,
                                        CASE
                                            WHEN label_pkg = 1 
                                            AND vtype_id in(1,2) THEN
                                            1 ELSE 0 
                                            END p_r,
                                        CASE
                                            WHEN label_pkg = 3 
                                            AND vtype_id = 40 THEN
                                            1 ELSE 0 
                                            END x_t,
                                        CASE
                                            WHEN label_pkg = 1 
                                            AND vtype_id = 40 THEN
                                            1 ELSE 0 
                                            END p_t 
                                        FROM
                                            stkdetails.c{ancestor_id} 
                                        WHERE
                                            ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                                            AND vtype_id IN ( 2,40 ) 
                                            AND ((
                                                company_id IN (
                                                SELECT ID 
                                                FROM
                                                    logistics.company_company 
                                                WHERE
                                                    level_id >= 2 and ancestor_id = {ancestor_id} 
                                                ) 
                                                and (company_to_id in ( 11013,11014)) 
                                            ) 
                                        ) 
                                        ) d 
                                GROUP BY
                                    product_id,
                                    company_id ,     
                                    company_to_id,
                                    batch_id
                                    )G 
                                    LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.ID 
                                    LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) C ON G.company_id = C.ID
                                    LEFT OUTER JOIN ( SELECT ID, NAME,level_id, division_id, sub_division_id FROM logistics.company_company ) e ON G.company_id = e.ID
        	                        LEFT OUTER JOIN ( SELECT ID, NAME FROM logistics.company_level ) f ON e.level_id = f.id
                            """
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            data['data'].append([r[13], r[3], r[14], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12],r[15],r[16],r[17]])
    


    elif what == "trace":
        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 
        data["dt"] = True
        ancestor_id = c.ancestor_id
        sWhere=f" where tm::date >= '{dt_fr}' and tm::date <= '{dt_to}' and ancestor_id = {ancestor_id}"
        
        cur = connection.cursor()
        cur.execute("SELECT (select last_name from company_user where id = uid ),"+\
                    "(SELECT name from company_company where id = dst_compid), "+\
                    "id,uid,lng_lat,dst_compid,distance,tm,coalesce(contents,''),coalesce(photo,''), "+\
                    "coalesce((select name from company_channel where id = (select channel_id from company_company where id = dst_compid)),''),"+\
                    "array_to_string(array(select name from company_channel_level where id in (select unnest(channel_level_ids) from company_company where id = dst_compid)),','),"+\
                    "coalesce((SELECT name FROM company_department where id = (SELECT department_id FROM company_staff WHERE user_id = uid)),'') "+\
                    "FROM z_salesmancheckin"+sWhere)
        rs = cur.fetchall() 
        for r in rs:
            btns = ''
            dt=r[7].strftime("%Y-%m-%d") 
            btns = f'<a class="btn btn-sm btn-default btn-dlg" href="company/saleman/checkin/photos/?id={r[2]}">查看图片</a>'
            btns = btns + f'<a class="btn btn-sm btn-default btn-dlg" href="company/saleman/checkin/trace/?uid={r[3]}&dt={dt}">当日轨迹</a>'
                
            data['data'].append([
                str(r[0]),
                str(r[1]),
                r[12],
                r[10],
                r[11],
                str(r[6])+'米',
                r[7].strftime("%Y-%m-%d %H:%M:%S"),
                r[8],
                btns
            ])
    
    elif what == "action":
        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 
        data["dt"] = True
        ancestor_id = c.ancestor_id
        sWhere=f" where tm::date >= '{dt_fr}' and tm::date <= '{dt_to}' and company_id = {ancestor_id}"
        
        sql = "select id,(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)),''),"+\
              "(select name from sales_action_category where id = category_id),"+\
              "digest,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))),','),"+\
              "coalesce(address,''),remark,"+\
              "to_char(tm,'yyyy-mm-dd HH24:MI:SS'),status,"+\
              "coalesce(to_char(permit_tm,'yyyy-mm-dd HH24:MI:SS'),''),reason,"+\
              "annotation "+\
              " from sales_action "+ sWhere
        cur = connection.cursor()
        cur.execute(sql)
        rs = cur.fetchall() 
        for r in rs:
            btns = ''
            btns = f'<a class="btn btn-sm btn-default btn-dlg" href="company/saleman/manage/?obj=action_photos&action_id={r[0]}">查看图片</a>'
            status = r[10]
            if status == 0:
                status = "<button reg_id='" + str(
                    r[0]) + "' class='btn btn-xs btn-primary btn-approve' onclick='btn_approve("+str(r[0])+",\"approved\")'  >现在审核</button>" + \
                         "<button reg_id='" + str(
                    r[0]) + "' class='btn btn-xs btn-danger  btn-reject'  onclick='btn_approve("+str(r[0])+",\"rejected\")'  >驳回</button>"
            
            elif status == 1:
                status = '已通过'
            elif status == 2:
                status = '未通过'
                
            data['data'].append([ 
                r[1],
                r[2],
                r[3],
                r[4],
                r[5],
                r[6],
                r[7],
                r[8],
                r[9],
                status,
                btns
            ])
    elif what == "sharegroup":
        ancestor_id = c.ancestor_id
        sWhere = f'company_id = '+str(ancestor_id)
        sql = """SELECT 
                    id,
                    name,
                    array_to_string(array(select last_name from company_user where id in (select unnest(user_ids))),','),
	                array_to_string(array(select name from company_usersharethings where id in (select unnest(a.sharethings))),','),
                    coalesce((remark),''),
                    to_char(tm,'yyyy-mm-dd HH24:MI:SS')
                FROM company_usersharegroup a where """+sWhere
        cur = connection.cursor()
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            data['data'].append([
                r[1],
                r[2],
                r[3],
                r[4],
                r[5],
                '<input class="btn btn-default btn-sm" type="button" onclick="openDlg(\'修改\',\'/company/saleman/manage/?obj=sharegroup&id='+str(r[0])+'\')" value="修改" />'
            ])


    return JsonResponse(data)


@csrf_exempt
def ajax_saleman_manage_data(request,what):
    data={
        'e':''
    }
    cur=connection.cursor() 
    if what == "agent":
        data = {
            'e':'',
            'agents':[]
        }
        user_id = request.GET.get('userid','')
        if user_id:
            sql = f"""
                select UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE user_id = {user_id}
            """
            cur.execute(sql)
            rs = cur.fetchall()
            for r in rs:
                data['agents'].append({
                    "id":r[0]
                })
        else:
            data['e'] = '数据丢失'
    elif what == "performance_agent":
        data = {
            'e':'',
            'list':[],
            'summary': []
        }
        user_id = request.GET.get('userid','')
        ancestor_id = request.GET.get('ancestor_id','')
        if user_id and ancestor_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)
            
            month = request.GET.get('month','')
            if month:
                dt_fr = month+'-01'
                dt_to = datetime.datetime.strptime(month,'%Y-%m')
                monthCountDay = calendar.monthrange(dt_to.year,dt_to.month)[1]
                lastDay = datetime.date(dt_to.year,dt_to.month,day=monthCountDay)
                dt_to = lastDay.strftime('%Y-%m-%d')
            
            sql = f"""
                select *  into  temp  table res_infor from  (SELECT
                    product_id,
                    company_id,
                    ( SELECT last_name FROM company_user WHERE ID = user_id ),
                    agent_name,
                    series_name,
                    product_name,
                    qty,
                    price,
                    amount,
                    x_r,
                    x_t,
                    p_r,
                    p_t 
                FROM
                    (
                    SELECT
                        product_id,
                        company_id,
                        (
                        SELECT
                            user_id 
                        FROM
                            logistics.company_staffsaldiv 
                        WHERE
                            ARRAY [ G.company_id ] <@agent_ids 
                            AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                            LIMIT 1 
                        ),
                        C.NAME AS agent_name,
                        ( SELECT NAME FROM product_series WHERE ID = P.series_id ) AS series_name,
                        P.NAME AS product_name,
                        ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                        P.price,
                        ( ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) ) * P.price amount,
                        x_r,
                        x_t,
                        p_r,
                        p_t 
                    FROM
                        (
                        SELECT
                            product_id,
                            company_id,
                            SUM ( x_r ) x_r,
                            SUM ( p_r ) p_r,
                            SUM ( x_t ) x_t,
                            SUM ( p_t ) p_t 
                        FROM
                            (
                            SELECT
                                product_id,
                                company_id,
                            CASE
                                    
                                    WHEN label_pkg = 3 
                                    AND vtype_id = 1 THEN
                                        1 ELSE 0 
                                    END x_r,
                            CASE
                                    
                                    WHEN label_pkg = 1 
                                    AND vtype_id = 1 THEN
                                        1 ELSE 0 
                                    END p_r,
                            CASE
                                
                                WHEN label_pkg = 3 
                                AND vtype_id = 40 THEN
                                1 ELSE 0 
                                END x_t,
                            CASE
                                
                                WHEN label_pkg = 1 
                                AND vtype_id = 40 THEN
                                1 ELSE 0 
                                END p_t 
                            FROM
                                stkdetails.c{ancestor_id} 
                            WHERE
                                ancestor_id = {ancestor_id} 
                                AND ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                                AND (
                                    (
                                        company_id IN (
                                        SELECT ID 
                                        FROM
                                            logistics.company_company 
                                        WHERE
                                            is_terminal = TRUE 
                                            AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE user_id = {user_id} ) 
                                        ) 
                                    ) 
                                    OR (
                                        company_id IN (
                                        SELECT ID 
                                        FROM
                                            logistics.company_company 
                                        WHERE
                                            level_id = 4 
                                            AND is_terminal = FALSE 
                                            AND ID IN ( SELECT UNNEST ( agent_ids ) AS agent_id FROM logistics.company_staffsaldiv WHERE company_id = {ancestor_id} ) 
                                        ) 
                                        AND ( SELECT series_id FROM product_product WHERE ID = product_id ) = 150 
                                    ) 
                                ) 
                                ) d 
                            GROUP BY
                                product_id,
                                company_id 
                                )
                                G LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, COALESCE ( price, 0 ) AS price FROM logistics.product_product ) P ON G.product_id = P.
                                ID LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) C ON G.company_id = C.ID 
                                ) outter 
                            WHERE
                            outter.user_id = {user_id})a"""
            cur.execute(sql)
            s = "select * from res_infor"
            cur.execute(s)
            rs = cur.fetchall()
            for r in rs:
                data['list'].append({
                    'product_id':r[0],
                    'agent_id':r[1],
                    'user_name':r[2],
                    'agent_name':r[3],
                    'product_series_name':r[4],
                    'product_name':r[5],
                    'qty':r[6],
                    'price':r[7],
                    'amount':r[8],
                    'x_r':r[9],
                    'x_t':r[10],
                    'p_r':r[11],
                    'p_t':r[12]
                })
            s = "select product_id,product_name,sum(qty),sum(amount) from res_infor group by product_id, product_name"
            cur.execute(s)
            rs = cur.fetchall()
            for i in rs:
                data['summary'].append({"product_name":i[1],
                                        'qty': i[2],
                                        'amount': i[3],})   
        else:
            data['e'] = '数据丢失'
    elif what == "trace":
        ancestor_id = request.GET.get('ancestor_id','')            
        tm_start = request.GET.get('tm_start','')
        tm_end = request.GET.get('tm_end','')
        last_name = request.GET.get('last_name','')

        if ancestor_id and tm_start and tm_end:
            sWhere=f" where ancestor_id = {ancestor_id} and tm >= '{tm_start}' and tm<= '{tm_end}' "
            if last_name:
                sWhere = sWhere + f" and uid in (select id from company_user where ancestor_id = {ancestor_id} and last_name like '%{last_name}%') "
            
            
            cur.execute("SELECT (select last_name from company_user where id = uid ),"+\
                        "(SELECT name from company_company where id = dst_compid), "+\
                        "id,uid,lng_lat,dst_compid,distance,tm,coalesce(contents,''),coalesce(photo,''), "+\
                        "coalesce((select name from company_channel where id = (select channel_id from company_company where id = dst_compid)),''),"+\
                        "array_to_string(array(select name from company_channel_level where id in (select unnest(channel_level_ids) from company_company where id = dst_compid)),','),"+\
                        "coalesce((SELECT name FROM company_department where id = (SELECT department_id FROM company_staff WHERE user_id = uid)),'') "+\
                        "FROM z_salesmancheckin"+sWhere+" order by id desc")
            rs = cur.fetchall() 
            arr = []
            for r in rs:
                dt=r[7].strftime("%Y-%m-%d") 
                
                arr.append({
                    'id': r[2],
                    'userName':str(r[0]),
                    'company_name':str(r[1]),
                    'department':r[12],
                    'channel':r[10],
                    'channelLevel':r[11],
                    'distance':str(r[6]),
                    'tm':r[7].strftime("%Y-%m-%d %H:%M:%S"),
                    'report':r[8],
                    'dt':dt
                })
            data['data'] = arr
        else:
            data['e'] = '数据丢失'
    elif what == "traceDetail":
        ancestor_id = request.GET.get('ancestor_id','')  
        id = request.GET.get('id','')   
        if ancestor_id and id:
            cur = connection.cursor()
            ssql = 'select uid,lng_lat,dst_compid,(SELECT name from company_company where id = dst_compid),distance,'+\
                   'tm,photo,contents,photo_mentou,photo_chenlie,(select last_name from company_user where id = uid ) from z_salesmancheckin where id = '+id
                   
            cur.execute(ssql)
            r = cur.fetchone()
            if r:
                uid = r[0]
                d = {
                    'uid': uid,
                    'lng_lat': [float(r[1][0]),float(r[1][1])],
                    'dst_compid': r[2],
                    'comp_name': r[3],
                    'distance': r[4],
                    'tm': r[5].strftime("%Y-%m-%d %H:%M:%S"),
                    'photo': r[6],
                    'contents': r[7],
                    'photo_mentou': r[8],
                    'photo_chenlie': r[9],
                    'last_name': r[10]
                }
                    
                data['record'] = d
                
                dt=r[5].strftime("%Y-%m-%d") 
                
                sWhere = f"where uid = {uid} and tm::date >= '{dt}' order by id"
                cur.execute(f"""select 
                                    (SELECT name from company_company where id = dst_compid), 
                                    lng_lat,
                                    tm
                                    from z_salesmancheckin {sWhere}""")
                records = []
                rs = cur.fetchall()
                if rs:
                    for r in rs:
                        records.append({
                            'comp_name': r[0],
                            'lng_lat': [float(r[1][0]),float(r[1][1])],
                            'tm':r[2].strftime("%Y-%m-%d %H:%M:%S")
                        })
                data['records'] = records
    elif what == "performance_level2":
        data = {
            'e': '',
            'list': [],
            'summary': []
        }
        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)
        ancestor_id = request.GET.get('ancestor_id', '')
        user_id = request.GET.get('userid', '')
        month = request.GET.get('month', '')
        if month:
            dt_fr = month + '-01'
            dt_to = datetime.datetime.strptime(month, '%Y-%m')
            monthCountDay = calendar.monthrange(dt_to.year, dt_to.month)[1]
            lastDay = datetime.date(dt_to.year, dt_to.month, day=monthCountDay)
            dt_to = lastDay.strftime('%Y-%m-%d')
        cur = connection.cursor()
        sql = f""" select *  into  temp  table res_temp from  ( SELECT product_id,
                        company_id,
                        ( SELECT last_name FROM company_user WHERE ID = user_id ),
                        company_name,
                        series_name,
                        p_name,
                        qty,
                        price, amount,
                        x_r,
                        x_t,
                        p_r,
                        p_t,
                        c_name,
                        level_name
						from  
						(SELECT
                        product_id,
                        company_id,
                        (
                        SELECT
                            user_id
                        FROM 
                            logistics.company_staffsaldiv 
                        WHERE 
                            (ARRAY [ G.company_to_id ] <@agent_ids or ARRAY [ G.company_id ] <@agent_ids )
                            AND ( SELECT ARRAY [ P.series_id ] <@product_series FROM logistics.company_user WHERE ID = user_id ) 
                            limit 1
                        ),
                        C.NAME company_name,
                        ( SELECT NAME FROM product_series WHERE ID = P.series_id ) series_name,
                        P.NAME p_name,
                        ( x_r - x_t ) * P.qty_p + ( p_r - p_t ) qty,
                        P.price,
                        (( x_r - x_t ) * P.qty_p + ( p_r - p_t ))* P.price amount,
                        x_r,
                        x_t,
                        p_r,
                        p_t,
                        e.name c_name,
                        f.name level_name
                    FROM
                        (
                        SELECT
                            product_id,
                            company_id,
                            company_to_id,
                            SUM ( x_r ) x_r,
                            SUM ( p_r ) p_r,
                            SUM ( x_t ) x_t,
                            SUM ( p_t ) p_t 
                        FROM
                            (
                            SELECT
                                product_id,
                                company_id,
                                company_to_id,
                            CASE
                                WHEN label_pkg = 3 
                                AND vtype_id in(1,2) THEN
                                    1 ELSE 0 
                                END x_r,
                            CASE
                                WHEN label_pkg = 1 
                                AND vtype_id in(1,2) THEN
                                1 ELSE 0 
                                END p_r,
                            CASE
                                WHEN label_pkg = 3 
                                AND vtype_id in(4,40)   THEN
                                1 ELSE 0 
                                END x_t,
                            CASE
                                WHEN label_pkg = 1 
                                AND vtype_id in(4,40)  THEN
                                1 ELSE 0 
                                END p_t 
                            FROM
                                stkdetails.c{ancestor_id} 
                            WHERE
                                ( dt BETWEEN '{dt_fr}' AND '{dt_to}' ) 
                                AND vtype_id IN ( 2,40,4 ) 
                                AND ( company_to_id not in( 115389,11013,11014)  or company_to_id is NULL)
                            ) d 
                    GROUP BY
                        product_id ,
                        company_id ,     
                        company_to_id
                        )G 
                        LEFT OUTER JOIN ( SELECT ID, NAME, qty_p, series_id, price FROM logistics.product_product ) P ON G.product_id = P.ID 
                        LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id, level_id FROM logistics.company_company ) C ON G.company_id = C.ID
                        LEFT OUTER JOIN ( SELECT ID, NAME, division_id, sub_division_id FROM logistics.company_company ) e ON G.company_to_id = e.ID
                        LEFT OUTER JOIN ( SELECT ID, NAME FROM logistics.company_level ) f ON c.level_id = f.id
                        where level_id >= 2  )outter WHERE user_id = {user_id})a  ;
                """
        cur.execute(sql)
        s = "select * from res_temp "
        cur.execute(s)
        rs = cur.fetchall()
        for r in rs:
            data['list'].append({
                'product_id': r[0],
                'agent_id': r[1],
                'user_name': r[2],
                'agent_name': r[3],
                'product_series_name': r[4],
                'product_name': r[5],
                'qty': r[6],
                'price': r[7],
                'amount': r[8],
                'x_r': r[9],
                'x_t': r[10],
                'p_r': r[11],
                'p_t': r[12],
                'next_agent':r[-2],
                'level':r[-1]
            })
        s = "select p_name,sum(qty),sum(amount) from res_temp  group by  p_name having sum(qty) >0"
        cur.execute(s)
        rs = cur.fetchall()
        for i in rs:
            data['summary'].append({"product_name": i[0],
                                    'qty': i[1],
                                    'amount': i[2], })

    return JsonResponse(data)


#2021-02-04 提交申请 处理程序 
def application_submit00(user_id,company_id,content_type,info):
    data={'e':''}   
    c=Company.objects.get(id=company_id)   
    u=User.objects.get(id=user_id)  
    if u.company_id!=company_id:
        data['e']='company, user not match'
        return data
    m=apps.get_model('company', content_type)
    app_id=info['app_id']
    if not app_id:
        if content_type in ['wxwalletapplication','bankinfoapplication']:
            #如果有未申批完成的申请，不能提交新申请
            if m.objects.filter(company_id=company_id,user_id=user_id).exclude(status_id__in=[5,6]).all():
                data['e']='当前有申请还在审核过程中，请不要重复申请。'
                return data
    if app_id:
        app=m.objects.get(id=app_id)
        if content_type in ['wxwalletapplication','bankinfoapplication']:
            app.status_id==4
    else:
        app=m()    
    app.ancestor_id=c.ancestor_id
    app.company_id=info['company_id']
    app.user_id=info['user_id']   
    app.wxopenid_id=info['wxopenid_id']
    app.nickname=info['nickname']
    app.headimgurl=info['headimgurl']

    if content_type=='wxwalletapplication':
        app.payee_company_id=info['payee_company_id']
        app.payee_wxopenid_id=info['payee_wxopenid_id']
        app.realname=info['realname']
        app.cellphone=info['cellphone']
    elif content_type=='bankinfoapplication':
        app.payee_company_id=info['payee_company_id']            
        app.bank_name=info['bank_name']           
        app.bank_account=info['bank_account']            
        app.payee=info['payee']            
    app.save()
    return data


#2021-02-20 提交申请 处理程序 
def application_submit(user_id,company_id,content_type,info):
    data={'e':''}   
    c=Company.objects.get(id=company_id)   
    u=User.objects.get(id=user_id)  
    
    if u.company_id!=company_id:
        data['e']='company, user not match'
        return data


    m=apps.get_model('company', content_type)
    if info['application_id']:
        app=m.objects.get(id=info['application_id'])
        app.status_id=4
        app.dt=datetime.datetime.now()
        app.tm=datetime.datetime.now()
        #删除已有日志?   
        for l in ApplicationReviewLog.objects.filter(content_type='wxwalletapplication',obj_id=app.id):
            l.delete()
    else:
        app=m() 
    app.ancestor_id=c.ancestor_id
    app.company_id=info['company_id']
    app.user_id=info['user_id']   
    app.wxopenid_id=info['wxopenid_id']
    app.nickname=info['nickname']
    app.headimgurl=info['headimgurl']

    if content_type=='wxwalletapplication':
        app.payee_company_id=info['payee_company_id']
        app.payee_wxopenid_id=info['payee_wxopenid_id']
        app.realname=info['realname']
        app.cellphone=info['cellphone']
    elif content_type=='bankinfoapplication':
        app.payee_company_id=info['payee_company_id']            
        app.bank_name=info['bank_name']           
        app.bank_account=info['bank_account']            
        app.payee=info['payee']            
    app.save()

    '''
    app_id=info['app_id']
    if not app_id:
        if content_type in ['wxwalletapplication','bankinfoapplication']:
            #如果有未申批完成的申请，不能提交新申请
            if m.objects.filter(company_id=company_id,user_id=user_id).exclude(status_id__in=[5,6]).all():
                data['e']='当前有申请还在审核过程中，请不要重复申请。'
                return data
    if app_id:
        app=m.objects.get(id=app_id)
        if content_type in ['wxwalletapplication','bankinfoapplication']:
            app.status_id==4
    else:
        app=m()    
    app.ancestor_id=c.ancestor_id
    app.company_id=info['company_id']
    app.user_id=info['user_id']   
    app.wxopenid_id=info['wxopenid_id']
    app.nickname=info['nickname']
    app.headimgurl=info['headimgurl']

    if content_type=='wxwalletapplication':
        app.payee_company_id=info['payee_company_id']
        app.payee_wxopenid_id=info['payee_wxopenid_id']
        app.realname=info['realname']
        app.cellphone=info['cellphone']
    elif content_type=='bankinfoapplication':
        app.payee_company_id=info['payee_company_id']            
        app.bank_name=info['bank_name']           
        app.bank_account=info['bank_account']            
        app.payee=info['payee']            
    app.save()
    '''
    return data



# 企业申请审批流 小程序(前端)接口
@csrf_exempt
def application_submit_app(request):
    data={'e':''}     
    e = time_key_check(request, sK)
    if e:
        data['e'] = e
        return JsonResponse(data)
    r=json.loads(request.body)
    e=[]    
    if 'user_id' not in r:
        e.append('user id missing')
    if 'content_type' not in r:
        e.append('content_type')
    if 'company_id' not in r:
        e.append('company id missing')
    if 'wxopenid' not in r:
        e.append('wxopenid  missing')
    else:
        openids=WxOpenid.objects.filter(wx_openid=r['wxopenid'])
        if not openids:
            e.append('wxopenid not match')
    if 'wxnickname' not in r:
        e.append('wxnickname missing')
    if 'headimgurl' not in r:
        e.append('headimgurl missing')
    
    if e:
        data['e']=','.join(e)
        return JsonResponse(data)
    content_type=r['content_type']
    user_id=int(r['user_id'])
    company_id=int(r['company_id'])
    wxopenid_id=openids[0].id
    wxnickname=r['wxnickname']
    headimgurl=r['headimgurl']
    app_id=0
    if 'application_id' in r:
        app_id=int(r['application_id'])    
    if content_type=='wxwalletapplication':
        #app_name='微信钱包审核'
        payeeopenids=openids=WxOpenid.objects.filter(wx_openid=r['payee_wxopenid'])
        if not payeeopenids:
            data['e']='wxopenid not match'
            return JsonResponse(data)
        else:
            payee_wxopenid_id=payeeopenids[0].id
        info={
            'application_id':app_id,
            'payee_company_id':int(r['payee_company_id']),
            'payee_wxopenid_id':payee_wxopenid_id,
            'realname':r['realname'],
            'cellphone':r['cellphone'],
        }        
    elif content_type=='bankinfoapplication':
        #app_name='银行卡审核'
        info={
            'application_id':app_id,
            'payee_company_id':int(r['payee_company_id']),
            'bank_name':r['bank_name'], 
            'bank_account':r['bank_account'],
            'payee':r['payee'],            
        }  
    #try
    info['company_id']=company_id
    info['user_id']=user_id
    info['wxopenid_id']=wxopenid_id
    info['nickname']=wxnickname
    info['headimgurl']=headimgurl
    data=application_submit(user_id,company_id,content_type,info)
    #data['app_name']=app_name
    return JsonResponse(data)


#2021-01-25
def application_approve(request):
    data={'e':'','status':''}
    c=request.user.company
    content_type=request.POST.get('content_type','')
    comment=request.POST.get('comment','')
    app_id=request.POST.get('app_id',0)
    group_id=request.POST.get('user_group_id',0)
    act=request.POST.get('action','approve')
    #django_content_type:199;"company";"wxwalletapplication"
    m = apps.get_model('company', content_type)
    app=m.objects.get(id=int(app_id))
    status_id=None
    if content_type in ['wxwalletapplication','bankinfoapplication']:        
        #7;"内勤管理组"  12;"销售助理" 18;"财务" 20;"出纳"
        #2;1;"内勤申核"   #3;2;"财务审核"  #4;10;"变更申请" #5;10000;"已确认"     
        if int(group_id)==12:            
            status_id=2
            data['status']="内勤申核"
        elif int(group_id)==18:
            status_id=3            
            data['status']='财务审核'       
        elif act=='reject':
            status_id=6            
            data['status']='已驳回'
        app.status_id=status_id
        if status_id==3:    #财务审核后,申请即被确认
            app.status_id=5
            data['status']='已确认'
            
            
            m = apps.get_model('company', content_type.replace('application',''))    
            #obj=m()
            
            #2021-05-19
            objs=m.objects.filter(application_id=app.id)
            if objs:
                obj=objs[0]
            else:
                obj=m()



            #为兼容2月5号前提交的申请
            if app.payee_company_id:
                payee_company_id=app.payee_company_id
            else:
                payee_company_id=app.company_id   
            
            
            if content_type=='bankinfoapplication': 
                for b in BankInfo.objects.filter(company_id=app.company_id):
                    b.is_default=False
                    b.save()
                obj.is_default=True
            
            obj.application_id=app.id
            obj.ancestor_id=app.ancestor_id
            obj.company_id=app.company_id
            if content_type=='wxwalletapplication':
                obj.wxopenid_id=app.payee_wxopenid_id
                obj.realname=app.realname 
                obj.cellphone=app.cellphone                
            else:
                obj.bank_name=app.bank_name
                obj.bank_account=app.bank_account
                obj.payee=app.payee               
            obj.save()   

        app.save()   
    log=ApplicationReviewLog(
        company_id=c.id,
        content_type=content_type,
        obj_id=int(app_id),
        status_id=status_id,
        user_id=request.user.id,
    )
    if comment:
        log.comment=comment
    log.save()        
    return JsonResponse(data)


# Jonathan
# 2020-12-15
@login_required
def white_domain(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['域名', '域名类型', '是否有效', '添加时间','操作']
    data['show_add'] = True
    data['murl'] = '/white_domain/edit/'

    for domain in White_Domain.objects.filter(company_id=request.user.company.id):
        flag = '否'
        if domain.is_active:
            flag = '是'
        data['data'].append([
            domain.domain,
            domain.domain_type.name,
            flag,
            domain.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/white_domain/edit/" +str(domain.id) + "/'>详情</a>" +
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(domain.id) + ")'>删除</button>"
        ])
    return render(request, 'obj/list_obj.html', data)


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

@login_required
def white_domain_delete(request, id=None):
    if id:
        obj = White_Domain.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/white_domain/')


@login_required
def third_party_company(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['第三方公司', '是否有效', '添加时间','操作']
    data['show_add'] = True
    data['murl'] = '/third_party_company/edit/'

    for t in Third_Party_Company.objects.filter(company_id=request.user.company.id):
        flag = '否'
        if t.is_active:
            flag = '是'
        data['data'].append([
            t.name,
            flag,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/third_party_company/edit/" + str(t.id) + "/'>详情</a>"
        ])
    return render(request, 'obj/list_obj.html', data)


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


# 绑定规则
@login_required
def label_bind_rule(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['绑定规则（箱-盒-瓶）', '是否可用', '时间','操作']
    data['show_add'] = True
    data['murl'] = '/label_bind_rule/edit/'

    for t in Label_Bind_Rule.objects.filter(company_id=request.user.company.id):
        flag = '否'
        if t.is_active:
            flag = '是'
        str_ = str(t.level_1)
        str_ += '-' + str(t.level_2)
        str_ += '-' + str(t.level_3)
        data['data'].append([
            str_,
            flag,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/label_bind_rule/edit/" + str(t.id) + "/'>详情</a>"+
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(t.id) + ")'>删除</button>"
        ])
    return render(request, 'obj/list_obj.html', data)

# 标签绑定删除
@login_required
def label_bind_rule_delete(request, id=None):
    if id:
        obj = Label_Bind_Rule.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/label_bind_rule/')


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


@csrf_exempt
def label_bind_rule_data(request, compid=None):
    data = {
        'e': '',
        'list': []
    }
    if compid:
        w = Label_Bind_Rule.objects.filter(company_id=int(compid), is_active=True)
        if w:
            for c in w:
                str_ = str(c.level_1)
                str_ += '-' + str(c.level_2)
                str_ += '-' + str(c.level_3)

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


# 域名白名单
@csrf_exempt
def white_domain_data(request, compid=None):
    data = {
        'e': '',
        'list': []
    }
    if compid:
        w = White_Domain.objects.filter(company_id=int(compid), domain_type=1, is_active=True)
        if w:
            for c in w:
                t = {
                    'id': c.id,
                    'domain': c.domain
                }
                data['list'].append(t)
    else:
        data['e'] = ' 数据丢失'
    return JsonResponse(data)


# 第三方公司
@csrf_exempt
def third_party_company_data(request, compid=None):
    data = {
        'e': '',
        'list': []
    }
    if compid:
        for t in Third_Party_Company.objects.filter(company_id=int(compid), is_active=True):
            ts = {
                'id': t.id,
                'name': t.name
            }
            data['list'].append(ts)
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)

 
# 序号绑定
@csrf_exempt 
def third_party_label_bind(request):
    data = {
        'e': '',
        'batch_id': '',
        'cnt': 0
    }
    path = "F:/datacenter/"+os.path.join("log","binds",time.strftime('%Y-%m-%d')+".txt") 
    f = open(path,'a')
    if request.method == 'POST':
        d = json.loads(request.body)
        
        f.write(time.strftime('%H:%M:%S')+":"+json.dumps(d))
        f.close() 
        
        if d['compid'] and d['uid']:
            compid = d['compid']
            uid = d['uid']
            third_party_compid = d['third_party_compid']
            remark = ''
            if 'remark' in d:
                remark = d['remark']
            if d['labels']:
                labels = d['labels']

                labels_len = range(len(labels))
                batch_id = str(time.strftime('%Y%m%d%H%M%S'))
                i = 0
                for c in labels_len:
                    #标签绑定规则
                    label_bind_rule = labels[c]['label_bind_rule']
                    #箱码 为数组 []
                    x_labels = labels[c]['label_code']
                    for x in range(len(x_labels)):
                        first_parent_id = 0
                        parent_id = 0
                        x_lbs = x_labels[x].split(',')
                        label_bar_code=x_lbs[2].split('HTTP')[0]
                        tp = Third_Party_Label_Bind(
                            company_id=compid,
                            user_id=uid,
                            label_type=labels[c]['label_type'],
                            label_code=x_lbs[0],
                            label_code_out=x_lbs[1],
                            label_bar_code=label_bar_code,
                            label_code_type=labels[c]['label_code_type'],
                            label_bind_rule=label_bind_rule,
                            third_party_company_id=third_party_compid,
                            batch_id=batch_id,
                            first_parent_id=first_parent_id,
                            parent_id=parent_id,
                            remark=remark
                        )  
                        tp.save()  
                        i = i+1 
 
                data['batch_id'] = batch_id
                data['cnt'] = i
            else:
                data['e'] = '无标签数据'
        else:
            data['e'] = '数据丢失'
    else:
        data['e'] = '请求失败'

    return JsonResponse(data)

# def third_party_label_bind(request):
#     data = {
#         'e': '',
#         'batch_id': '',
#         'cnt': 0
#     }
#     path = "F:/datacenter/"+os.path.join("log","binds",time.strftime('%Y-%m-%d')+".txt") 
#     f = open(path,'a')
#     f.write(time.strftime('%H:%M:%S')+":hh")
#     if request.method == 'POST':
#         d = json.loads(request.body)
        
#         f.write(time.strftime('%H:%M:%S')+":"+json.dumps(d))
#         f.close() 
        
#         if d['compid'] and d['uid']:
#             compid = d['compid']
#             uid = d['uid']
#             third_party_compid = d['third_party_compid']
#             if d['labels']:
#                 labels = d['labels']

#                 labels_len = range(len(labels))
#                 batch_id = str(time.strftime('%Y%m%d%H%M%S'))
#                 i = 0
#                 for c in labels_len:
#                     #标签绑定规则
#                     label_bind_rule = labels[c]['label_bind_rule']
#                     #箱码 为数组 []
#                     x_labels = labels[c]['label_code']
#                     x_labels_out = labels[c]['label_code_out']
#                     #产品码
#                     x_labels_bar = []
#                     if labels[c]['label_bar_code']:
#                         x_labels_bar = labels[c]['label_bar_code']
#                     if isinstance(x_labels, str):
#                         x_labels = [x_labels]
#                         x_labels_out = [x_labels_out]
#                         x_labels_bar = [x_labels_bar]


#                     first_parent_id = 0
#                     parent_id = 0
#                     #循环箱码
#                     ln = min(len(x_labels),len(x_labels_out))

#                     #循环箱码
#                     for x in range(ln): 
#                         tp = Third_Party_Label_Bind(
#                             company_id=compid,
#                             user_id=uid,
#                             label_type=labels[c]['label_type'],
#                             label_code=x_labels[x],
#                             label_code_out=x_labels_out[x],
#                             label_code_type=labels[c]['label_code_type'],
#                             label_bind_rule=label_bind_rule,
#                             third_party_company_id=third_party_compid,
#                             batch_id=batch_id,
#                             first_parent_id=first_parent_id,
#                             parent_id=parent_id
#                         )
#                         if len(x_labels_bar)>x:
#                             tp.label_bar_code=x_labels_bar[x]

#                         tp.save() 
#                         i = i+1

#                     # 如果有二级绑定
#                     if 'children' in labels[c]:
#                         children = labels[c]['children']
#                         for c2 in range(len(children)):
#                             # 盒标|二级绑定
#                             h_labels = children[c2]['label_code']
#                             h_labels_out = children[c2]['label_code_out']
#                             if isinstance(h_labels, str):
#                                 h_labels = [h_labels]
#                                 h_labels_out = [h_labels_out]
#                             #循环盒标
#                             for h in range(len(h_labels)):
#                                 tp2 = Third_Party_Label_Bind(
#                                     company_id=compid,
#                                     user_id=uid,
#                                     label_type=children[c2]['label_type'],
#                                     label_code=h_labels[h],
#                                     label_code_out=h_labels_out[h],
#                                     label_code_type=children[c2]['label_code_type'],
#                                     label_bind_rule=label_bind_rule,
#                                     third_party_company_id=third_party_compid,
#                                     batch_id=batch_id,
#                                     parent_id=parent_id,
#                                     first_parent_id=first_parent_id
#                                 )
#                                 tp2.save()
#                                 parent_id = tp2.id

#                                 i = i + 1
#                             # 三级绑定
#                             if 'children' in children[c2]:
#                                 children_3 = children[c2]['children']
#                                 for c3 in range(len(children_3)):
#                                     tp3 = Third_Party_Label_Bind(
#                                         company_id=compid,
#                                         user_id=uid,
#                                         label_type=children_3[c3]['label_type'],
#                                         label_code=children_3[c3]['label_code'],
#                                         label_code_out=children_3[c3]['label_code_out'],
#                                         label_code_type=children_3[c3]['label_code_type'],
#                                         label_bind_rule=label_bind_rule,
#                                         third_party_company_id=third_party_compid,
#                                         batch_id=batch_id,
#                                         parent_id=parent_id,
#                                         first_parent_id=first_parent_id
#                                     )
#                                     tp3.save()
#                                     i = i + 1
#                             parent_id = first_parent_id

#                 data['batch_id'] = batch_id
#                 data['cnt'] = i
#             else:
#                 data['e'] = '无标签数据'
#         else:
#             data['e'] = '数据丢失'
#     else:
#         data['e'] = '请求失败'

#     return JsonResponse(data)



# 标签序号查询
@login_required
def third_party_label_search(request):
    data = {
        'e': '',
        'labels': [],
        'search_label_type': '',
        'search_label': '',
        'search_label_third_company': '', 
        'tm': '',
        'batch_id': '',
        'u_name': '',
        'bind_rule': ''
    }
    if request.method == 'POST':
        compid = request.user.company.id
        label_code = request.POST.get('label_code', '')
        label = Third_Party_Label_Bind.objects.filter(label_code=label_code,
                company_id=int(compid)).order_by('-tm')[:1]
        if label:
            label = label[0]
            data['search_label'] = label_code
            data['search_label_third_company'] = label.third_party_company.name 
            data['tm'] = label.tm
            data['batch_id'] = label.batch_id
            data['u_name'] = label.user.username
            data['bind_rule'] = label.label_bind_rule
            if label.label_type == 'X':
                id = label.id
                if label.first_parent_id != 0:
                    labels = Third_Party_Label_Bind.objects.filter(first_parent_id=label.first_parent_id)
                    data['labels'] = json.loads(serializers.serialize("json", labels))
                    x_label = Third_Party_Label_Bind.objects.filter(id=label.first_parent_id)[0]
                    # 将查询的插入前头
                    data['labels'].insert(0, json.loads(serializers.serialize("json", [x_label])[1:-1]))
                else:
                    labels = Third_Party_Label_Bind.objects.filter(first_parent_id=id)
                    data['labels'] = json.loads(serializers.serialize("json", labels))
                    # 将查询的插入前头
                    data['labels'].insert(0, json.loads(serializers.serialize("json", [label])[1:-1]))
                data['search_label_type'] = '箱'
            else:
                if label.label_type == 'H':
                    data['search_label_type'] = '盒'
                else:
                    data['search_label_type'] = '瓶'
                first_parent_id = label.first_parent_id
                labels = Third_Party_Label_Bind.objects.filter(
                    Q(first_parent_id=first_parent_id) | Q(id=first_parent_id))
                data['labels'] = json.loads(serializers.serialize("json", labels))
    else:
        data['e'] = '数据丢失'
    return render(request, 'company/label_bind_search.html', data)

@login_required
def third_party_label_list(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': [], 'murl': '', 'dt': False, 'add': True, 'order':[]}
    data['clmns'] = ['标签序号', '第三方标签序号','产品码', '第三方公司', '标签类型', '码类型', '绑定规则','备注', '时间']
    # data['show_add'] = True
    # data['murl'] = '/mall/boards/edit/'
    data['btn_name'] = '搜索详细绑定记录'
    data['btn_url'] = '/third_party_label/search/'
    data['dt']=True
    
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_from', dt)
    dt_to = request.GET.get('date_to', "")
    if not dt_to:
        dt_to = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    data["date_from"]=dt_fr
    data["date_to"]=dt_to       

    

    cur = connection.cursor()
    company_id=request.user.company.id
    # 查询最后一次更新记录
    cur.execute("SELECT label_code,label_code_out,label_bar_code,"+
        "(SELECT name from company_third_party_company WHERE id = third_party_company_id),label_type,label_code_type,"+
        "label_bind_rule,remark,tm FROM company_third_party_label_bind WHERE company_id = "+str(company_id)+" and tm>='"+dt_fr+"' and tm <='"+dt_to+"'")
    for r in cur.fetchall():
        label_code_type = '二维码'
        label_type = '箱'
        if r[5] == 1:
            label_code_type = '条形码'


        data['data'].append([
            r[0],
            r[1],
            r[2],
            r[3],
            label_type,
            label_code_type,
            r[6],
            r[7],
            str(r[8])
        ]) 
    #print(data)
    return render(request, 'obj/list_obj.html', data)



# 权益
@login_required
def benefit(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['品牌权益', '权益设置'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['权益名称', '面向对象', '是否激活', '备注', '添加时间', '操作']
    data['show_add'] = True
    data['murl'] = '/company/benefit/edit/'

    for t in Benefit.objects.filter(company_id=request.user.company.id):
        flag = '否'
        face_to = ''
        remark = '无'
        if t.is_face_to_agent:
            face_to = '经销商'
        if t.is_face_to_terminal:
            face_to += ',终端店'
        if t.is_face_to_business:
            face_to += ',业务员'
        if t.is_active:
            flag = '是'
        if t.remark:
            remark = t.remark
        data['data'].append([
            "<a href='/company/benefit/edit/" +
            str(t.id) + "/'>" + t.name + "</a>",
            face_to,
            flag,
            remark,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/company/benefit/rule/" + str(t.id) + "/'>规则设定</a>" +
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(t.id) + ")'>删除</button>"
        ])
    return render(request, 'obj/list_obj.html', data)


# 权益编辑
@login_required
def benefit_edit(request, id=None):
    if id:
        obj = Benefit.objects.get(id=int(id))
    else:
        obj = Benefit(company_id=request.user.company.id)
    if request.method == 'GET':
        form = Benefit_Form(instance=obj)
    else:
        form = Benefit_Form(request.POST, instance=obj)
    if form.is_valid():
        form.save()
    return render(request, 'company/benefit.html', {'form': form})


# 权益删除
@login_required
def benefit_delete(request, id=None):
    if id:
        obj = Benefit.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/company/benefit/')



# 权益规则
@login_required
def benefit_rule(request, id=None):
    data = {'data': [],
            'clmns': ['规则名称', '类型','规则', '备注', '添加时间', '操作'],
            'e': [], 'subtt': ['品牌权益', '权益规则'],
            'level_up_method_id': '',
            'level_up_method': '',
            'list': [],
            'cats':[]
            }
    if id:
        benefit = Benefit.objects.get(id=int(id))

        if request.method == 'POST':
            level_id = request.POST.get('level_id', '')
            if level_id:
                obj = Benefit_Rule.objects.get(id=int(level_id))
            else:
                obj = Benefit_Rule(company_id=request.user.company.id, benefit_id=int(id))
            if obj:
                form = Benefit_Rule_Form(request.POST, instance=obj)
                if form.is_valid():
                    form.save()

        brand_rule = Benefit_Rule.objects.filter(benefit_id=id)
        for t in brand_rule:
            remark = ''
            if t.remark:
                remark =t.remark
            rule = t.rule_category.name
            if t.rule_category.id == 1:
                rule = rule +' 打'+str(t.discount)+'折'

            data['data'].append([
                t.name,
                t.rule_category.name,
                rule,
                remark,
                t.tm.strftime("%Y-%m-%d %H:%M:%S"),
                "<a class='btn btn-danger btn-xs' onclick='deleteData(" + str(t.id) + ")'>删除</a>"
            ])

        rule_category = Benefit_Rule_Category.objects.all()
        for r in rule_category:
            data['cats'].append({
                'id':r.id,
                'name':r.name
            })


        #benefits = Benefit.objects.filter(company_id=request.user.company.id, is_active=True)
        #data['benefits'] = json.loads(serializers.serialize("json", benefits))

        return render(request, 'company/benefit_rule.html', data)
    else:
        return JsonResponse(data)


# 权益删除
@login_required
def benefit_rule_delete(request, id=None, benefit_rule_id=None):
    if id and benefit_rule_id:
        obj = Benefit_Rule.objects.get(id=int(benefit_rule_id), company_id=request.user.company.id)
        obj.delete()
        return redirect('/company/benefit/rule/' + id)
    else:
        return redirect('/company/benefit/')


# 品牌管理
@login_required
def brands(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['品牌管理', '品牌设置'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['品牌名称', '厂家', '升级条件', '是否激活', '备注', '添加时间', '操作']
    data['show_add'] = True
    data['murl'] = '/company/brands/edit/'

    for t in Brands.objects.filter(company_id=request.user.company.id):
        flag = '否'
        remark = '无'
        if t.level_up_method == 1:
            level_up_method = '按销售数量'
        else:
            level_up_method = '按销售金额'
        if t.is_active:
            flag = '是'
        if t.remark:
            remark = t.remark
        data['data'].append([
            "<a href='/company/brands/edit/" +
            str(t.id) + "/'>" + t.name + "</a>",
            t.third_party_company.name,
            level_up_method,
            flag,
            remark,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/company/brands/level/" + str(t.id) + "/'>等级设定</a>" +
            "<a class='btn btn-default btn-xs' href='/company/brands/edit/" + str(t.id) + "/products/'>产品绑定</a>" +
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(t.id) + ")'>删除</button>"
        ])
    return render(request, 'obj/list_obj.html', data)


# 品牌编辑
@login_required
def brands_edit(request, id=None):
    if id:
        obj = Brands.objects.get(id=int(id))
    else:
        obj = Brands(company_id=request.user.company.id)
    if request.method == 'GET':
        form = Brands_Form(instance=obj, user=request.user)
    else:
        form = Brands_Form(request.POST, instance=obj, user=request.user)
    if form.is_valid():
        form.save()
    return render(request, 'company/brand.html', {'form': form})


# 品牌删除
@login_required
def brands_delete(request, id=None):
    if id:
        obj = Brands.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/company/brands/')


# 品牌绑定产品
@login_required
def brands_edit_product(request, id=None):
    data = {'data': [],
            'e': [], 'subtt': ['品牌管理', '品牌产品绑定'],
            'products_bind': [],
            'products': [],
            'brand_name': ''
            }
    if id:
        obj = Brands.objects.get(id=int(id))
        data['brand_name'] = obj.name

        if request.method == 'POST':
            productChooses = request.POST.get('productChooses', '')
            if productChooses:
                ps = json.loads(productChooses)                
                p_len = range(len(ps))
                cur = connection.cursor()
                # 转为默认
                cur.execute("update product_product set brand_id = null where brand_id = " + id)
                for c in p_len:
                    cur.execute("update product_product set brand_id = " + id + " where id = " + ps[c])

        products_bind = Product.objects.filter(brand_id=int(id), company_id=request.user.company.id, is_delete=False)
        products = Product.objects.filter(brand_id=None, company_id=request.user.company.id, is_delete=False)
        data['products_bind'] = json.loads(serializers.serialize("json", products_bind))
        data['products'] = json.loads(serializers.serialize("json", products))

        return render(request, 'company/brand_products.html', data)
    else:
        return JsonResponse(data)


# 品牌等级
@login_required
def brands_level(request, id=None, type=None):
    data = {'data': [],
            'clmns': ['等级级别', '等级名称', '等级图片', '升级条件', '权益', '备注', '操作'],
            'e': [], 'subtt': ['品牌管理', '品牌等级'],
            'level_up_method_id': '',
            'level_up_method': '',
            'list': [],
            'benefits': []
            }
    if id:
        brand = Brands.objects.get(id=int(id))
        level_up_method_id = brand.level_up_method
        data['level_up_method_id'] = level_up_method_id
        if level_up_method_id == 1:
            data['level_up_method'] = '按销售数量'
        elif level_up_method_id == 2:
            data['level_up_method'] = '按销售金额'
        if request.method == 'POST':
            level_id = request.POST.get('level_id', '')
            if level_id:
                obj = Brands_Level.objects.get(id=int(level_id))
            else:
                obj = Brands_Level(company_id=request.user.company.id, brand_id=int(id))
            if type == 'delete' and level_id:
                obj.delete()
                brands_agent_update(id,level_up_method_id)
            else:
                form = Brands_Level_Form(request.POST, request.FILES, instance=obj)
                if form.is_valid():
                    form.save()
                    brands_agent_update(id,level_up_method_id)
        brand_obj = Brands_Level.objects.filter(brand_id=id)
        for t in brand_obj:
            if level_up_method_id == 1:
                level_up_method = '销售数量>=' + str(t.need_num)
            elif level_up_method_id == 2:
                level_up_method = '销售金额>=' + str(t.need_money) + ' 元'
            photo_url = ''
            remark = '无'
            benefit_name = ''
            if t.photo:
                photo_url = t.photo.url
            if t.remark:
                remark = t.remark
            if t.benefit:
                benefit_name = t.benefit.name

            data['data'].append([
                t.level,
                t.name,
                "<img src='" + photo_url + "' style='width:30px' />",
                level_up_method,
                benefit_name,
                remark,
                "<a class='btn btn-default btn-xs' onclick='editLevel(" + str(t.id) + ")'>修改</a>" +
                "<a class='btn btn-default btn-xs' onclick='bindBenefit(" + str(t.id) + ")'>权益绑定</a>" +
                "<a class='btn btn-danger btn-xs' onclick='deleteLevel(" + str(t.id) + ")'>删除</a>"
            ])
        data['list'] = json.loads(json.dumps(serializers.serialize("json", brand_obj)))

        benefits = Benefit.objects.filter(company_id=request.user.company.id, is_active=True)
        data['benefits'] = json.loads(serializers.serialize("json", benefits))

        return render(request, 'company/brand_level.html', data)
    else:
        return JsonResponse(data)





@csrf_exempt
def brands_agent_level(request):
    data = {
        'e':'',
        'levels':[],
        'tasks':[]
    }
    company_id = request.GET.get('company_id','')
    if company_id :
        c = Company.objects.get(id=int(company_id))
        brands_agent_level_update(c.ancestor_id,company_id)
        obj = Brands_Agent_Level.objects.filter(company_id=int(company_id))
        if obj:
            for o in obj:
                b = o.brand_level
                name = b.brand.name + b.name
                photo = b.photo.url
                level = b.level

                benefit = None
                #权益内容
                b = o.brand_level.benefit
                if b:
                    if b.is_active:
                        benefit = {
                            'name':b.name,
                            'rules':[]
                        }
                        #查询权益详细规则
                        bs = Benefit_Rule.objects.filter(benefit_id=b.id)
                        if bs:
                            for b2 in bs:
                                benefit['rules'].append({
                                    'id': encrypt_p(str(b2.id)) ,
                                    'name':b2.name,
                                    'type':b2.rule_category.name,
                                    'discount':b2.discount
                                })


                data['levels'].append({
                    'name':name,
                    'photo':photo,
                    'level':level,
                    'benefit':benefit
                })
        tasks = Sale_Task_Allocate.objects.filter(agent_id=int(company_id))
        if tasks:
            cur = connection.cursor()
            for t in tasks:
                allocate_type = t.allocate_type
                if t.sale_task.is_active:
                    products = []
                    if allocate_type == 1: 
                        ssql = ("select "
                                "(SELECT name from product_product where id = product_id),num,sale_num "
                                "from company_sale_task_allocate_products "
                                "where agent_id = "+company_id +" and sale_task_allocate_id = "+str(t.id))
                        cur.execute(ssql)
                        ps = cur.fetchall()
                        if ps:
                            for p in ps:
                                products.append({
                                    'name':p[0],
                                    'num':p[1],
                                    'sale_num':p[2]
                                })
                    data['tasks'].append({
                        'name': t.sale_task.name,
                        'start_tm': t.sale_task.start_tm,
                        'end_tm': t.sale_task.end_tm,
                        'sale_money': t.sale_money,
                        'sold_money': t.sold_money,
                        'finish_percent': t.finish_percent,
                        'allocate_type':allocate_type,
                        'products':products
                    })


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



# 下级终端店等级
@csrf_exempt
def brands_agent_children_level(request):

    data = {
        'e':'',
        'levels':[] 
    }
    company_id = request.GET.get('company_id','') 
    if company_id :
        #c = Company.objects.get(id=int(company_id))
        cur = connection.cursor()
        cur.execute("select (select name from company_company where id = company_id) as compname,"+
                    "(select name from company_brands where id = brand_id),"+
                    "(select name from company_brands_level where id = brand_level_id),"+
                    "(select photo from company_brands_level where id = brand_level_id)"+ 
                    "from company_brands_agent_level where company_id in (SELECT id FROM company_company where parent_id = "+company_id+") order by compname")
        rs = cur.fetchall()
        if rs:
            for r in rs:
                data['levels'].append({
                    'agent_name':r[0],
                    'brand_name':r[1],
                    'level_name':r[2],
                    'level_photo':r[3]
                })
 

    else:
        data['e'] = '数据丢失'

    return JsonResponse(data)



@csrf_exempt
def test_brands(request,ancestor_id,company_id):
    data = {
        'e': ''
    }
    brands_agent_level_update(ancestor_id,company_id)
    #sale_task_agent_update(ancestor_id,company_id)
    return  JsonResponse(data)


# 考核任务更新 
def sale_task_agent_update(ancestor_id, company_id):
    cur = connection.cursor()
    # 经销商任务
    agent_tasks = Sale_Task_Allocate.objects.filter(agent_id=int(company_id))
    if agent_tasks:
        for t in agent_tasks:
            # 任务开始时间
            start_tm = t.sale_task.start_tm.strftime("%Y-%m-%d")
            # 任务结束时间
            end_tm = (t.sale_task.end_tm+datetime.timedelta(days=1)
                      ).strftime("%Y-%m-%d")
            # 如果按照销售数量升级 
            if t.allocate_type == 1: 
                # 查询销售出库 剔除退库
                cur.execute("SELECT product_id,count(*) FROM inventory_stkdetails WHERE company_id = "+str(company_id)+
                            "and vtype_id = 2 and label_pkg = 3 "+
                            "and label_code not in ( "+
                            "    SELECT label_code from inventory_stkdetails where vtype_id = 4 and label_code in ( "+
                            "        SELECT label_code FROM inventory_stkdetails WHERE company_id = "+str(company_id)+
                            "            and vtype_id = 2  "+
                            "    ) "+
                            ")"+
                            "and product_id in ("+
                            "    SELECT product_id from company_sale_task_allocate_products where agent_id = "+str(company_id)+
                            ") "+
                            "and tm BETWEEN '"+start_tm+"' and '"""+end_tm+"'"+
                            "GROUP BY product_id")
                rs = cur.fetchall()
                if rs: 
                    for r in rs:
                        product_id = r[0]
                        num = r[1]
                        cur.execute("update company_sale_task_allocate_products set sale_num = "+str(num) +" where product_id = "+ str(product_id) +" and agent_id = "+str(company_id))
                    cur.execute("UPDATE company_sale_task_allocate a set finish_percent = ("+
                                "SELECT ((sum(sale_num)*1.0)/(sum(num)*1.0))*100 FROM company_sale_task_allocate_products where sale_task_allocate_id = a.id"+
                                ") where agent_id = "+str(company_id))
            else:   
                cur.execute("SELECT product_id,"+
                            "count(*) * COALESCE((select price from product_product WHERE id = product_id),0) "+
                            "FROM inventory_stkdetails WHERE company_id = "+str(company_id)+" "+
                            "and vtype_id = 2 and label_pkg = 3 "+
                            "and label_code not in ( "+
                            "    SELECT label_code from inventory_stkdetails where vtype_id = 4 and label_code in ( "+
                            "        SELECT label_code FROM inventory_stkdetails WHERE company_id = "+str(company_id)+
                            "            and vtype_id = 2  "+
                            "    ) "+
                            ")"+ 
                            "and tm BETWEEN '"+start_tm+"' and '"""+end_tm+"' "+
                            "GROUP BY product_id")
                rs = cur.fetchall()  
                if rs: 
                    for r in rs:
                        product_id = r[0]
                        money = r[1]
                        cur.execute("UPDATE company_sale_task_allocate set finish_percent = ("+str(money)+"/sale_money)*100,sold_money = "+str(money)+" where agent_id = "+str(company_id))
    sale_task_company_update(ancestor_id)




# 更新所有任务


def sale_task_company_update(company_id):
    cur = connection.cursor()
    # 总任务
    company_tasks = Sale_Task.objects.filter(company_id=int(company_id))
    if company_tasks:
        for t in company_tasks:
            cur.execute(
                "select sum(finish_percent) from company_sale_task_allocate where sale_task_id = "+str(t.id))
            d = cur.fetchone()
            if d: 
                t.finish_percent = d[0]
                t.last_update_tm = datetime.datetime.now()
                t.save()
            else: 
                t.finish_percent = 0
                t.last_update_tm = datetime.datetime.now()
                t.save()



# 更新当前任务
def sale_task_update(id):
    tasks = Sale_Task_Allocate.objects.filter(sale_task_id=int(id))
    if tasks:
        for t in tasks:
            sale_task_agent_update(t.company_id,t.agent_id)



# 更新当前品牌下的经销商等级
def brands_agent_update(brand_id,level_up_method):
    levels = Brands_Agent_Level.objects.filter(brand_id=int(brand_id))
    if levels:
        cur = connection.cursor()
        for t in levels:
            all_num = t.all_num
            all_money = t.all_money
            # 如果按照销售数量升级
            if level_up_method == 1:
                cur.execute(
                    "select id from company_brands_level where " + str(all_num) + " >= need_num and brand_id = " + str(
                        brand_id) + " ORDER BY need_num desc LIMIT 1")
                d = cur.fetchone()
                if d:
                    level_id = d[0]
            # 如果按照销售金额升级
            elif level_up_method == 2:
                cur.execute("select id from company_brands_level where " + str(
                    all_money) + " >= need_money and brand_id = " + str(brand_id) + " ORDER BY need_money desc LIMIT 1")
                d = cur.fetchone()
                if d:
                    level_id = d[0]
            if level_id:
                t.brand_level_id = int(level_id)
                t.save()


# 经销商等级升级记录
def brands_agent_do_record(ancestor_id,company_id,product_id,product_num):
    data = {
        'e': ''
    }

    product = Product.objects.filter(id=int(product_id))
    if product:
        product=product[0]
        a = Brands_Agent_Records(
            ancestor_id=int(ancestor_id),
            company_id=int(company_id),
            brand=product.brand,
            product_id=int(product_id),
            product_name=product.name,
            product_num=int(product_num),
            product_money=product.price
        )
        a.save()
    else:
        data['e'] = '产品不存在'

    return JsonResponse(data)

# 经销商品牌等级更新
def brands_agent_level_update(ancestor_id, company_id):

    data = {
        'e': ''
    }

    cur = connection.cursor()
    # 查询销售出库 剔除退库
    cur.execute("SELECT product_id,(SELECT brand_id from product_product where id = product_id),"+\
                "(SELECT level_up_method from company_brands where id = ((SELECT brand_id from product_product where id = product_id))),"
                "(SELECT price from product_product where id = product_id),"
                "count(*) FROM inventory_stkdetails WHERE company_id = "+str(company_id)+
                "and vtype_id = 2  and label_pkg = 3 "+
                "and label_code not in ( "+
                "    SELECT label_code from inventory_stkdetails where vtype_id = 4 and label_code in ( "+
                "        SELECT label_code FROM inventory_stkdetails WHERE company_id = "+str(company_id)+
                "            and vtype_id = 2  "+
                "    ) "+
                ")"+
                "and product_id in ("+
                "   SELECT id FROM product_product WHERE brand_id in ( "+\
	            "       SELECT brand_id FROM company_brands_level where company_id = "+str(ancestor_id)+")"+\
                ") "+
                "GROUP BY product_id")
    rs = cur.fetchall()             
    for r in rs:
        product_id = r[0]
        brand_id = r[1]
        level_up_method = r[2]
        price = r[3]
        count = r[4]
        level_id = None
        all_price = 0
        if price:
            all_price = price * count
        if level_up_method == 1: 
            cur.execute("select id from company_brands_level where "+str(count) +
                            " >= need_num and brand_id = "+str(brand_id)+" ORDER BY need_num desc LIMIT 1")
            d = cur.fetchone()
            if d:
                level_id = d[0]
        else:
            cur.execute("select id from company_brands_level where "+str(all_price) +
                            " >= need_money and brand_id = "+str(brand_id)+" ORDER BY need_money desc LIMIT 1")
            d = cur.fetchone()
            if d:
                level_id = d[0] 
                
        if level_id:
                b = Brands_Agent_Level.objects.filter(
                    brand_id=int(brand_id), company_id=int(company_id))
                if b:
                    b = b[0]
                    b.all_money = all_price
                    b.all_num = count
                    b.brand_level_id = int(level_id)
                    b.save()
                else:
                    b = Brands_Agent_Level(
                        ancestor_id=int(ancestor_id),
                        company_id=int(company_id),
                        brand_id=int(brand_id),
                        brand_level_id=int(level_id),
                        all_money=all_price,
                        all_num=count
                    )
                    b.save()
 

    return JsonResponse(data)




# 经销商等级列表
@login_required
def brands_agent_level_list(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['品牌权益', '经销商等级'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['经销商名称', '品牌', '等级', '总金额', '产品总数量']

    for t in Brands_Agent_Level.objects.filter(ancestor_id=request.user.company.id):
        data['data'].append([
            t.company.name,
            t.brand.name,
            "<img src='"+t.brand_level.photo.url+"' style='width:25px' /> "+t.brand_level.name,
            str(t.all_money),
            t.all_num
            #"<a class='btn btn-default btn-xs' href='/company/sale_task/edit/" + str(t.id) + "/'>数据更改</a>"
        ])
    return render(request, 'obj/list_obj.html', data)


# 考核系统
@login_required
def sale_task(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['任务考核', '任务设置'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['任务名称', '开始时间', '结束时间', '状态', '完成进度', '备注', '操作']
    data['show_add'] = True
    data['murl'] = '/company/sale_task/edit/'
    sale_task_company_update(request.user.company.id)

    for t in Sale_Task.objects.filter(company_id=request.user.company.id):
        flag = '关闭'
        remark = '无'
        finish_percent = str(t.finish_percent)
        if t.is_active:
            flag = '进行中'
        if t.remark:
            remark = t.remark
        width = str(t.finish_percent)
        if t.finish_percent and t.finish_percent >100:
            width = '100'
        data['data'].append([
            "<a href='/company/sale_task/edit/" +
            str(t.id) + "/'>" + t.name + "</a>",
            t.start_tm.strftime("%Y-%m-%d"),
            t.end_tm.strftime("%Y-%m-%d"),
            flag,
            '<div class="progress" style="margin:0"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="' + finish_percent + '" aria-valuemin="0" aria-valuemax="100" style="width: ' + width + '%;">' + finish_percent + '%</div></div>',
            remark,
            "<a class='btn btn-default btn-xs' href='/company/sale_task/edit/" + str(t.id) + "/'>详情</a>" +
            "<a class='btn btn-default btn-xs' href='/company/sale_task/allocate/" + str(t.id) + "/'>任务分配</a>" +
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(t.id) + ")'>删除</button>"
        ]) 
    return render(request, 'obj/list_obj.html', data)


# 销售任务设定
@login_required
def sale_task_edit(request, id=None):
    if id:
        obj = Sale_Task.objects.get(id=int(id))
    else:
        obj = Sale_Task(company_id=request.user.company.id)
    if request.method == 'GET':
        form = Sale_Task_Form(instance=obj)
    else:
        form = Sale_Task_Form(request.POST, instance=obj)
    if form.is_valid():
        form.save()
        if id:
            sale_task_update(id)
    return render(request, 'company/sale_task.html', {'form': form})


# 销售任务分配
@login_required
def sale_task_allocate(request, id=None, type=None):
    data = {'data': [],
            'clmns': ['经销商', '完成方式', '进度', '备注', '操作'],
            'e': [], 'subtt': ['任务考核', '任务设置', '任务分配'],
            'list': [],
            'agents': []
            }
    if id:
        cur = connection.cursor()
        # task = Sale_Task.objects.get(id=int(id))
        if request.method == 'POST':
            allocate_id = request.POST.get('allocate_id', '')
            agent = request.POST.get('agent', '')
            product_ids = request.POST.get('product_ids', '')
            allocate_type = request.POST.get('allocate_type', '0')
            obj = None
            if allocate_id:
                obj = Sale_Task_Allocate.objects.get(id=int(allocate_id))
            else:
                cur.execute(
                    "select count(*) from company_sale_task_allocate where sale_task_id = " + id + " and agent_id = " + agent)
                r = cur.fetchone()
                if int(r[0]) == 0:
                    obj = Sale_Task_Allocate(company_id=request.user.company.id, sale_task_id=int(
                        id), allocate_type=int(allocate_type))

            if obj:
                form = Sale_Task_Allocate_Form(request.POST, instance=obj)
                if form.is_valid():
                    form.save()
                    if product_ids:
                        ps = product_ids.split(',')
                        for p in range(len(ps)):
                            p1 = ps[p].split('|')
                            sp = Sale_Task_Allocate_Products(
                                sale_task_allocate_id=form.instance.id,
                                agent=form.instance.agent,
                                product_id=int(p1[0]),
                                num=int(p1[1]),
                            )
                            sp.save()
                    sale_task_agent_update(request.user.company.id, agent)

        agents = Company.objects.filter(parent_id=int(request.user.company.id))
        data['agents'] = json.loads(serializers.serialize("json", agents))

        cur.execute("SELECT id,allocate_type,sale_money,sold_money,finish_percent,remark," +
                    "(SELECT name from company_company where id = agent_id)," +
                    "(SELECT sum(num) from company_sale_task_allocate_products WHERE sale_task_allocate_id = a.id) from company_sale_task_allocate a where sale_task_id = "+id)
        allocates = cur.fetchall()
        for r in allocates:
            a_id = r[0]
            allocate_type = r[1]
            sale_money = r[2]
            #sold_money = r[3]
            finish_percent = r[4]
            remark = r[5]
            if not remark:
                remark = '无'
            agent_name = r[6]
            sala_num = r[7]
            width = str(finish_percent)
            if finish_percent and finish_percent > 100:
                width = '100'
            finish_percent = str(finish_percent)

            sale_limit = ''
            if allocate_type == 1:
                allocate_type = '销售数量 >= ' + str(sala_num)

            else:
                allocate_type = '销售金额 >= ' + str(sale_money) + '元'

            data['data'].append([
                agent_name,
                allocate_type,
                '<div class="progress" style="margin:0"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="' +
                finish_percent + '" aria-valuemin="0" aria-valuemax="100" style="width: ' +
                width + '%;">' + finish_percent + '%</div></div>',
                remark,
                # "<a class='btn btn-default btn-xs' onclick='editData(" + str(a.id) + ")'>修改</a>" +
                "<a class='btn btn-danger btn-xs' onclick='deleteData(" + str(
                    a_id) + ")'>删除</a>"
            ])
        data['list'] = []
        return render(request, 'company/sale_task_allocate.html', data)
    else:
        return JsonResponse(data)




# 销售任务删除
@login_required
def sale_task_delete(request, id=None):
    if id:
        obj = Sale_Task.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/company/sale_task/')
@login_required
def sale_task_allocate_delete(request, id=None, allocate_id=None):
    if id and allocate_id:
        obj = Sale_Task_Allocate.objects.get(id=int(allocate_id), company_id=request.user.company.id)
        task_id = obj.sale_task_id
        obj.delete()
        return redirect('/company/sale_task/allocate/' + str(task_id))
    else:
        return redirect('/company/sale_task/')


# 任务记录
@login_required
def sale_task_record(request):

    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['任务考核', '任务记录'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['任务名称', '经销商', '目标金额', '已完成金额', '完成进度','最后更新时间']
    data['show_add'] = False
    tasks = Sale_Task_Allocate.objects.filter(company_id=request.user.company.id).order_by('-last_update_tm')
    for t in tasks:

        finish_percent = str(t.finish_percent)
        width = str(t.finish_percent)
        if t.finish_percent >100:
            width = '100'


        data['data'].append([
            t.sale_task.name,
            t.agent.name,
            str(t.sale_money),
            str(t.sold_money),
            '<div class="progress" style="margin:0"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="' + finish_percent + '" aria-valuemin="0" aria-valuemax="100" style="width: ' + width + '%;">' + finish_percent + '%</div></div>',
            t.last_update_tm.strftime("%Y-%m-%d %H:%M:%S")
        ])
    return render(request, 'obj/list_obj.html', data)



# 轮播图
@login_required
def page_banners(request, id=None):
    data = {'data': [],
            'clmns': ['图片', '是否激活', '排序', '上传时间', '操作'],
            'e': [], 'subtt': ['页面轮播图', '轮播图管理'],
            'list': []
            }

    if request.method == 'POST':
        banner_id = request.POST.get('banner_id', '')
        obj = None
        if banner_id:
            obj = Page_Banners.objects.get(id=int(banner_id))
        else:
            obj = Page_Banners(company_id=request.user.company.id)
        if obj:
            form = Page_Banners_Form(request.POST,request.FILES, instance=obj)
            if form.is_valid():
                form.save()
    banners = Page_Banners.objects.filter(company_id=request.user.company.id).order_by('sort_id')
    for b in banners:
        flag = '否'
        img_url = ''
        if b.is_active:
            flag = '是'
        if b.image:
            img_url = b.image.url
        data['data'].append([
            "<img src='" + img_url + "' style='width:100px' />",
            flag,
            b.sort_id,
            b.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' onclick='editData(" + str(b.id) + ")'>修改</a>"+
            "<a class='btn btn-danger btn-xs' onclick='deleteData(" + str(b.id) + ")'>删除</a>"
        ])
    data['list'] = json.loads(json.dumps(serializers.serialize("json", banners)))
    return render(request, 'company/page_banner.html', data)

# 轮播图删除
@login_required
def page_banners_delete(request, id=None):
    if id :
        obj = Page_Banners.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/company/page_banners/')

# 新闻资讯
@login_required
def news(request):
    data = {'data': [], 'clmns': [], 'e': [],'subtt': ['页面管理', '新闻资讯'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['文章导图', '标题', '备注', '是否激活','添加时间','操作']
    data['show_add'] = True
    data['murl'] = '/company/news/edit/'

    for t in News.objects.filter(company_id=request.user.company.id):
        flag = '否'
        remark = '无'
        img_url = ''
        if t.is_active:
            flag = '是'
        if t.remark:
            remark = t.remark
        if t.poster:
            img_url = t.poster.url

        data['data'].append([
            "<img src='" + img_url + "' style='width:50px' />",
            t.subtitle,
            remark,
            flag,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            "<a class='btn btn-default btn-xs' href='/company/news/edit/" + str(t.id) + "/'>详情</a>"+
            "<button class='btn btn-danger btn-xs' onclick='deleteItem(" + str(t.id) + ")'>删除</button>"
        ])
    return render(request, 'obj/list_obj.html', data)

# 新闻资讯编辑
@login_required
def news_edit(request, id=None):
    if id:
        obj = News.objects.get(id=int(id))
    else:
        obj = News(company_id=request.user.company.id)
    if request.method == 'GET':
        form = News_Form(instance=obj)
    else:
        form = News_Form(request.POST,request.FILES, instance=obj)
    if form.is_valid():
        form.save()
    return render(request, 'company/news.html', {'form': form})


# 新闻删除
@login_required
def news_delete(request, id=None):
    if id :
        obj = News.objects.get(id=int(id), company_id=request.user.company.id)
        obj.delete()
    return redirect('/company/news/')



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

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

            f_url = "media\\"+os.path.join(comp_name, 'news', file_name)
            with open(f_url, 'wb+') as destination:
                for chunk in img.chunks():
                    destination.write(chunk)
            data['errno'] = '0'
            data['data'].append(f_url)
        else:
            data['errno'] = '500'
    else:
        data['errno'] = '500'
    return JsonResponse(data)

@login_required
def toggle_brandrecommender_active(request):
    id = request.GET.get('id', '')
    if not id:
        return JsonResponse({'e': 'no id'})
    else:
        br = BrandRecommender.objects.get(id=id)
        if br.is_active:
            br.is_active = False
        else:
            br.is_active = True
        br.save()
        return JsonResponse({'e': ''})

@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'] = [_('标签号码'),_('消费者'),_('产品'),_('省'),_('市'),_('地址'),_('时间')]


    ls = LabelScan.objects.filter(company_id=request.user.company.id,dt__range=(dt_fr,dt_to))
    for l in ls:
        product_name = ''
        if l.product:
            product_name = l.product.name

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

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


'''
def get_staff_saldiv(request,user_id):
    data={'e':'','saldivs':[],'subsaldivs':[],'agents':[],'groups':[]}

    
    cur=connection.cursor()      
    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 div in r[0]:
            data['saldivs'].append(div)
    #if r[1]:
        for sub in r[1]:
            data['subsaldivs'].append(sub)
    #if r[2]:
        for agt in r[2]:
            data['agents'].append(agt)
    #if r[3]:
        for grp in r[3]:
            data['groups'].append(grp)
        
    return JsonResponse(data)
'''
 
#业务员打卡记录
@login_required
def saleman_checkin(request):
    data = {'data': [], 'clmns': [], 'e': [],'subtt': ['页面管理', '新闻资讯'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['业务员', '打卡终端店','部门','客户渠道','渠道等级', '距离', '时间', '报告','操作']
    data['show_add'] = False
    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 ancestor_id = {ancestor_id}"
    
    cur = connection.cursor()
    cur.execute("SELECT (select last_name from company_user where id = uid ),"+\
                "(SELECT name from company_company where id = dst_compid), "+\
                "id,uid,lng_lat,dst_compid,distance,tm,coalesce(contents,''),coalesce(photo,''), "+\
                "coalesce((select name from company_channel where id = (select channel_id from company_company where id = dst_compid)),''),"+\
                "'',"+\
                "coalesce((SELECT name FROM company_department where id = (SELECT department_id FROM company_staff WHERE user_id = uid)),'') "+\
                "FROM z_salesmancheckin"+sWhere)
    rs = cur.fetchall() 
    for r in rs:
        btns = ''
        dt=r[7].strftime("%Y-%m-%d") 
        btns = f'<a class="btn btn-sm btn-default btn-dlg" href="company/saleman/checkin/photos/?id={r[2]}">查看图片</a>'
        btns = btns + f'<a class="btn btn-sm btn-default btn-dlg" href="company/saleman/checkin/trace/?uid={r[3]}&dt={dt}">当日轨迹</a>'
            
        data['data'].append([
            str(r[0]),
            str(r[1]),
            r[12],
            r[10],
            r[11],
            str(r[6])+'米',
            r[7].strftime("%Y-%m-%d %H:%M:%S"),
            r[8],
            btns
        ])
    return render(request, 'obj/list_obj.html', data)
    
def saleman_checkin_trace(request):
    data = {
        'points':[]
    }
    uid = request.GET.get('uid','')
    dt = request.GET.get('dt','')
    sWhere = f"where uid = {uid} and tm::date >= '{dt}' order by id"
    cur = connection.cursor()
    cur.execute("select (SELECT name from company_company where id = dst_compid), lng_lat from z_salesmancheckin "+sWhere)
    rs = cur.fetchall()
    if rs:
        points = []
        for r in rs:
            points.append({
                'name':r[0],
                'lnglat':[float(r[1][0]),float(r[1][1]) ]
            })
        data['points'] = points
    
    return render(request, 'company/saleman_trace.html', data)
    
 
def saleman_checkin_photos(request):
    data = {'data': [], 'clmns': [], 'e': [],'subtt': ['业务员拜访记录', '查看图片'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['门头照片', '陈列照片','补充照片']
    data['show_add'] = False 
    
    
    id = request.GET.get('id','') 
    sWhere = f"where id = {id}"
    cur = connection.cursor()
    cur.execute("select photo,photo_mentou,photo_chenlie from z_salesmancheckin "+sWhere)
    rs = cur.fetchall()
    if rs: 
        for r in rs:
            data['data'].append([
                '<img src="'+r[1]+'" style="max-height:400px;max-width:400px" />',
                '<img src="'+r[2]+'" style="max-height:400px;max-width:400px" />',
                '<img src="'+r[0]+'" style="max-height:400px;max-width:400px" alt="无" />',
            ]) 
    
    return render(request, 'obj/list_obj.html', data)

def company_delete(request):
    ancestor_id = "19257" 
    cur = connection.cursor()
    #add_user_from_company(ancestor_id)
    return JsonResponse({'e':''})
     
    #for b in Batch.objects.filter(ancestor_id=int(ancestor_id)):
    #    print(b)
    #    b.delete()
    #return JsonResponse({'e':''})
    #开始删除终端店订单
    cur.execute("delete from company_agentorderdetails where ancestor_id="+ancestor_id)
    cur.execute("delete from company_agentorderbatch where ancestor_id="+ancestor_id)

    
    
    for b in Batch.objects.filter(ancestor_id=int(ancestor_id)):
       #print(b)
        b.delete()
    
    com = Company.objects.filter(ancestor_id=ancestor_id,level_id__gt=2)
    for c in com:
        company_id = str(c.id)
        #print(company_id)
        c.delete()
    # user = User.objects.filter(ancestor_id=int(ancestor_id),id__gt=3886)
    # for u in user:
    #     print(str(u.id))
    #     u.delete()
    return JsonResponse({'e':''})

    #删除白名单
    cur.execute("delete from company_white_domain where company_id="+ancestor_id)
    #删除标签绑定记录
    cur.execute("delete from company_third_party_label_bind where company_id="+ancestor_id)
    #删除营销人员区域管理
    cur.execute("delete from company_staffsaldiv where company_id="+ancestor_id)

    #开始删除铭牌权益
    #删除经销商等级记录
    cur.execute("delete from company_brands_agent_records where ancestor_id="+ancestor_id)
    #删除经销商等级
    cur.execute("delete from company_brands_agent_level where ancestor_id="+ancestor_id)
    #删除等级
    cur.execute("delete from company_brands_level where company_id="+ancestor_id)
    #删除品牌
    cur.execute("update product_product set brand_id = null where company_id="+ancestor_id)
    cur.execute("delete from company_brands where company_id="+ancestor_id)
    #删除权益规则
    cur.execute("delete from company_benefit_rule where company_id="+ancestor_id)
    #删除权益
    cur.execute("delete from company_benefit where company_id="+ancestor_id)
    #删除经销商任务
    cur.execute("delete from company_sale_task_allocate where company_id="+ancestor_id)
    #删除总任务
    cur.execute("delete from company_sale_task where company_id="+ancestor_id)
    #删除第三方公司
    cur.execute("delete from company_third_party_company where company_id="+ancestor_id)


    #开始删除活动数据
    #删除消费者扫码记录
    cur.execute("delete from sales_labelscan where company_id="+ancestor_id)
    #删除核销配送返现记录
    cur.execute("delete from sales_hexiao_record where company_id="+ancestor_id)
    #删除消费者中奖记录
    cur.execute("delete from sales_consumerwinner where company_id="+ancestor_id)
    #删除步奖记录
    cur.execute("delete from sales_bujiang_labels where company_id="+ancestor_id) 
    #开始删除活动
    for a in Activities.objects.filter(company_id=int(ancestor_id)):
        a.delete()
    #删除奖品
    cur.execute("delete from sales_award where company_id="+ancestor_id)

    #开始删除会员信息
    #删除会员积分记录
    cur.execute("delete from mall_userpoints_record where company_id="+ancestor_id)
    #删除会员积分
    cur.execute("delete from mall_userpoints where company_id="+ancestor_id)
    #删除商城用户地址
    cur.execute("delete from mall_user_address where company_id="+ancestor_id)
    #删除订单评论
    cur.execute("delete from mall_order_comment where company_id="+ancestor_id)
    #删除订单详情
    cur.execute("delete from mall_order_detail where company_id="+ancestor_id)
    #删除订单
    cur.execute("delete from mall_orders where company_id="+ancestor_id)
    #删除商品轮播图 
    cur.execute("delete from mall_points_products_banner where company_id="+ancestor_id)
    #删除商品
    cur.execute("delete from mall_points_products where company_id="+ancestor_id)
    #删除积分商城设置
    cur.execute("delete from mall_settings where company_id="+ancestor_id)
    #删除会员等级
    cur.execute("delete from sales_memberlevel where company_id="+ancestor_id)  
    #删除会员
    cur.execute("delete from sales_member where company_id="+ancestor_id)  

    #开始删除业务员打卡记录
    cur.execute("delete from z_salesmancheckin where ancestor_id="+ancestor_id)

    #



    #删除营销分区
    #cur.execute("delete from company_subsaldivision where company_id="+ancestor_id)
    #删除营销大区



    #开始删除节假日
    cur.execute("delete from sales_holiday where company_id="+ancestor_id)

  

    #开始删除出库入库数据
    
    for b in Batch.objects.filter(ancestor_id=int(ancestor_id)):
        #print(b)
        b.delete()

    #删除准确的物流数据
    #cur.execute("delete from inventory_stkdetails where ancestor_id="+ancestor_id)
    #删除已上传的物流数据
    #cur.execute("delete from inventory_batchdetails where ancestor_id="+ancestor_id)
    #删除物流数据Batch
    #cur.execute("delete from inventory_batch where ancestor_id="+ancestor_id)
    #删除物流仓库
    cur.execute("delete from inventory_storehouse where company_id="+ancestor_id)
    #删除经销商订单
    cur.execute("delete from company_agentorderdetails where ancestor_id="+ancestor_id) 
    cur.execute("delete from company_agentorderbatch where ancestor_id="+ancestor_id)


    com = Company.objects.filter(ancestor_id=ancestor_id,level_id__gt=1)
    for c in com:
        company_id = str(c.id)
        c.delete()
    user = User.objects.filter(ancestor_id=int(ancestor_id),id__gt=3886)
    for u in user:
        #print(str(u.id))
        u.delete()
        
    ss = Series.objects.filter(company_id=int(ancestor_id))
    for s in ss:
        #print(str(s.id))
        s.delete()
    # pros = Product.objects.filter(company_id=int(ancestor_id))
    # for p in pros:
    #     print(str(p.id))
    #     p.delete()
    cur.execute("delete from product_productprop where company_id="+ancestor_id)
    cur.execute("delete from promotion_material where company_id="+ancestor_id)
    return JsonResponse({'e':'success'})


#添加经销商未导入的用户账号
def add_user_from_company(ancestor_id): 
    cur = connection.cursor()
    cur.execute("SELECT id,cell_phone FROM company_company WHERE ancestor_id = "+ancestor_id+
        "AND id not in (SELECT company_id FROM company_user WHERE ancestor_id = "+ancestor_id+")"+
        "and cell_phone not in (SELECT username FROM company_user WHERE ancestor_id = "+ancestor_id+") AND level_id = 4")
    rs = cur.fetchall()
    for r in rs:
        cur.execute("select count(*) from company_user where username = '"+r[1]+"'")
        rr = cur.fetchone() 
        if rr[0] == 0:
            u = User()
            u.username=r[1]
            u.phone=r[1]
            u.company_id=r[0]
            u.ancestor_id=int(ancestor_id)               
            u.set_password("123456")
            u.save()  
            g=Group.objects.get(id=5)                        
            u.groups.add(g) 



# 留言
@csrf_exempt
def leave_message(request):
    data = {
        'e':''
    }
    consumer_id = request.POST.get('consumer_id','')
    company_id = request.POST.get('company_id','')
    subject = request.POST.get('subject','')
    name = request.POST.get('name','')
    tel = request.POST.get('tel','')
    address = request.POST.get('address','') 
    message = request.POST.get('message','') 
    if consumer_id and company_id and name and tel and address:
        consumer_id = decrypt_p(consumer_id)
        cur = connection.cursor()
        dt = datetime.datetime.now().strftime('%Y-%m-%d')
        cur.execute("select count(*) from company_leave_message where consumer_id = "+consumer_id+" and "+
            "company_id = "+company_id +" and leave_date = '"+dt+"' ")
        ct = int(cur.fetchone()[0])
        if ct<=3:
            lm = Leave_Message(
                company_id=int(company_id),
                consumer_id=int(consumer_id),
                subject=subject,
                name=name,
                tel=tel,
                address=address,
                message=message
            )
            lm.save()
        else:
            data['e'] = '当天可提交次数已达上限'
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)

#消息留言
@login_required
def leave_message_list(request):
    data = {'data': [], 'clmns': [], 'e': [],'subtt': ['会员管理', '消息留言'], 'murl': '', 'dt': True, 'add': False}
    data['clmns'] = ['头像','微信昵称','主题','姓名', '电话','地址','消息','时间']


    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', dt)
    data["date_from"]=dt_fr
    data["date_to"]=dt_to    
    dt_to = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    u = request.user
    c = u.company
    if c.id==176056:
        data['clmns'] = ['头像', '微信昵称', '主题', '姓名', '电话', '城市', '购买机构', '时间']
    cur = connection.cursor()
    cur.execute("select (SELECT wx_nickname from sales_consumeraccount WHERE id = consumer_id),"+
	    "(SELECT wx_headimgurl from sales_consumeraccount WHERE id = consumer_id),"+
        "subject,"+
        "name,"+
        "tel,"+
        "address,"+
        "message,tm from company_leave_message where company_id = "+str(request.user.company.id)+" and tm>='"+dt_fr+"' and tm <='"+dt_to+"'")
    rs = cur.fetchall() 
    for r in rs:
        data['data'].append([
            "<img src='"+r[1]+"' style='width:30px' />",
            str(r[0]),
            str(r[2]),
            str(r[3]),
            str(r[4]),
            str(r[5]),
            str(r[6]),
            r[7].strftime("%Y-%m-%d %H:%M:%S")
        ])
    return render(request, 'obj/list_obj.html', data)

# 用户品牌关联
@login_required
def user_brands(request,id=None):
    data = {
        'e':'',
        'products':[]
    }
    if request.method == 'POST': 
        brand_ids = request.POST.get('brand_ids', '')
        bs = []
        if brand_ids:
            bs = brand_ids.split(',')
        
        obj = User.objects.get(id=int(id))
        obj.brand_ids = bs
        obj.save()
    cur = connection.cursor()
    ssql = ("select id,name from company_brands "
            "where array[id] <@ (select brand_ids from company_user where id = "+str(id)+" )")
    cur.execute(ssql)
    rs = cur.fetchall()
    for r in rs:
        data['products'].append({
            'id':r[0],
            'name':r[1]
        })
    return render(request, 'company/user_brands.html', data)


#2021-01-04
def auth_txt(request,file_name):   
    t='error'
    fs=[
        'AVQ7vT2y3X.txt',
        'kmaSPKL2qi.txt',
        'MP_verify_Apm8ueGlttXm3f3v.txt',
        'MP_verify_BMKOImLfGdRBoCVn.txt',
        'MP_verify_dDCad5nDr1PguTaz.txt',
        'MP_verify_KSszkH6otcVzVTgA.txt',
        'MP_verify_oHSdj8rdg7AalbNA.txt',
        'MP_verify_pCyo0qfelFAOiZIp.txt',
        'MP_verify_uebwFIuroWKtMUgv.txt',
        'MP_verify_waYqEcGM4koyXd8N.txt',
        'MP_verify_x0bWH2L8RAgYPkQ5.txt',
        'N3JGAyOSPx.txt',
        'QUU8m0PVzG.txt',
        'MP_verify_CjgWtBdarfFaJJyI.txt',
        'MP_verify_CTdc5Bn88a1G1ymt.txt',
        'MP_verify_eISzNVIZWvn0QrJ1.txt',
        '6867287938.txt',
        'MP_verify_eGgAfUEEbDyEyTUw.txt',
        'lxtNS0FugD.txt',
        'MP_verify_5LWl0fLxc3Bdvvhz.txt',
        'MP_verify_17cwI6HzCKVcUytQ.txt',
        'MP_verify_1pYbxvzTYw4OIynj.txt',
        'MP_verify_9nIDtfO0M7iWbQdm.txt',
        'MP_verify_hsaDLunZaeo29gih.txt',
        'MP_verify_kOildZ0UtyBogeL1.txt',
        'MP_verify_OKC8TwYTIOOksyN0.txt',
        'MP_verify_DRVrVfYfH4UBqX3G.txt',
        'MP_verify_OBm5E91stPV1US9H.txt',
        'MP_verify_8Qs8LBeWbXqARGrY.txt',
        'MP_verify_T5CJ3QUQC8FEVNKd.txt',
        'MP_verify_O0A0UG4ylpDY6Rpq.txt',
        'MP_verify_gOizPBlcll3nr60V.txt',
        'MP_verify_xVYc0FFtAM19j6Td.txt',
        'MP_verify_ng00Y87rUe565p1O.txt',
        'MP_verify_KVgA0qkiHQrR2iKd.txt',
        'MP_verify_3tUBs1fDvaPGXxt7.txt',
        'MP_verify_rIbowoja572gDX4y.txt',
        'MP_verify_HGUJgkrZs6MJWlnF.txt',
        'verify_0fb98c6786a5c84b9d1c7647d8cebdad.html',

        #https证书申请 验证文件
        'fileauth.txt',
        'DozVsxtOiU.txt',
    ]
    if file_name in fs:    
        with open('F:\\datacenter\\media\\auth\\'+file_name, 'r') as f:        
            t=f.read()
    return HttpResponse(t)       




#2021-02-24
@login_required
def bulletinboard(request,id=None):
    is_saved=False
    div_ids=[]
    sal_divs=[]
    cur=connection.cursor()

    if id:        
        obj = BulletinBoard.objects.get(id=int(id))        
    else:
        obj = BulletinBoard(company_id=request.user.company.id,user_id=request.user.id)

    if request.method == 'GET':
        form = BulletinboardForm(instance=obj)
        formset=BulletinBoardAttachFormset(instance=obj) 
        
        s="select id,name from company_salesdivision where company_id="+str(request.user.company_id)+\
            " and rpt_shown=true order by code"
        cur.execute(s)
        for r in cur.fetchall():
            sal_divs.append([r[0],r[1]])
        ids=[]
        for d in obj.salesdivisions:
            ids.append(str(d))
        if ids:
            cur.execute("select id,name from company_salesdivision where id in  ("+",".join(ids)+")")
            for r in cur.fetchall():
                div_ids.append([r[0],r[1]])
    else:
        form = BulletinboardForm(request.POST, request.FILES, instance=obj)
        formset=BulletinBoardAttachFormset(request.POST, request.FILES, instance=obj)

        if form.is_valid():
            is_saved=True
            form.save()
            if formset.is_valid():
                formset.save()
            return  redirect("/obj/list/bulletinboard/")  

        #form=ChannelPromotionsForm(request.POST, request.FILES, instance=obj)
        #formset=ChannelRebateFormset(request.POST, request.FILES, instance=obj)


    return render(request, 'company/bulletinboard.html',
            {'form':form,'formset':formset,'is_saved=False':is_saved,'sal_divs':sal_divs,'div_ids':div_ids})


#2021-03-06    
def get_departments(dept,cur):
    d={}
    d['id']=dept['id']
    d['parent_id']=dept['parent_id']
    d['name']=dept['name']
    d['level']=dept['level']
    d['headcount']=dept['headcount']    
    d['children']=[]
    children=[]
    s="select id,name,level,coalesce(division_id,0),"+\
        "(select count(*) from logistics.company_staff where department_id=a.id) "+\
        "from logistics.company_department a where parent_id="+str(d['id'])+" order by sn"
    cur.execute(s)    
    for r in cur.fetchall():
        children.append({'id':r[0],'name':r[1],'level':r[2],'division_id':r[3],'headcount':{'current':r[4],'total':r[4]},'parent_id':d['id'] })           
    if children:
        d['children']=[get_departments(child,cur) for child in children]    
    for c in d['children']:
        d['headcount']['total']=d['headcount']['total']+c['headcount']['total']
    return d 


#2021-03-07
@login_required
def orginazition_edit(request,obj_name,id=None):
    u=request.user
    if obj_name=='department':
        is_saved=False
        subdivisions=[]
        if id:
            obj=Department.objects.get(id=int(id))
            if obj.division:
                for s in SubSalDivision.objects.filter(division_id=obj.division.id):
                    subdivisions.append([s.id,s.name])
        else:
            obj=Department(company_id=u.ancestor_id)
            pid=request.GET.get('parent_id','')
            if pid:
                pid=int(pid)
                ps=Department.objects.filter(id=pid)
                if ps:
                    p=ps[0]
                    obj.parent_id=pid
                    obj.division_id=p.division_id
                    obj.subsidiary=p.subsidiary
        if request.method=='GET':
            form=DepartmentForm(instance=obj,user=request.user)  
        else:
            
            form=DepartmentForm(request.POST,instance=obj,user=request.user)
            if form.is_valid():
                form.save()
                is_saved=True                
        r=render(request,'company/edit_department.html',{'form':form,'subdivisions':subdivisions,'is_saved':is_saved})
        return HttpResponse(r)
    elif obj_name=='position':
        is_saved=False       
        if id:
            obj=Position.objects.get(id=int(id))            
        else:
            obj=Position(company_id=u.ancestor_id)            
        if request.method=='GET':
            form=PositionForm(instance=obj)  
        else:            
            form=PositionForm(request.POST,instance=obj)
            if form.is_valid():
                form.save()
                is_saved=True   
        r=render(request,'company/edit_position.html',{'form':form,'is_saved':is_saved})
        return HttpResponse(r)
    elif obj_name=='staff':
        
        is_saved=False       
        choose_last_name=False
        if u.ancestor_id == 19318:
            choose_last_name = True
        if id:
            obj=Staff.objects.get(id=int(id))            
        else:
            obj=Staff(company_id=u.ancestor_id)            
        if request.method=='GET':
            if not id:
                dept_id=request.GET.get('dept_id','')
                if dept_id:
                    ds=Department.objects.filter(id=int(dept_id))
                    if ds:
                        obj.department=ds[0]
            form=StaffForm(instance=obj,user=request.user)  
        else:            
            form=StaffForm(request.POST,instance=obj,user=request.user)
            if form.is_valid():
                form.save()
                is_saved=True   
        r=render(request,'company/edit_staff.html',{'form':form,'is_saved':is_saved,'choose_last_name':choose_last_name})
        return HttpResponse(r)




#2021-02-24
@login_required
def orginazition(request,what,id=None):
    u=request.user
    c=u.company
    aid=str(u.ancestor_id)
    cur=connection.cursor()
    if what=="vieworginazition": 
        departments=[]               
        cur.execute("select id,name from company_department where company_id="+str(aid)+" and level=0")
        r=cur.fetchone()
        if r:            
            departments=get_departments({'parent_id':0,'id':r[0],'name':r[1],'level':0,'division_id':0,'headcount':{'current':0,'total':0}},cur)
        cur.close()
        return render(request,'company/view_orginazition.html', {'departments':departments})
    elif what=="liststaff":
        if request.method=="GET":            
            id=request.GET.get('dept_id','')
            obj=Department.objects.get(id=int(id))
            sWhere=" where d.id="+id+" or d.parent_id="+id
            if obj.level==0:
                sWhere=''
            label=obj.get_label()            
            clmns=[_('姓名'),_('岗位职务'),_('部门'),_('部门负责人'),_('上级部门'),_('手机电话'),_('登录帐号')]
            data=[]          
            s="select s.id,s.name,coalesce(s.cellphone,u.phone,''),coalesce(u.username,''),d.name,"+\
                "(select name from company_department where id=d.parent_id),"+\
                "coalesce((select name from company_position where id=s.position_id),''),"+\
                "case when is_department_head then '是' else '否' end "+\
                "from "+\
                "(select * from company_staff a where company_id="+aid+") s "+\
                "left outer join "+\
                "(select * from company_department where company_id="+aid+") d "+\
                "on s.department_id=d.id "+\
                "left outer join "+\
                "(select id,username,last_name,phone from company_user where ancestor_id="+aid+") u "+\
                "on s.user_id=u.id "+sWhere            
            cur.execute(s)
            for r in cur.fetchall():
                a=r[1]
                if request.user.has_perm('company.sys_admin'):
                    a="<a href='/company/orginazition/edit/staff/"+str(r[0])+"/' tt='员工信息-修改' >"+r[1]+"</a>" 
                data.append([ a ,r[6],r[4],r[7],r[5],r[2],r[3] ])           
            r=render(request,'company/list_staff.html', {'label':label,'data':data,'clmns':clmns,'url':request.get_full_path()})
            cur.close()
            return HttpResponse(r)
    elif what=='listposition':
        data=[]
        clmns=['职务名称','备注说明']
        cur.execute("select id,name,coalesce(remark,'') from company_position where company_id="+aid+" and is_delete=false")
        for r in cur.fetchall():
            a=r[1]
            if request.user.has_perm('company.sys_admin'):
                a="<a href='/company/orginazition/edit/position/"+str(r[0])+"/' tt='岗位职务-修改' >"+r[1]+"</a>"
            data.append([a,r[2]])
        r=render(request,'company/list_position.html', {'data':data,'clmns':clmns,'url':request.get_full_path()})
        cur.close()
        return HttpResponse(r)

    #2021-04-27
    elif what=='cgroup_menu':
        if request.method=='GET':
            id=request.GET.get('cgroup_id','')
            if not id:
                cgroups=[]
                cur.execute("SELECT id, name FROM company_cgroup where company_id="+str(u.ancestor_id)+" and is_delete=false order by name")
                for r in cur.fetchall():
                    cgroups.append({'id':r[0],'name':r[1]})
                return render(request,'rbac/list_cgroup_menu.html', {'cgroups':cgroups})
            else:
                g=CGroup.objects.get(id=int(id))
                m=RbacMenu(company=None,cgroup=g)
                menuitems=m.get_menu()   
                cur.close()
                return render(request,'rbac/cgroup_menu.html',{'menuitems':menuitems,'cgroup':g})
        else:
            r=json.loads(request.body)   
            cgroup_id=r['cgroup_id']
            auth_ids=r['auth_ids']
            g=CGroupMenu.objects.get(cgroup_id=int(cgroup_id))
            auth_ids = [ int(x) for x in auth_ids ]            
            g.menus=auth_ids
            g.save()
            data={'e':''}
            cur.close()
            return JsonResponse(data)
            #return render(request,'rbac/cgroup_menu.html',{'menuitems':menuitems,'cgroup':g})

    #2021-04-27
    elif what=='cgroup':
        if request.method=='GET':           
            id=request.GET.get('id','')
            if id:
                obj=CGroup.objects.get(id=int(id))
                form=CGroupForm(instance=obj)
                return render(request,'company/edit_cgroup.html',{'form':form})
            else:
                data=[]
                clmns=['功能组别','停用','备注说明']
                cur.execute("SELECT id,name,coalesce(remark,''),case when is_delete then '是' else '否' end,"+\
                    "to_char(tm_edit,'yyyy-mm-dd HH24:HI:SS') FROM company_cgroup "+\
                    "where company_id="+str(request.user.ancestor_id)+" order by name")
                for r in cur.fetchall():
                    a='<a href="/company/orginazition/cgroup/?id='+str(r[0])+'">'+r[1]+'</a>'
                    data.append([ a ,r[3],r[2] ])
                return render(request,'company/list_cgroup.html',{'clmns':clmns,'data':data})
        else:
           
            #id=request.POST['id']

            obj=CGroup.objects.get(id=int(id))
            form=CGroupForm(request.POST,instance=obj)
            is_saved=False
           
            if form.is_valid():
                form.save()
                is_saved=True
            return render(request,'company/edit_cgroup.html',{'form':form,'is_saved':is_saved})
            #return JsonResponse(data)

@login_required
@csrf_exempt
def ajax_upload_file(request):
    u=request.user
    c=u.company.name
    p=os.path.join(MEDIA_ROOT,c,'uploadfile')
    data={'e':'','uri':''}
    if request.method == 'POST':       
        file = request.FILES.get('file',None)           
        if file:
            a=file.name.split('.')
            if len(a)>1:
                ext='.'+a[1]
            else:
                ext=''
            day_dir = datetime.datetime.now().strftime('%Y%m%d')
            pre_dir = os.path.join(p,day_dir).replace('/','\\')
            if not os.path.exists(pre_dir):
                os.makedirs(pre_dir)
            fn=str(uuid.uuid4())+ext
            filename=os.path.join(pre_dir,fn)            
            with open(filename,'wb') as f:
                for line in file.chunks():
                    f.write(line)
            data['uri']="/media/"+c+"/uploadfile/"+day_dir+"/"+fn
        else:
            data['e']='file missing'

    
    
    return JsonResponse(data)


def test_add_user(request):
    ancestor_id = "19651"
    cur = connection.cursor()
    cur.execute("select id,name,cell_phone,level_id FROM company_company a WHERE ancestor_id =19651"+
                "and (SELECT count(*) from company_user where company_id = a.id) = 0 "+
                "and (SELECT count(*) from company_user where username = a.cell_phone) = 0 and cell_phone is not null and cell_phone !='' ")
    rows = cur.fetchall()
    for r in rows:
        id = r[0]
        name = r[1]
        cell_phone = r[2]
        level_id = r[3]

        u = User()

        if cell_phone:
            u.username = cell_phone
        else:
            u.username = name
        u.company_id = id
        u.ancestor_id = int(ancestor_id)

        u.set_password("123456")

        u.save() 
        gs=Group.objects.filter(id=5)
        if gs:
            u.groups.add(gs[0])   



        #print(id,name)

    return JsonResponse({'e':''})


#2021-04-05
def get_company_applicationreviewlog(content_type,obj_id):    
    cur=connection.cursor()
    l=[]
    s="select to_char(tm,'yyyy-mm-dd HH24:MI'),coalesce(comment,''),"+\
        "(select last_name from company_user where id=user_id),"+\
        "(select name from company_applicationstatus where id=status_id),"+\
        "coalesce((select name from company_company where id=company_id),'') "+\
        "from company_applicationreviewlog "+\
        "where content_type='"+content_type+"' and obj_id="+str(obj_id)+" order by id"
    cur.execute(s)
    for r in cur.fetchall():
        l.append({
            'time':r[0],
            'comment':r[1],
            'user':r[2],
            'status':r[3],            
        })
    cur.close()
    return l


@login_required
def html_company_applicationreviewlog(request):
    content_type=request.GET.get('content_type','')
    obj_id=request.GET.get('obj_id','')
    l=get_company_applicationreviewlog(content_type,obj_id)
    return render(request,'company/company_applicationreviewlog.html',{"logs":l})



#2021-05-10
@login_required
def obj_edit(request,obj_name,id):
    data={'e':'','data':[]}
    m = apps.get_model('company',obj_name)
    objs=m.objects.filter(id=int(id))
    if objs:
        o=objs[0]
    else:
        data['e']='object id error'
        return JsonResponse(data)
 
    u=request.user
    cur=connection.cursor()
    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 4 in group_ids:  #4;"系统管理员" 18;"财务" 20;"出纳"
        if request.method=='GET':
            return render(request,'company/edit_'+obj_name.lower()+'.html',{'obj':o})    
        else:  
            r=json.loads(request.body)
            #class ChangeLog(models.Model):
            #    company = models.ForeignKey('company.Company', verbose_name=_('公司'), related_name='changelog_company', on_delete=models.PROTECT) 
            #    ancestor_id=models.IntegerField(_('族系'), db_index=True)
            #    user = models.ForeignKey('company.User', verbose_name=_('操作人'), on_delete=models.PROTECT, related_name='changelog_user')     
            #    obj_name=models.CharField(_('对象名称'),max_length=20, db_index=True)    
            #    obj_id=models.IntegerField(_('对象id'),db_index=True)
            #    tm = models.DateTimeField(_('时间'), auto_now_add=True)
            #    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True)
            #    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
            #if obj_name=='bankinfoapplication':
            #    remark='收款行帐号:'+o.bank_account+" -> "+r['bank_account']
            #    o.bank_account=r['bank_account']
            #if obj_name=='WxWallet':                
            #    remark='收款人实名:'+o.realname+" -> "+r['realname']
            #    o.realname=r['realname']
            #o.save()
            if obj_name=='wxwalletapplication':
                remark='收款人实名:'+o.realname+" -> "+r['realname']
                o.realname=r['realname']
                o.save()
                ws=WxWallet.objects.filter(application_id=int(id))
                if ws:
                    w=ws[0]
                    w.realname=r['realname']
                    w.save()
            elif obj_name=='bankinfoapplication':
                remark='帐号:'+o.bank_account+"->"+r['bank_account']+\
                    ',开户行:'+o.bank_name+"->"+r['bank_name']+\
                    ',收款人:'+o.payee+"->"+r['payee']
                o.bank_account=r['bank_account']
                o.bank_name=r['bank_name']
                o.payee=r['payee']
                o.save()
                bs=BankInfo.objects.filter(application_id=int(id))
                if bs:
                    b=bs[0]
                    b.bank_account=r['bank_account']
                    b.save()
            l=ChangeLog(company=u.company,ancestor_id=u.ancestor_id,user_id=u.id,obj_name=obj_name,obj_id=int(id),remark=remark)
            l.save()            
            return JsonResponse(data)
    else:
        data['e']='未授权的操作'
        return JsonResponse(data)
            

#2021-07-23
@login_required
def franchise_outlet(request):
    if request.method=='GET':
        is_view=request.GET.get('is_view','0')
        gis_city_id=request.GET.get('gis_city_id','')
        lng_lat=request.GET.get('lng_lat','')
        el_id=request.GET.get('el_id','')
        id=request.GET.get('obj_id','')
        outlet_name=request.GET.get('outlet_name','未知门店名称')
        province_name=request.GET.get('provinve','')
        city_name=request.GET.get('city','')
        
        center={'lng':116.404,'lat':39.915} 
        centerc=''
        aid=str(request.user.company.ancestor_id)
        
        cur=connection.cursor()
        if lng_lat:
            a=lng_lat.split(',')
            center['lng']=a[0]
            center['lat']=a[1]
        elif gis_city_id:            
            cur.execute("SELECT public.st_x(public.ST_Centroid(geom)),public.st_y(public.ST_Centroid(geom)) FROM "+tb_gis+" where id="+gis_city_id)
            r=cur.fetchone()
            if r:
                center['lng']=r[0]
                center['lat']=r[1]  
        elif province_name and city_name:
            centerc=province_name+city_name
        series_legends=[]    
        status=[]
        outlets=[]
        s="select name,coalesce(icon,'unknown') from product_series where company_id="+aid
        cur.execute(s)
        for r in cur.fetchall():
            series_legends.append({'name':r[0],'icon':r[1]})
        s="select s.name,c.en_name,c.name from "+\
            "(SELECT name,color_id FROM company_outletstatus where company_id="+aid+") s "+\
            "left outer join "+\
            "(select id,name,code,en_name from company_color) c "+\
            "on s.color_id=c.id"
        cur.execute(s)
        for r in cur.fetchall():
            status.append({'name':r[0],'color_code':r[1],'color_name':r[2]})
        sId=''
        if id:
            if id!='None':
                sId=" and id<>"+id
        s="select o.id,o.lng_lat,"+\
            "coalesce(s.name,''),"+\
            "case when f.unjoin then 'tree'   else "+\
                "case when t.id is null then 'unknown' else coalesce(s.icon,'unknown') end "+\
            "end,"+\
            "case when f.unjoin then '黄色'   else coalesce(c.name,'红色') end, "+\
            "case when f.unjoin then 'yellow' else coalesce(c.en_name,'red')end, "+\
            "case when f.unjoin then '未加盟' else coalesce(t.name,'') end ,o.name "+\
            "from "+\
            "(SELECT name,lng_lat,company_id,prdduct_id,series_id,status_id,id FROM company_outlet "+\
                "where ancestor_id="+aid+" and is_delete=false and array_length(lng_lat,1)>0 "+sId+") o "+\
            "left outer join "+\
            "(select id,name,icon from product_series where company_id="+aid+") s "+\
            "on o.series_id=s.id "+\
            "left outer join "+\
            "(SELECT id, name, remark, color_id FROM company_outletstatus) t "+\
            "on o.status_id=t.id "+\
            "left outer join "+\
            "(SELECT id, name, code, en_name  FROM logistics.company_color) c "+\
            "on t.color_id=c.id "+\
            "left outer join "+\
            "(select id,franchise_status @> '[{\"id\":\"9\"}]'::jsonb unjoin,name from company_company where ancestor_id="+aid+") f "+\
            "on o.company_id=f.id"   
        
        
        # 2023-03-16 1年半前注册的门店 使用特殊图标
        sInterval='18 MONTH'

        # 2023-02-09 使用加盟商单状态字段franchisestatus_id，不再用多状字段franchise_status
        s="select o.id,o.lng_lat,"+\
            "coalesce(s.name,''),"+\
            "case when f.unjoin then 'tree'   else "+\
                "case when t.id is null then 'unknown' else coalesce(s.icon,'unknown') end "+\
            "end,"+\
            "case when f.unjoin then '黄色'   else coalesce(c.name,'红色') end, "+\
            "case when f.unjoin then 'yellow' else coalesce(c.en_name,'red')end, "+\
            "case when f.unjoin then '未加盟' else coalesce(t.name,'') end,o.name,"+\
            "f.dept,f.rmk," +\
            "(LEAST(f.tm,f.qry_time)+interval'"+sInterval+"')<CURRENT_TIMESTAMP "+\
            "from "+\
            "(SELECT  name,lng_lat,company_id,prdduct_id,series_id,status_id,id,create_tm FROM company_outlet "+\
                "where ancestor_id="+aid+" and is_delete=false and array_length(lng_lat,1)>0 "+sId+") o "+\
            "left outer join "+\
            "(select id,name,icon from product_series where company_id="+aid+") s "+\
            "on o.series_id=s.id "+\
            "left outer join "+\
            "(SELECT id, name, remark, color_id FROM company_outletstatus) t "+\
            "on o.status_id=t.id "+\
            "left outer join "+\
            "(SELECT id, name, code, en_name  FROM logistics.company_color) c "+\
            "on t.color_id=c.id "+\
            "left outer join "+\
            "(select id,case when franchisestatus_id=9 then true else false end unjoin,name,tm,qry_time,"+\
                "coalesce((select name from company_subsaldivision where id=sub_division_id),'') dept,coalesce(remark,'') rmk "+\
                "from company_company where ancestor_id="+aid+") f "+\
            "on o.company_id=f.id"         
        cur.execute(s)
        
        for r in cur.fetchall():
            sAge='false'
            if r[10]:
                sAge='true'
            outlets.append({
                "id":r[0],
                "remark":r[9],"dept":r[8],'status': r[6],'outlet_name': r[7],
                "series":{"name":r[2],"icon":r[3]},
                "color":{"name":r[4],"code":r[5]},                
                "lnglat":{"lng":float(r[1][0]),"lat":float(r[1][1])},
                "bAge":sAge        #2023-03-15 门店是否是在指定指间之前注册 
            })        
        cur.close()
        data={'center':center,'centerc':centerc,'lng_lat':lng_lat,'el_id':el_id,'outlet_name':outlet_name,'outlets':outlets,'series_legends':series_legends,'status':status}
        
        #print(data)
        html='company/franchise/outlet_location.html'
        #if request.user.id==11783:
        #    html='company/franchise/outlet_location_admin.html'
        return render(request,html,data) 



#2021-07-23
@login_required
def view_outlet(request,id=None):
    data={'e':''}
    u=request.user
    c=u.company
    if c.level_id!=1:
        data['e']='company level error'
        return JsonResponse(data)
    cur=connection.cursor() 
    if id:
        cur.close()        
    else:
        cid=str(c.id)           
        series_legends=[]    
        status=[]
        outlets=[]
        s="select name,coalesce(icon,'unknown') from product_series where company_id="+cid
        cur.execute(s)
        for r in cur.fetchall():
            series_legends.append({'name':r[0],'icon':r[1]})
        s="select s.name,c.en_name,c.name,s.id from "+\
            "(SELECT id,name,color_id FROM company_outletstatus where company_id="+cid+") s "+\
            "left outer join "+\
            "(select id,name,code,en_name from company_color) c "+\
            "on s.color_id=c.id"
        cur.execute(s)
        for r in cur.fetchall():
            status.append({'name':r[0],'color_code':r[1],'color_name':r[2],'id':r[3]})
        
        data={'e':'','series_legends':series_legends,'status':status}
        cur.close()
        html='company/franchise/view_outlet.html'   
        return render(request,html,data) 
        

#2021-08-09
@login_required
def edit_outlet(request,id=None):
    u=request.user
    c=u.company
    is_saved=False
    if id:        
        obj = Outlet.objects.get(id=int(id))        
    else:
        obj = Outlet(ancestor_id,c.ancestor_id)
    if request.method=='GET':
        form=OutletForm(instance=obj)
        form.fields['series'].queryset=Series.objects.filter(company_id=c.id)
        form.fields['product'].queryset=Product.objects.filter(company_id=c.id)
        form.fields['status'].queryset=OutletStatus.objects.filter(company_id=c.id)
    else:
        form=OutletForm(request.POST,instance=obj)
        
    return render(request,'company/franchise/edit_outlet.html',{'form':form,'is_saved':is_saved})



def outlet_info(o_id):             
    s="select o.id, o.name, c.unjoin,"+\
        "c.id, c.name, coalesce(c.external_code,''),"+\
        "coalesce(s.id,0), coalesce(s.name,''),"+\
        "coalesce(t.id,0), coalesce(t.name,''),"+\
        "coalesce(o.remark,''), o.city, coalesce(address,''),"+\
        "coalesce(c.qry_teacher,o.qry_teacher,''),coalesce(to_char(c.qry_time,'yyyy-mm-dd hh24:mm:ss'),''),"+\
        "coalesce((select name from company_subsaldivision where id=c.sub_division_id),'') "+\
        "from "+\
        "(select id,name,series_id,status_id,remark,coalesce(city_gis->>'name','') city,address,company_id,"+\
            "qry_teacher,qry_time from company_outlet where id="+str(o_id)+") o "+\
        "left outer join "+\
        "(select id,name from company_outletstatus) t "+\
        "on o.status_id=t.id "+\
        "left outer join "+\
        "(select id,name from product_series) s "+\
        "on o.series_id=s.id "+\
        "left outer join "+\
        "(select id,name,external_code,franchise_status @> '[{\"id\":\"9\"}]'::jsonb unjoin,sub_division_id,"+\
            "qry_teacher,qry_time from company_company) c "+\
        "on o.company_id=c.id"

    # 2023-02-01 2021-11-18加盟商状态改为单选， franchise_status=9 未加盟状态
    s="select o.id, o.name, case when c.franchisestatus_id=9 then true else false end,"+\
        "c.id, c.name, coalesce(c.external_code,''),"+\
        "coalesce(s.id,0), coalesce(s.name,''),"+\
        "coalesce(t.id,0), coalesce(t.name,''),"+\
        "coalesce(o.remark,''), o.city, coalesce(address,''),"+\
        "coalesce(c.qry_teacher,o.qry_teacher,''),coalesce(to_char(c.qry_time,'yyyy-mm-dd hh24:mm:ss'),''),"+\
        "coalesce((select name from company_subsaldivision where id=c.sub_division_id),''),"+\
        "coalesce(c.remark,'') "+\
        "from "+\
        "(select id,name,series_id,status_id,remark,coalesce(city_gis->>'name','') city,address,company_id,"+\
            "qry_teacher,qry_time from company_outlet where id="+str(o_id)+") o "+\
        "left outer join "+\
        "(select id,name from company_outletstatus) t "+\
        "on o.status_id=t.id "+\
        "left outer join "+\
        "(select id,name from product_series) s "+\
        "on o.series_id=s.id "+\
        "left outer join "+\
        "(select id,name,external_code,franchisestatus_id,sub_division_id,"+\
            "qry_teacher,qry_time,remark from company_company) c "+\
        "on o.company_id=c.id"

    cur=connection.cursor()
    cur.execute(s)
    r=cur.fetchone()
    if r[2]:
        s={'id':0,'name':'未加盟'}
    else:
        s={'id':r[8],'name':r[9]}
    d = {
        'id': r[0],
        'name': r[1],
        'company': {'id':r[3], 'name':r[4], 'code':r[5]},
        'series': {'id':r[6],'name':r[7]},
        'status': s,
        'remark': r[10],
        'city': r[11],
        'address': r[12],
        'qry_teacher':r[13],
        'qry_time':r[14],
        'dept':r[15],
        'remark':r[16]
    }
    cur.close()
    return d


#2021-07-31
@login_required
def outlet_get(request,what,id=None):
    data={'e':''}
    if what=='list':
        cur=connection.cursor()
        aid=str(request.user.company.ancestor_id)
        status_id=request.GET.get('status_id','')
        sStatus=''
        if status_id:
            sStatus=" and status_id="+status_id


        # 2023-03-16 1年半前注册的门店 使用特殊图标
        sInterval='18 MONTH'
        
        '''
        s="select o.name,o.lng_lat,"+\
            "coalesce(s.name,''),"+\
            "case when f.unjoin then 'tree'   else "+\
                "case when t.id is null then 'unknown' else coalesce(s.icon,'unknown') end "+\
            "end,"+\
            "case when f.unjoin then '未加盟' else coalesce(t.name,'') end,"+\
            "case when f.unjoin then '黄色' else coalesce(c.name,'红色') end,"+\
            "case when f.unjoin then 'yellow' else coalesce(c.en_name,'red') end,"+\
            "(select name from company_company where id=o.company_id),o.id "+\
            "from "+\
            "(SELECT name,lng_lat,company_id,prdduct_id,series_id,status_id,id,ancestor_id FROM company_outlet "+\
                "where ancestor_id="+aid+" and array_length(lng_lat,1)>0 "+sStatus+") o "+\
            "left outer join "+\
            "(select id,name,icon from product_series where company_id="+aid+") s "+\
            "on o.series_id=s.id "+\
            "left outer join "+\
            "(SELECT id, name, remark, color_id FROM company_outletstatus) t "+\
            "on o.status_id=t.id "+\
            "left outer join "+\
            "(SELECT id, name, code, en_name  FROM logistics.company_color) c "+\
            "on t.color_id=c.id "+\
            "left outer join "+\
            "(select id,franchise_status @> '[{\"id\":\"9\"}]'::jsonb unjoin,name,tm,qry_time from company_company where ancestor_id="+aid+") f "+\
            "on o.company_id=f.id"
        '''
        # 2023-02-01: 2021-11-18 加盟状态单选
        s="select o.name,o.lng_lat,"+\
            "coalesce(s.name,''),"+\
            "case when f.franchisestatus_id=9 then 'tree'   else "+\
                "case when t.id is null then 'unknown' else coalesce(s.icon,'unknown') end "+\
            "end,"+\
            "case when f.franchisestatus_id=9 then '未加盟' else coalesce(t.name,'') end,"+\
            "case when f.franchisestatus_id=9 then '黄色' else coalesce(c.name,'红色') end,"+\
            "case when f.franchisestatus_id=9 then 'yellow' else coalesce(c.en_name,'red') end,"+\
            "(select name from company_company where id=o.company_id),o.id,"+\
            "coalesce((select name from company_subsaldivision where id=f.sub_division_id ),''),"+\
            "coalesce(f.remark,''), "+\
            "(LEAST(f.tm,f.qry_time)+interval'"+sInterval+"')<CURRENT_TIMESTAMP "+\
            "from "+\
            "(SELECT name,lng_lat,company_id,prdduct_id,series_id,status_id,id,ancestor_id,create_tm FROM company_outlet "+\
                "where ancestor_id="+aid+" and array_length(lng_lat,1)>0 "+sStatus+") o "+\
            "left outer join "+\
            "(select id,name,icon from product_series where company_id="+aid+") s "+\
            "on o.series_id=s.id "+\
            "left outer join "+\
            "(SELECT id, name, remark, color_id FROM company_outletstatus) t "+\
            "on o.status_id=t.id "+\
            "left outer join "+\
            "(SELECT id, name, code, en_name  FROM logistics.company_color) c "+\
            "on t.color_id=c.id "+\
            "left outer join "+\
            "(select id,franchisestatus_id,name,sub_division_id,remark,tm,qry_time from company_company where ancestor_id="+aid+") f "+\
            "on o.company_id=f.id"



        cur.execute(s)
        a=[]
        #2;"黄色";"#FFFF00";"yellow"
        #9;0;"未加盟"
        for r in cur.fetchall():
            a.append({
                "id":r[8],
                "name":r[0],
                "series":{"name":r[2],"icon":r[3]},
                "color":{"name":r[5],"code":r[6]},
                "status":r[4],
                "lnglat":{"lng":float(r[1][0]),"lat":float(r[1][1])},
                "dept":r[9], "remark":r[10],
                "bAge":r[11]        #2023-03-15 门店是否是在指定指间之前注册 
            })
        

        data['outlets']=a
    elif what=='outlet':        
        data['data']=outlet_info(id)
    return JsonResponse(data)
        

#2021-08-10
@login_required
def franchise_action(request,what,action,id):
    data={'e':''}
    u=request.user
    t=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if what=='agent':
        os=Company.objects.filter(id=int(id))
        if not os:
            data['e']='agent id error'
        else:
            o=os[0]
            if action=='approve':
                o.approve_by_id=u.id
                o.approve_tm=t
                o.save()
            else:
                data['e']='action name error'
    elif what=='outlet':
        os=Outlet.objects.filter(id=int(id))
        if not os:
            data['e']='outlet id error'
        else:
            o=os[0]
            if action=='approve':
                o.approve_by_id=u.id
                o.approve_tm=t
                o.save()
            else:
                data['e']='action name error'
    return JsonResponse(data)




#2021-08-10
@login_required
def print_excel(request,what):
    data={}
    html='sales/sales_table/jswy_'+what+'_tic.html' 
    return render(request, html, data)
    #return HttpResponse(html)
    #html=render(request, 'sales/sales_table/jswy_inbound_tic.html', data)
    

@csrf_exempt
def ajax_company(request,obj): 
    if obj == 'addDetail':
        return ajaxAddDetail(request)
    elif obj == 'getChannels':
        return ajaxGetChannels(request)
    elif obj == 'getChannelLevels':
        return ajaxGetChannelLevels(request)
    elif obj == 'getProductSeries':
        return ajaxGetProductSeries(request)
    elif obj == 'getCompanyFiles':
        return ajaxGetCompanyFiles(request) 
    elif obj == 'getMapPoints':
        return ajaxMapPoints(request) 
    elif obj == 'searchCompanyOrProduct':
        return ajaxSearchCompanyOrProduct(request) 
    elif obj == 'inspection_report':
        return ajaxGetInspectionReport(request)
    elif obj == 'getList':
        return ajaxGetCompanyList(request)
    elif obj == 'getTerminalRegisterList':
        return ajaxGetTerminalRegisterList(request)
    elif obj == 'terminalRegisterApprove':
        return ajaxTerminalRegisterApprove(request)
        
        

def ajaxAddDetail(request):
    res = {
        'e': ''
    }
    d = json.loads(request.body)
    if (
        'id' in d and
        'contacts' in d and
        'cell_phone' in d and
        'address' in d and
        'lng_lat' in d 
    ):
        id = d['id']
        contacts = d['contacts']
        cell_phone = d['cell_phone'] 
        address = d['address']
        lng_lat = d['lng_lat']
        if (
            id and
            contacts and
            cell_phone and
            address and
            lng_lat 
        ):
            c = Company.objects.get(id=id) 
            c.contacts = contacts
            c.cell_phone = cell_phone
            c.address = address
            c.lng_lat = lng_lat
            
            if 'channel_id' in d and d['channel_id']:
                c.channel_id = d['channel_id']
            
            if 'channelLevels' in d and d['channelLevels']:
                c.channel_level_ids = d['channelLevels']
                
            if 'productSeries' in d and d['productSeries']:
                c.series_more = d['productSeries']

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

def ajaxGetChannels(request):
    res = {
        'e': '',
        'channels':[]
    }
    ancestor_id = request.GET.get('ancestor_id','')
    if ancestor_id:
        rs = Channel.objects.filter(ancestor_id=ancestor_id)
        for r in rs:
            res['channels'].append({
                'id':r.id,
                'name':r.name
            })
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)
    

def ajaxGetChannelLevels(request):
    res = {
        'e': '',
        'channelLevels':[]
    }
    ancestor_id = request.GET.get('ancestor_id','')
    if ancestor_id:
        rs = Channel_Level.objects.filter(ancestor_id=ancestor_id)
        for r in rs:
            res['channelLevels'].append({
                'id':r.id,
                'name':r.name,
                'remark':r.remark
            })
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)
    

def ajaxGetProductSeries(request):
    res = {
        'e': '',
        'series':[]
    }
    ancestor_id = request.GET.get('ancestor_id','')
    if ancestor_id:
        cur=connection.cursor()
        cur.execute("select id,name from product_series where company_id = "+ancestor_id)
        rs = cur.fetchall() 
        for r in rs:
            res['series'].append({
                'id':r[0],
                'name':r[1]
            })
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)

def ajaxGetCompanyFiles(request):
    res = {
        'e': '',
        'files':[]
    }
    company_id = request.GET.get('company_id','')
    if company_id:
        rs = UploadFiles.objects.filter(company_id=company_id)
        for r in rs:
            res['files'].append({
                'id':r.id,
                'category_name':r.category.name,
                'url':r.url,
                'media_type':r.media_type
            })
    else:
        res['e'] = '数据丢失'
    return JsonResponse(res)
    

def ajaxMapPoints(request):

    def generateFeatures(rs, _type):
        ps = {
            'type': 'FeatureCollection',
            'features': []
        }
        for r in rs:
            ps['features'].append({
                'geometry': {
                    'type': 'Point',
                    'coordinates': [float(r[2][0]), float(r[2][1])],
                },
                'properties': {
                    'id': r[0],
                    'label_code': r[1],
                    'lnglat': [float(r[2][0]), float(r[2][1])],
                    'address': r[3],
                    'type': _type
                },
                'type': 'Feature'
            })
        return ps

    data = {
        'e':''
    }
    company_id = request.GET.get('company_id','0')
    product_id = request.GET.get('product_id','')
    agent_id = request.GET.get('agent_id','')
    tm_start = request.GET.get('tm_start',(datetime.datetime.now() - datetime.timedelta(days=120)).strftime('%Y-%m-%d'))
    tm_end = request.GET.get('tm_end',datetime.datetime.now().strftime('%Y-%m-%d')+' 23:59:59')
    last_id = request.GET.get('last_id','')

    cur=connection.cursor()
 
    sql = f"""
        select id,label_code,lng_lat,address
        from logistics.sales_labelscan 
        where 
        company_id = {company_id}
        and lng_lat is not null 
        and tm >= '{tm_start}' and tm<= '{tm_end}'
        
    """
    if product_id:
        sql = sql + ' and product_id = '+ product_id
    else:
        sql = sql + ' and product_id is not null'
    #if agent_id:
        #sql = sql + ' and agent_id = '+ agent_id

    cur.execute(sql)
    rs = cur.fetchall()
    data['yingxiao'] = generateFeatures(rs,'yingxiao')

    sql = f"""
        select id,label_code,lng_lat,address
        from logistics.sales_fakelabel 
        where 
        ancestor_id = {company_id}
        and lng_lat is not null 
        and tm >= '{tm_start}' and tm<= '{tm_end}'
        and product_id is not null
    """
    if product_id:
        sql = sql + ' and product_id = '+ product_id
    else:
        sql = sql + ' and product_id is not null'
    if agent_id:
        sql = sql + ' and agent_id = '+ agent_id
    cur.execute(sql)
    rs = cur.fetchall()
    data['jiahuo'] = generateFeatures(rs,'jiahuo')
        
    sql = f"""
        select id,label_code,lng_lat,address
        from logistics.sales_bugsell 
        where 
        ancestor_id = {company_id}
        and lng_lat is not null 
        and tm >= '{tm_start}' and tm<= '{tm_end}'
        and product_id is not null
    """
    if product_id:
        sql = sql + ' and product_id = '+ product_id
    else:
        sql = sql + ' and product_id is not null'
    if agent_id:
        sql = sql + ' and agent_id = '+ agent_id
    cur.execute(sql)
    rs = cur.fetchall()
    data['cuanhuo'] = generateFeatures(rs,'cuanhuo')

    sql = f"""
        select id,'',lng_lat,address
        from logistics.company_company 
        where 
        (ancestor_id = {company_id} or ancestor_id = 19651)
        and is_terminal = true 
        and lng_lat is not null 
        and (array_length(lng_lat, 1)>0) 
        limit 500
    """
    if agent_id:
        sql = sql + ' and id = '+ agent_id
    cur.execute(sql)
    rs = cur.fetchall()
    data['shop'] = generateFeatures(rs,'shop')
    
    cur.close()
    return JsonResponse(data)
    
def ajaxSearchCompanyOrProduct(request):
    data = {
        'e':'',
        'data':[]
    }

    keyword = request.GET.get('keyword','')
    company_id = request.GET.get('company_id','')
    if keyword and company_id: 
        cur=connection.cursor()
        sql = f"""
            (select id,name,'商家' from company_company where ancestor_id = {company_id} and name like '%{keyword}%') UNION
            (select id,name,'产品' from product_product where company_id = {company_id} and name like '%{keyword}%')
            limit 50
        """
        cur.execute(sql)
        for r in cur.fetchall():
            data['data'].append({
                'id':r[0],
                'name':r[1],
                'type':r[2]
            })

    return JsonResponse(data)
   

def ajaxGetInspectionReport(request):
    data = {
        'e':'',
        'data':[]
    }
    
    company_id = request.GET.get('company_id','')
    if company_id: 
        cur=connection.cursor()
        sql = f"""
            select
                id,title,contents,dt,to_char(dt,'yyyy年mm月')
            from
                company_inspectionreport
            where company_id = {company_id} and is_active = true order by dt desc
        """
        cur.execute(sql)
        for r in cur.fetchall():
            data['data'].append({
                'id':r[0],
                'title':r[1],
                'contents':quote(r[2],'utf-8'),
                'dt':r[3],
                'month':r[4]
            })

    return JsonResponse(data)


def ajaxGetCompanyList(request):
    data = {
        'e':'',
        'data':[]
    }
    ancestor_id = request.GET.get('ancestor_id','')
    lng = request.GET.get('lng','')
    lat = request.GET.get('lat','')
    keyword = request.GET.get('key','')
    if ancestor_id:
        swhere = "ancestor_id = "+ancestor_id+" and lng_lat is not null and array_length(lng_lat,1)>0"
        if keyword:
            swhere = swhere +" and (name like '%"+keyword+"%' or address like '%"+keyword+"%' ) "
        if lng and lat and lng!="0" and lat !="0":
            sql = "select t.id, t.name, t.lng_lat, t.img_logo, t.address, public.ST_DistanceSphere("+\
                    "public.st_setsrid(public.st_makepoint(lng_lat[1],lng_lat[2]),4326),"+\
                    "public.st_setsrid(public.st_makepoint("+lng+","+lat+"),4326)"+\
                ") AS distance "+\
                "from logistics.company_company t where "+swhere
        else:
            sql = "select t.id, t.name, t.lng_lat, t.img_logo, t.address, 0 as distance "+\
                "from logistics.company_company t where "+swhere

        cur=connection.cursor()
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            data['data'].append({
                'id': r[0],
                'name': r[1],
                'lnglat': r[2],
                'img_logo': r[3],
                'address': r[4],
                'distance': r[5]
            })
    return JsonResponse(data)


def ajaxGetTerminalRegisterList(request):
    data = {
        'e':'',
        'data':[]
    }
    company_id = request.GET.get('company_id','')
    cat = request.GET.get('cat', 'aprv')
    if not company_id:
        return JsonResponse({'e':'数据丢失'})
    if cat == 'aprv':
        ts = TerminalRegister.objects.filter(parent_id=company_id,tm_aprv__isnull=True,is_rejected=False)
    elif cat == 'rejected':
        ts = TerminalRegister.objects.filter(parent_id=company_id,is_rejected=True)
    else:
        tm_start = request.GET.get('tm_start', (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d'))
        tm_end = request.GET.get('tm_end', datetime.datetime.now().strftime('%Y-%m-%d'))
        ts = TerminalRegister.objects.filter(parent_id=company_id,tm__gte=tm_start,tm__lte=tm_end)
    for t in ts:
        data['data'].append({
            'id': t.id,
            'name': t.name,
            'contacts': t.contacts,
            'cell_phone': t.cell_phone,
            'address': t.address,
            'img_signboard': t.img_signboard.url,
            'tm': t.tm,
            'img_license': t.img_license.url,
            'license_number': t.license_number,
            'lng_lat': t.lng_lat,
            'imgs': t.imgs,
            'is_rejected': t.is_rejected,
            'tm_rejected': t.tm_rejected,
            'tm_aprv': t.tm_aprv,
            'user_aprv_id': t.user_aprv_id
        })
    return JsonResponse(data)

def ajaxTerminalRegisterApprove(request):
    data={
        'e':'',
    }
    id = request.POST.get('id','')   
    approved=request.POST.get('approved','')
    rejected=request.POST.get('rejected','')
    user_id=request.POST.get('user_id','')
    if not id:
        return JsonResponse({'e':'数据丢失'})
    
    # 点击了 驳回注册 按钮
    if rejected:   
        obj=TerminalRegister.objects.get(id=int(id)) 
        # 更新注册申请状态
        obj.is_rejected=True
        obj.tm_rejected=datetime.datetime.now()  
        obj.save()
        return JsonResponse(data)
    if approved:  
        data=terminal_register_approve_automatic(id,user_id)

    return JsonResponse(data)


@csrf_exempt
def ajax_company_detail(request):
    
    data = {
        'e':'',
        'cell_phone':'',
        'name':'',
        'license_number':'',
        'contacts':'',
        'address':'',
        'areas':[],
        'lnglat':[],
        'img_logo': '',
        'remark': ''
    }
    id = request.GET.get("id","")
    if id:
        c = Company.objects.get(id=id)
        data['cell_phone'] = c.cell_phone
        data['name'] = c.name
        data['license_number'] = c.license_number
        data['contacts'] = c.contacts
        data['address'] = c.address
        data['lnglat'] = c.lng_lat
        data['remark'] = c.remark
        if c.img_logo:
            data['img_logo'] = c.img_logo.url
        
        cur=connection.cursor()
        cur.execute(f"""
            SELECT NAME 
            FROM
                gis.adm_map_cn                
            WHERE
                ID IN ( SELECT "unnest" ( adm_ids ) FROM logistics.company_company WHERE ID = {id} )
        """)
        rs = cur.fetchall()
        for r in rs:
            data['areas'].append(r[0])
    else:
        data['e'] = '数据丢失'

    return JsonResponse(data)


#2022-04-22 查询分页返回经销商（如西凤375，有4万多经销商）
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
@login_required
def ajax_datatable(request,what):
    u=request.user
    c=u.company    
    can_edit=False    
    if (c.level_id==1 and u.has_perm('company.sys_admin')) or u.id in [14040]:   #长宇酒业，14040;"助理":        
        can_edit=True

    obj_list=[]
    search_dict=dict()

    draw=int(request.GET.get('draw'))
    start=int(request.GET.get('start'))
    length=int(request.GET.get('length'))
    if what=='agent':
        if c.level_id==1:
            obj_list=Company.objects.filter(ancestor_id=c.id).exclude(id=c.id)
        else:
            obj_list=Company.objects.filter(parent_id=c.id).exclude(id=c.id) 
        cnt_total=obj_list.count()   
        name__icontains=request.GET.get('name__icontains','')
        level_id=request.GET.get('level_id','')
        is_golden=request.GET.get('is_golden','')
        parent_id=request.GET.get('parent_id','')
        cell_phone=request.GET.get('cell_phone','')
        if name__icontains:
            search_dict['name__icontains']=name__icontains
        if level_id:
            search_dict['level_id']=int(level_id)
        if is_golden:
            search_dict['is_golden']=int(is_golden)    
        if parent_id:
            search_dict['parent_id']=int(parent_id)
        if cell_phone:
            search_dict['cell_phone']=cell_phone
    
    if search_dict:
        obj_list=obj_list.filter(**search_dict)
        cnt_filtered=obj_list.count()
    else:
        cnt_filtered=cnt_total    

    paginator = Paginator(obj_list, length)     
    if start:
        page=int(start/length)+1
    else:
        page=1   

    objs=paginator.page(page)
    data=[]
    for o in objs:
        if what=='agent':
            name=o.name
            if can_edit:
                name='<a href="/obj/edit/agent/'+str(o.id)+'/">'+name+'</a>'
            div=''
            parent_name=''
            if o.parent:
                parent_name=o.parent.name
            if o.division:
                div=o.division.name
            sub_div=''
            if o.sub_division:
                sub_div=o.sub_division.name
            is_expense_account='否'
            if o.is_expense_account:
                is_expense_account='是'
            accounts=[]
            for i in  User.objects.filter(company_id=o.id):
                if i.last_name:
                    accounts.append(i.last_name)
                else:
                    accounts.append(i.username)
            is_terminal='否'
            if o.is_terminal:
                is_terminal='是'
            is_golden='否'

            #clmns=[_('经销商/分销商名称'),_('外部编码'),_('父级'),_('营销层级'),_('所属战区'),_('所属分区'),_('经销商地址'),_('联系电话'),_('派出机构'),_('帐号'),_('终端店')_('金牌客户')]
            data.append([ 
                name,o.external_code,parent_name,o.level.name,div,sub_div,o.address,o.cell_phone,is_expense_account,','.join(accounts),is_terminal,is_golden
            ])       
    d={
        'draw':draw,        
        "recordsTotal": cnt_total,
        "recordsFiltered": cnt_filtered,
        'data':data
    }   
    return JsonResponse(d,safe=True)





#2022-04-22 查询分页返回经销商（如西凤375，有4万多经销商）
#from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
@login_required
def datatable_server(request,what):
    u=request.user
    c=u.company    
    show_add=False    
    murl='/obj/edit/'+what+'/'
    if (c.level_id==1 and u.has_perm('company.sys_admin')) or u.id in [14040]:   #长宇酒业，14040;"助理":        
        show_add=True

    if what=='agent':        
        tt1='公司管理'
        tt2='经销商列表' 
        clmns=[_('经销商/分销商名称'),_('外部编码'),_('父级'),_('营销层级'),_('所属战区'),_('所属分区'),_('经销商地址'),_('联系电话'),_('派出机构'),_('帐号'),_('终端店'),_('金牌客户')]  
    
    data = {'show_add':show_add,'tt1':tt1,'tt2':tt2,'clmns':clmns,'murl':murl}
    data['btn_name'] = '导入数据'
    data['btn_url'] = '/company/use_excel_upload_companies/'

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





#2022-05-06 窜货预警 市场稽查授权
@login_required
def mkt_inspection_list(request):
    show_add=False
    can_edit=False  
    u=request.user
    cid=u.company.ancestor_id  
    if u.company.level_id==1 and u.has_perm('company.sys_admin'):
        show_add=True
        can_edit=True
    data={'schema':None,'clmns':[],'data':[],'show_add':show_add,'can_edit':can_edit}
    #当前企业 窜货预警 稽察授权设置 
    schemas=CompanyCfgOpt.objects.filter(company_id=cid,configure_id=1)
    if schemas:
        opt=schemas[0].option
        data['schema']=opt.option
        #1;"按产品管理"
        #3;"按战区分区管理"
        #6;"按经销商"
        #8;"按产品系列管理"        
        if opt.id==3:
            data['clmns']=[_('稽察员'),_('负责战区'),_('负责分区')]

            for o in UserCfgOpt.objects.filter(company_id=cid,configure_id=1):
                divs=[]
                subdivs=[]
                v=o.value
                for d in v['divs']:
                    divs.append(d['name'])
                for d in v['subdivs']:
                    subdivs.append(d['name'])
                name=o.user.username
                if can_edit:
                    name='<a href="/company/bugsell/mktinspection/edit/'+str(o.id)+'/">'+name+'</a>'
                data['data'].append([ name, ",".join(divs), ",".join(subdivs) ])


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


@login_required
def mkt_inspection_edit(request,id=None):    
    show_add=False
    can_edit=False    
    obj=None
    u=request.user
    cid=u.company.ancestor_id   
    #1;"市场稽查组"
    grp=CGroup.objects.filter(company_id=cid,group_id=1)[0]
    if u.company.level_id==1 and u.has_perm('company.sys_admin'):
        show_add=True
        can_edit=True

    
    if id:
        obj=UserCfgOpt.objects.get(id=int(id))
    else:
        obj=UserCfgOpt(company_id=cid,configure_id=1)    
    
    if request.method=='POST':
        data={'e':''}
        d = json.loads(request.body)  
        if not d['user_id']:
            data['e']='user id missing'
        else:
            v=d['value']
            obj.user_id=int(d['user_id'])
            obj.value=v
            obj.save()            
        return JsonResponse(data)    
    else:
        users=[]
        if not id:                  
            cur=connection.cursor() 
            s="select id,username,last_name from company_user where company_id="+str(cid)+\
                " and cgroup_ids @> '[{\"id\":"+str(grp.id)+"}]'"    
            cur.execute(s)
            for r in cur.fetchall():
                users.append({'id':r[0],'username':r[1],'last_name':r[2]})
            cur.close()            
        
        divs=[]
        for div in SalesDivision.objects.filter(company_id=cid):
            divs.append([div.id,div.name])            
        
        data={'users':users,'obj':obj,'divs':divs,'show_add':show_add}
        return render(request, 'sales/mkt_inspection_edit.html', data)    


@login_required
def outlet_edit(request, id=None):
    data = {
        'e':''
    }
    name = request.POST.get('name','')
    company_id = request.POST.get('company_id','')
    province = request.POST.get('province','')
    city = request.POST.get('city','')
    county = request.POST.get('county','')
    series_id = request.POST.get('series_id','')
    status_id = request.POST.get('status_id','')
    remark = request.POST.get('remark','')
    address = request.POST.get('address','')
    lng_lat = request.POST.get('lng_lat','')
    if name and series_id and company_id:
        cur=connection.cursor()
        if id:
            obj = Outlet.objects.get(id=int(id))
        else:
            c = Company.objects.get(id=int(company_id))
            obj = Outlet(company_id=c.id,ancestor_id=c.ancestor_id)
        obj.name = name
        if province:
            cur.execute("select name from "+tb_gis+" where id = "+province)
            province = {"id":province,"name":cur.fetchone()[0]}
        else:
            province = {}
        obj.province_gis = province
        if city:
            cur.execute("select name from "+tb_gis+" where id = "+city)
            city = {"id":city,"name":cur.fetchone()[0]}
        else:
            city = {}
        obj.city_gis=city
        if county:
            cur.execute("select name from "+tb_gis+" where id = "+county)
            county = {"id":county,"name":cur.fetchone()[0]}
        else:
            county = {}
        obj.county_gis = county
        obj.series_id = series_id
        if status_id:
            obj.status_id = status_id
        obj.remark = remark
        obj.address = address
        if lng_lat:
            if not lng_lat.startswith('['):
                lng_lat = lng_lat.split(',')
            obj.lng_lat = lng_lat
                
        obj.save()
        data['id'] = obj.id
        data['lng_lat'] = obj.lng_lat
        cur.close()
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)
    
def server_error(request):
    return render(request,'500.html')



@login_required
def use_excel_upload_companies(request):
    if request.method == 'GET':
        return render(request, 'company/company_upload.html')   
    else:
        data = {
            'e': ''
        }
        # 根据等级名称获取等级ID
        def get_level_id(cLevel):
            if cLevel == "一级":
                return "2"
            elif cLevel == "二级":
                return "4"
            elif cLevel == "三级":
                return "5"
            elif cLevel == "四级":
                return "6"
            return "2"
        def get_level_name(level_id):
            if level_id == "2":
                return "一级"
            elif level_id == "4":
                return "二级"
            elif level_id == "5":
                return "三级"
            elif level_id == "6":
                return "四级"
            return "一级"
        cur = connection.cursor()
        # 创建临时表
        cur.execute("""
            create temp table 
            companies (
                ancestor_id integer,
                name character varying(100),
                level_id integer,
                parent_name character varying(20),
                address character varying(200),
                province character varying(50),
                city character varying(100),
                county character varying(100),
                division character varying(50),
                subdivision character varying(50),
                cell_phone character varying(100),
                contacts character varying(50)
            )
        """)

        # 获取操作人公司信息
        ancestor_id=request.user.ancestor_id
        c=request.user.company

        # 读取上传的文件
        f = request.FILES['file']
        if not f:
            data['e'] = '无上传文件'
            return JsonResponse(data)
        fn = f.name
        a = []
        dt = datetime.datetime.now()
        p = settings.MEDIA_ROOT+'/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 #获取列数

        values=''
        cName=''
        cLevel=''
        cParentName=''
        cAddress=''
        cProvince=''
        cCity=''
        cCounty=''
        cDivision=''
        cSubdivision=''
        cPhone=''
        cContacts=''
        #print(rw1)
        for i in range(2,rw1):
            cName=sheet.cell_value(i,0)
            cLevel=sheet.cell_value(i,1)
            cParentName=sheet.cell_value(i,2)
            cAddress=sheet.cell_value(i,3)
            cProvince=sheet.cell_value(i,4)
            cCity=sheet.cell_value(i,5)
            cCounty=sheet.cell_value(i,6)
            cDivision=sheet.cell_value(i,7)
            cSubdivision=sheet.cell_value(i,8)
            cPhone=str(sheet.cell_value(i,9)).split('.')[0]
            cContacts=sheet.cell_value(i,10)
            values = values + f"({str(ancestor_id)},'{cName}',{get_level_id(cLevel)},'{cParentName}','{cAddress}','{cProvince}','{cCity}','{cCounty}','{cDivision}','{cSubdivision}','{cPhone}','{cContacts}'),"
        values = values.strip(',')

        cur.execute(f"""
            insert into companies (ancestor_id,name,level_id,parent_name,address,province,city,county,division,subdivision,cell_phone,contacts)
            values {values}
        """)

        cur.execute(f"""
            insert into company_company (
                category_id,
                hierarchy_id,
                ancestor_id,
                name, 
                level_id,
                parent_id,
                address, 
                province,
                city,
                county,
                division_id,
                sub_division_id,
                cell_phone,
                contacts,
                tm_register,
                remark
            )
            select 
                {str(c.category_id)},
                ancestor_id,
                ancestor_id,
                name,
                level_id,
                (select id from company_company where ancestor_id = a.ancestor_id and name = a.parent_name),
                address,
                (select id from gis.adm_map_cn where name = a.province and level = 1),
                (select id from gis.adm_map_cn where name = a.city and level = 2 and id_1 = (select id from gis.adm_map_cn where name = a.province and level = 1)),
                (select id from gis.adm_map_cn where name = a.county and level = 3 and id_1 = (select id from gis.adm_map_cn where name = a.province and level = 1) and id_2 = (select id from gis.adm_map_cn where name = a.city and level = 2 and id_1 = (select id from gis.adm_map_cn where name = a.province and level = 1))),
                (select id from company_salesdivision where name = a.division),
                (select id from company_subsaldivision where name = a.subdivision),
                a.cell_phone,
                a.contacts,
                now(),
                '工具导入'
            from companies a
            where 
                (select count(id) from company_company where name = a.name and ancestor_id = a.ancestor_id)=0 
                and (select count(*) from companies where name =a.name)=1
        """)


        # 添加用户账号
        cur.execute(f"""
            select id, name, cell_phone,contacts from company_company 
            where ancestor_id={str(ancestor_id)}
                and name not in (select username from logistics.company_user where ancestor_id={str(ancestor_id)}) 
                and cell_phone not in(select username from logistics.company_user where ancestor_id={str(ancestor_id)})
                and cell_phone is not null
                and cell_phone !=''
                and remark='工具导入'
        """)
        values = ''
        uPassword='pbkdf2_sha256$216000$WfYC3VU8Cu8E$8O1agbGrXwP51zl7wTvj30sJ2KmryQsFoJxyFCphHfQ='
        uName=''
        uLastName=''
        uPhone=''
        uCompanyId=''
        uDateJoin=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        rs = cur.fetchall()
        for r in rs:
            uCompanyId=str(r[0])
            uPhone=r[2].split('.')[0]
            uName=r[2].split('.')[0]
            if r[3]:
                uLastName=r[3]
            else:
                uLastName=''
            values = values + f"('{uPassword}',false,'{uName}','','{uLastName}','',false,'{uDateJoin}','{uPhone}',{uCompanyId},{str(ancestor_id)},'[]',true,false,false,'{uDateJoin}'),"
        values = values.strip(',')

        # 创建临时表
        cur.execute("""
            create temp table 
            temp_users (
                password character varying(100),
                is_superuser boolean NOT NULL,
                username character varying(30),
                first_name character varying(30),
                last_name character varying(30),
                email character varying(30),
                is_staff boolean NOT NULL,
                date_joined timestamp with time zone NOT NULL,
                phone character varying(30),
                company_id integer,
                ancestor_id integer,
                cgroup_ids jsonb,
                is_active boolean NOT NULL,
                is_delete boolean NOT NULL,
                pwd_changed boolean NOT NULL,
                tm timestamp with time zone NOT NULL
            )
        """)
        
        
        cur.execute(f"""
            insert into temp_users 
            (password,is_superuser,username,first_name,last_name,email,is_staff,date_joined,phone,company_id,ancestor_id,cgroup_ids,is_active,is_delete,pwd_changed,tm)
            values {values}
        """)

        # 将临时表数据插入正式表内
        cur.execute("""
            insert into company_user 
            (password,is_superuser,username,first_name,last_name,email,is_staff,date_joined,phone,company_id,ancestor_id,cgroup_ids,is_active,is_delete,pwd_changed,tm)
            select password,is_superuser,username,first_name,last_name,email,is_staff,date_joined,phone,company_id,ancestor_id,cgroup_ids,is_active,is_delete,pwd_changed,tm
            from temp_users a 
            where (select count(id) from company_user where username = a.username)=0 
            and (select count(*) from temp_users where username = a.username)=1 
        """)

        # 插入用户权限表
        cur.execute(f"""
            insert into company_user_groups (user_id,group_id)
            select id, 5 from company_user a
            where ancestor_id={str(ancestor_id)} and date_joined='{uDateJoin}'
            and (select count(id) from company_user_groups where user_id = a.id)<1
        """)

        # 查询重复的经销商
        cur.execute("""
            select name,level_id,parent_name,address,province,city,county,division,subdivision,cell_phone,contacts
            from companies a
            where 
                (select count(id) from company_company where name = a.name and ancestor_id = a.ancestor_id)>0
                or (select count(*) from companies where name =a.name)>1
        """)
        repeatAgent=[]
        rs=cur.fetchall()
        for r in rs:
            repeatAgent.append([
                r[0],
                get_level_name(str(r[1])),
                r[2],
                r[3],
                r[4],
                r[5],
                r[6],
                r[7],
                r[8],
                r[9],
                r[10]
            ])
        data['repeatAgent']=repeatAgent

        # 查询重复的用户账号
        cur.execute("""
            select cell_phone,name,to_char((select date_joined from company_user where username = cell_phone),'yyyy-mm-dd HH24:MM:SS') 
            from companies a 
            where (select count(id) from company_user where username = a.cell_phone)>0 
            or (select count(*) from companies where cell_phone = a.cell_phone)>1 
        """)
        repeatUser=[]
        rs=cur.fetchall()
        for r in rs:
            repeatUser.append([
                r[0],
                r[1],
                r[2]
            ])
        data['repeatUser']=repeatUser
        
        return JsonResponse(data)











# 2022-11-03
def fg_movement(request,company_id):
    """
    小程序取库存变动记录
    """
    data={'e':'','data':[]}
    k = sK
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    #uid = request.GET.get('user_id', '')
    cs=Company.objects.filter(id=int(company_id))
    if not cs:
        data['e']='company id error'
        return JsonResponse(data)
    c=cs[0]
    cid=str(c.id)
    aid=str(c.ancestor_id)
    tb="stkdetails.c"+aid

    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
    data['date_from']=dt_fr
    data['date_to']=dt_to
    cur=connection.cursor()
    
    s="select b.code,to_char(b.tm,'yyyy-mm-dd hh24:mi:ss'),x,h,p,"+\
        "(select code from inventory_batch where company_id="+cid+" and id=batch_id),"+\
        "(select name from product_product where id=product_id),"+\
        "(select name from inventory_voucher where id=vtype_id),"+\
        "coalesce((select name from inventory_storehouse where id=store_id),''),dt,vtype_id,"+\
        "coalesce((select name from company_company where id=company_to_id),'') "+\
        "from "+\
        "(select batch_id,vtype_id,product_id,store_id,"+\
            "sum(x) x,sum(h) h,sum(p) p from "+\
            "(select batch_id,vtype_id,product_id,store_id,"+\
                "case when label_pkg=3 then 1 else 0 end x,"+\
                "case when label_pkg=2 then 1 else 0 end h,"+\
                "case when label_pkg=1 then 1 else 0 end p "+\
                "from "+tb+" where company_id="+cid+" "+\
                    "and (dt between '"+dt_fr+"' and '"+dt_to+"')"+\
            ") d "+\
            "group by batch_id,vtype_id,product_id,store_id"+\
        ") g "+\
        "left outer join "+\
        "(select id,tm,code,batch_no,dt,company_to_id from inventory_batch where company_id="+cid+") b "+\
        "on g.batch_id=b.id "+\
        "order by dt,vtype_id"
    cur.execute(s)
    clmns=['时间','单据编号','单据类型','产品名称','客户名称','箱','盒','瓶']
    for r in cur.fetchall():
        data['data'].append([
            r[1],r[0],r[7],r[6],r[11],
            r[2],r[3],r[4]    
        ])

    cur.close()
    # 2022-11-04
    data['clmns']=clmns
    return JsonResponse(data)




    
#返利  积分
def request_rebate_points(obj,channelpromotions_id,self_p_ratio,parent_p_ratio=0):
    data={'e':''}
    cur = connection.cursor()
    rs=[]
    c = Company.objects.get(id=obj.company_id)
    stk_tb = ''
    #判断是宴会还是确认收货物流
    what = ''
    if str(obj.__class__).split("'")[1].split(".")[-1] == 'Batch':
        what = 'Batch'
    elif str(obj.__class__).split("'")[1].split(".")[-1] =='Apply':
        what = 'Apply'
    # 是否是宴席活动产品
    s = "select products  from sales_channelpromotions  WHERE company_id = 19318  and (triggers @> '[{\"id\":\"2\"}]' ::jsonb or triggers @> '[{\"id\":\"3\"}]' ::jsonb)" + \
        " and    NOW() BETWEEN tm_start and tm_end  and products  != '{}' and status = 1 and is_delete = false "
    cur.execute(s)
    ps = cur.fetchall()
    pro_products = []
    sAnd = ""
    if ps:
        for i in ps:
            pro_products.append(i[0][0])
    if pro_products:
        sAnd = " and product_id in " + str(pro_products).replace('[', '(').replace("]", ")")
    if what=='Batch':
        stk_tb = 'stkdetails.c' + str(c.ancestor_id)
        user_id = obj.user_id
        s = "select a.* from (SELECT label_id,label_code,label_pkg,label_pk_id from "+ stk_tb +" where batch_id = " + str(obj.id) +sAnd+ ")A "+\
	        "left outer join ( "+\
            "SELECT label_pk_id FROM logistics.company_pointslogdetails )b "+\
            "on b.label_pk_id =a.label_pk_id "+\
            "where b.label_pk_id is not null GROUP BY a.label_code,a.label_id,a.label_pk_id,a.label_pkg,b.label_pk_id "
        sWhere = " and action = 1 "
    elif what =='Apply':
        user_id = obj.applyer_id
        if obj.channelpromotions_id:
            channelpromotions_id = obj.channelpromotions_id
            cPro = ChannelPromotions.objects.get(id=channelpromotions_id)
            if cPro.triggers:
                for i in cPro.triggers:
                    if i['id'] == '2':
                        details = i['details']
                        if details['package'] == 1 or details['package'] == '1' or details['package'] == 2 or details['package'] == '2':
                            self_p_ratio = details['value']
        s = "select a.* from (SELECT label_id,code,package_id,label_pk_id from logistics.banquet_apply_codes where apply_id=" + str(obj.id) +sAnd+ ")A "+\
	        "left outer join ( "+\
            "SELECT label_pk_id FROM logistics.company_pointslogdetails )b "+\
            "on b.label_pk_id =a.label_pk_id "+\
            "where b.label_pk_id is not null GROUP BY a.code,a.label_id,a.label_pk_id,a.package_id,b.label_pk_id "
        sWhere = " and action = 0 "
    # 积分以及积分人写入积分日志表
    bp = BonusPointsLog(ancestor_id=c.ancestor_id, company_id=obj.company_id, user_id=user_id,
                        channelpromotions_id=channelpromotions_id, content_object=obj, 
                        object_id=obj.id, self_points=0,parent_points=[])
    bp.save()
    # 读取当前batch所有标签号码
    # 积分以及积分人写入积分日志详情表
    # pkid 重复的  进行校验
    cur.execute(s)
    rs = cur.fetchall()

    asql = []
    for r in rs :
        #如果是箱标重复
        if r[2] == 3:
            # 检查是不是有该箱自身重复
            s = "SELECT count(*),label_pkg from  logistics.company_pointslogdetails where label_pk_id= "+str(r[3])+" and err is null and label_pkg in(1,3) "+ sWhere +" group by label_pkg"
            cur.execute(s)
            qty= cur.fetchall()
            for i in qty:
                if i[1] ==3 and i[0] >0 :
                    asql.append("( "+str(c.ancestor_id)+", '"+str(r[1])+"', "+str(r[0])+", "+str(r[3])+", 3,0,0, 'now()', 'now()', '该箱已有积分记录', "+str(bp.channelpromotions_id)+","+str(bp.company_id)+","+str(bp.id)+","+str(bp.user_id)+" )")
                #箱标下有瓶已经有积分记录
                else:
                    asql.append("( " + str(c.ancestor_id) + ", '" + str(r[1]) + "', " + str(r[0]) + ", " + str(r[3]) + ", 3, (SELECT qty_p FROM logistics.product_product WHERE id = "+ str(obj.product_id) + ")-" + str(
                            i[0]) + ",1,0,0, 'now()', 'now()', '该箱部分瓶已有积分记录', " + str(bp.channelpromotions_id) + "," + str(bp.company_id) + "," + str(bp.id) + "," + str(
                            bp.user_id) + " )")

        #如果是瓶标重复
        elif r[2] ==1:
            #1：瓶标重复 该瓶不会获得积分
            s = "SELECT count(*) from  logistics.company_pointslogdetails where label_pk_id= " + str(
                r[3]) + " and label_pkg =1 and  err is null and label_code ='"+str(r[1])+"'"+ sWhere 
            cur.execute(s)
            qty = cur.fetchone()
            if qty[0] > 0:
                asql.append("( " + str(c.ancestor_id) + ", '" + str(r[1]) + "', " + str(r[0]) + ", " + str(
                    r[3]) + ", 1, 0, 0,'now()', 'now()', '该瓶已有积分记录', " + str(
                    bp.channelpromotions_id) + "," + str(bp.company_id) + "," + str(bp.id) + "," + str(bp.user_id) + " )")
            else:
                #2：上级箱重复
                s = "SELECT count(*) from  logistics.company_pointslogdetails where label_pk_id= " + str(r[3]) + " and label_pkg =3  "
                cur.execute(s)
                qty = cur.fetchone()
                if qty[0] > 0:
                    asql.append("( " + str(c.ancestor_id) + ", '" + str(r[1]) + "', " + str(r[0]) + ", " + str(
                        r[3]) + ", 1, 0, 0,'now()', 'now()', '该瓶上级箱已有积分记录', " + str(
                        bp.channelpromotions_id) + "," + str(bp.company_id) + "," + str(bp.id) + "," + str(bp.user_id) + " )")
    if asql:
        s = "INSERT INTO logistics.company_pointslogdetails " \
            "(ancestor_id, label_code, label_id, label_pk_id, label_pkg, " \
            "self_points,parent_points, dt,tm,err, channelpromotions_id, company_id, log_id, user_id) VALUES "+ ','.join(asql)
        cur.execute(s)
    # pkid 没返利过的写入详情标
    if what == 'Batch':
        sInsert = " insert into logistics.company_pointsLogDetails " + \
                  " (product_id,action,ancestor_id,label_code,label_id,label_pk_id,label_pkg,self_points,parent_points,dt,tm,channelpromotions_id,company_id,log_id,user_id ) select " + \
                  " product_id,1," + str(c.ancestor_id) + ",label_code,label_id,label_pk_id,label_pkg," + \
                  "CASE label_pkg WHEN 3  THEN (SELECT qty_p FROM logistics.product_product WHERE id = a.product_id)*"+str(self_p_ratio)+" " + \
                  "WHEN 2 THEN (SELECT qty_h FROM logistics.product_product WHERE id = a.product_id)*"+str(self_p_ratio)+" " + \
                  "WHEN 1 THEN (SELECT qty_x FROM logistics.product_product WHERE id = a.product_id)*"+str(self_p_ratio)+" ELSE 0 END ," + \
                  "CASE label_pkg WHEN 3  THEN (SELECT qty_p FROM logistics.product_product WHERE id = a.product_id)*" + str(parent_p_ratio) + " " + \
                  "WHEN 2 THEN (SELECT qty_h FROM logistics.product_product WHERE id = a.product_id)*" + str(parent_p_ratio) + " " + \
                  "WHEN 1 THEN (SELECT qty_x FROM logistics.product_product WHERE id = a.product_id)*" + str(parent_p_ratio) + " ELSE 0 END ," + \
                  "dt,tm," + \
                  str(bp.channelpromotions_id) + "," + str(bp.company_id) + "," + str(bp.id) + "," + str(bp.user_id) + \
                  " from " + stk_tb + " a where batch_id = " + str(obj.id) + sAnd+ \
            " and label_pk_id not in (select label_pk_id from  logistics.company_pointslogdetails where action = 1)"


    elif what == 'Apply':
        sInsert = " insert into logistics.company_pointsLogDetails " + \
                  " (product_id,action,ancestor_id,label_code,label_id,label_pk_id,label_pkg,self_points,parent_points,dt,tm,channelpromotions_id,company_id,log_id,user_id ) select " + \
                  " product_id,0," + str(c.ancestor_id) + ",code,label_id,label_pk_id,package_id," + \
                  "CASE package_id WHEN 3 THEN (SELECT qty_p FROM logistics.product_product WHERE id = a.product_id) *"+str(self_p_ratio)+" " + \
                  "WHEN 2 THEN (SELECT qty_h FROM logistics.product_product WHERE id = a.product_id)*"+str(self_p_ratio)+" " + \
                  "WHEN 1 THEN (SELECT qty_x FROM logistics.product_product WHERE id = a.product_id)*"+str(self_p_ratio)+" ELSE 0 END ,0," + \
                  "dt,now()," + \
                  str(bp.channelpromotions_id) + "," + str(bp.company_id) + "," + str(bp.id) + "," + str(bp.user_id) + \
                  " from  logistics.banquet_apply_codes a where apply_id = " + str(obj.id) + sAnd+ \
                  " and label_pk_id not in (select label_pk_id from  logistics.company_pointslogdetails "+\
                  " where (label_pk_id = a.label_pk_id and package_id=3 and action =0)or (label_code  = a.code and package_id = 1 and action =0 ))"
    cur.execute(sInsert)
    #更新标签发货顶级
    s = "update logistics.company_pointslogdetails a   set company_fr_id  = (SELECT company_to_id   FROM " +\
        "stkdetails.c"+str(c.ancestor_id)+" WHERE  vtype_id = 2 and label_pk_id = a.label_pk_id " +\
        "AND company_to_id IN ( SELECT ID FROM logistics.company_company WHERE level_id = 2 AND ancestor_id = "+str(c.ancestor_id)+" )" +\
        "ORDER BY id desc limit 1 )  where a.log_id = " + str(bp.id)
    cur.execute(s)

    #积分返利 检查该次操作一共获得多少积分
    s = "select sum(parent_points),company_fr_id from logistics.company_pointslogdetails where log_id = " + str(bp.id)+" group by company_fr_id "
    # 给发货顶级返利
    cur.execute(s)
    rs = cur.fetchall()
    all_points = []
    for r in rs:
        if r[1] is not None:
            if  what == 'Batch':
                all_points.append({'company_fr_id':r[1],'points':int(r[0])})
            s = "INSERT into logistics.company_bonuspoints as a (ancestor_id, points,  tm,company_id,channelpromotions_id)values " + \
                "(" + str(c.ancestor_id) + "," + str(r[0]) + ",now()," + str(r[1]) + ","+str(channelpromotions_id)+") on conflict(company_id)  do update set points = (EXCLUDED.points + a.points) "
            cur.execute(s)
    if all_points:
        bp.parent_points = all_points
        bp.save
        
    # 给经销商自己返利
    s = "select sum(self_points) from logistics.company_pointslogdetails where log_id = " + str(bp.id)
    # 给发货顶级返利
    cur.execute(s)
    r = cur.fetchone()
    if r[0]:
        #该次操作日志一共多少积分
        bp.self_points = r[0]
        bp.save()
        #更新积分表 有则更新 没有则创建
        s = "INSERT into logistics.company_bonuspoints as a (ancestor_id, points, tm,company_id,channelpromotions_id)values " +\
            "("+str(c.ancestor_id)+","+str(r[0])+",now(),"+str(c.id)+","+str(channelpromotions_id)+") on conflict(company_id)  do update set points = (EXCLUDED.points + a.points) "
        cur.execute(s)
    return JsonResponse(data)
    

# 当前积分
@login_required
def bonusPoints(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['渠道促销', '积分'], 'murl': '', 'dt': False, 'add': True}
    data['clmns'] = ['当前积分', '父级公司名字', '经销商名字', '备注', '更新时间', '积分变化明细']
    data['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)
    for t in bps:
        remark = t.remark
        if not t.remark:
            remark = ""
        s = f"""select name,(select name from company_company where id={t.company_id})
         from company_company where id={t.ancestor_id}
        """
        cur.execute(s)
        r = cur.fetchone()
        btn = '<button style="margin:0;padding:1px 10px;" onclick="catPointsDetails('+str(t.company_id)+')" class="update btn btn-sm btn-warning">详情</button>'

        data['data'].append([
            "<a href='/company/bonusPoints/edit/" +
            str(t.id) + "/'>" + str(t.points) + "</a>",
            r[0], r[1],
            remark,
            t.tm.strftime("%Y-%m-%d %H:%M:%S"),
            # "<a class='btn btn-default btn-xs' href='company/bonusPoints/edit_list/" + str(t.id) + "/'>详情</a>"
            btn
        ])
    return render(request, 'obj/list_points.html', data)


# 积分编辑
@login_required
def bonusPoints_edit(request, id=None):
    if id:
        obj = BonusPoints.objects.get(id=int(id))
    else:
        obj = BonusPoints(company_id=request.user.company_id)
    befor_points = obj.points
    if request.method == 'GET':
        form = BonusPoints_Form(instance=obj, user=request.user)
    else:
        form = BonusPoints_Form(request.POST, instance=obj, user=request.user) 
    if form.is_valid():
        points_change = form.save()
        pclog = PointsChangeLog(ancestor_id=obj.ancestor_id,company_id=obj.company_id,user=request.user,
                                before_modify=befor_points,after_modify=request.POST['points'],remark=request.POST['remark'])
        pclog.save() 
    return render(request, 'company/points.html', {'form': form})


@login_required
def bonusPoints_edit_list(request, cid, type=None):
    data = {'data': [],  'e': [],}
    cur = connection.cursor()

    
    s = "SELECT * from (SELECT * from (select '发货所得'::text as act,case contenttype_id when 19 then '收货确认' when '320' then '宴会申请' else'未知' end,  " + \
        "to_char(tm,'yyyy-mm-dd HH24:MI:SS')tm,jsonb_array_elements(parent_points )->> 'points'  as points  , jsonb_array_elements(parent_points )->> 'company_fr_id'as company_fr_id from " + \
        " logistics.company_bonuspointslog where parent_points @>'[{\"company_fr_id\":" + str(
        cid) + "}]'  ) a where a.company_fr_id = '" + str(cid) + "'   " + \
        " union   SELECT '收货所得'::text as act, case contenttype_id when 19 then '收货确认' when '320' then '宴会申请' else'未知' end, " + \
        "to_char(tm,'yyyy-mm-dd HH24:MI:SS')tm,cast(self_points as TEXT) points,cast(company_id as TEXT) from logistics.company_bonuspointslog where company_id = " + str(
        cid) + " and  self_points is not null and self_points> 0 " +\
        " UNION SELECT '人工维护', '积分修改',to_char( tm, 'yyyy-mm-dd HH24:MI:SS' ) tm,"+\
        "( after_modify - before_modify ) :: TEXT, 	company_id :: TEXT	FROM company_pointschangelog 	WHERE company_id = " + str(cid)+\
        "  UNION  SELECT '兑换现金', '积分使用',to_char( tm, 'yyyy-mm-dd HH24:MI:SS' ) tm, points:: TEXT, 	company_id :: TEXT	FROM company_pointsredeemed	WHERE company_id = " + str(cid)+" )m " +\
        "left outer join (SELECT name ,id  from company_company )z on z.id = m.company_fr_id::int  order by m.tm desc "
    cur.execute(s)
    r = cur.fetchall()
    for i in r :
        data['data'].append([ i[1],i[0],i[3],i[2]])
    return  JsonResponse(data)


#积分报表
@login_required
def bonusPoints_list(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['渠道促销', '积分报表'], 'murl': '', 'dt': True, 'add': True,'date_from':'','date_to':''}
    data['clmns'] = ['兑换终端', '区域', '联系人', '兑换积分', '兑换金额', '兑换时间','剩余可用积分','累计兑换金额']
    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
    sWhere = " and (dt between '" + dt_fr + "' and '" + dt_to + "')"

    data['show_add'] = False
    # data['murl'] = '/company/bonusPoints/edit/'
    cur = connection.cursor()
    company_id = request.user.company_id
    ancestor_id = request.user.ancestor_id
    ancestor_id = 19318
    company_id = 19318

    s=f"""
        SELECT COALESCE(d.name,'未划分'),b.name,c.username,a.points::TEXT,a.amount::TEXT,to_char(a.tm,'yyyy-mm-dd HH24:MI:SS')tm,e.points::TEXT,f.amounts::TEXT  from (
        SELECT * FROM logistics.company_pointsredeemed WHERE ancestor_id = {ancestor_id} {sWhere})A
        left outer join (select id ,division_id,name from company_company WHERE ancestor_id = {ancestor_id} )b on b.id = a.company_id
        left outer join (SELECT id ,username ,last_name from company_user WHERE ancestor_id = {ancestor_id})c on c.id =a.user_id 
        left outer join (SELECT id ,name  from company_salesdivision )d on d.id =b.id 
        left outer join (SELECT points,company_id from company_bonuspoints WHERE ancestor_id = {ancestor_id})e on e.company_id =a.company_id 
        left outer join (SELECT sum(amount)amounts,company_id from company_pointsredeemed WHERE ancestor_id = {ancestor_id} GROUP BY company_id)f on f.company_id=a.company_id
    """
    cur.execute(s)
    rs = cur.fetchall()
    if rs:
        for r in rs :
            data['data'].append([r[1],r[0],r[2],r[3],r[4],r[5],r[6],r[7] ])
    return render(request, 'obj/list_points.html', data)


@csrf_exempt
def bonuspoints_infor(request,comapny_id):
    data = {'e': '', 'info': [],'details':[],'total':0}
    k = sK
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    dt_fr = request.GET.get('dt_fr','')
    dt_to = request.GET.get('dt_to',now())
    cur= connection.cursor()
    sDt = " and (dt BETWEEN'"+dt_fr+"'and '"+dt_to+"') "

    #查询是否有积分信息
    s = "SELECT b.name,b.point_ratio,a.points,a.ancestor_id FROM (select  points,channelpromotions_id,ancestor_id from company_bonuspoints where company_id = "+str(comapny_id)+")A "+\
        "left outer join (select id,point_ratio,name   from sales_channelpromotions )B "+\
        "on b.id = a.channelpromotions_id"
    cur.execute(s)
    r = cur.fetchone()
    if r:
        data['info']={"name":r[0],"point":r[2],"ratio":r[1]}
        s = "SELECT * from (SELECT * from (select '发货所得'::text as act,case contenttype_id when 19 then '收货确认' when 320 then '宴会申请' else'未知' end,  " + \
            "to_char(tm,'yyyy-mm-dd HH24:MI:SS')tm,jsonb_array_elements(parent_points )->> 'points'  as points  , jsonb_array_elements(parent_points )->> 'company_fr_id'as company_fr_id,id,remark from " + \
            " logistics.company_bonuspointslog where parent_points @>'[{\"company_fr_id\":" + str(
            comapny_id) + "}]'  ) a where a.company_fr_id = '" + str(comapny_id) + "'   " + \
            " union   SELECT '收货所得'::text as act, case contenttype_id when 19 then '收货确认' when 320 then '宴会申请' else'未知' end, " + \
            "to_char(tm,'yyyy-mm-dd HH24:MI:SS')tm,cast(self_points as TEXT) points,cast(company_id as TEXT),id,remark from logistics.company_bonuspointslog where company_id = " + str(
            comapny_id) + " and  self_points is not null and self_points> 0 " + \
            " UNION SELECT '人工维护', '积分修改',to_char( tm, 'yyyy-mm-dd HH24:MI:SS' ) tm," + \
            "( after_modify - before_modify ) :: TEXT, 	company_id :: TEXT,0,remark	FROM company_pointschangelog 	WHERE company_id = " + str(
            comapny_id) + \
            "  UNION  SELECT '兑换现金', '积分使用',to_char( tm, 'yyyy-mm-dd HH24:MI:SS' ) tm, points:: TEXT, 	company_id :: TEXT,0,remark	FROM company_pointsredeemed	WHERE company_id = " + str(
            comapny_id) + " )m " + \
            "left outer join (SELECT name ,id  from company_company )z on z.id = m.company_fr_id::int  " +\
            "LEFT OUTER JOIN (SELECT json_agg(json_build_object('points', a.points,'product',c.name,'qty',a.qty))details,a.log_id " + \
            "FROM  (SELECT SUM ( self_points )points,product_id,count(*) qty,log_id from company_pointslogdetails  GROUP BY product_id,log_id)a, " + \
            "  (SELECT name,id from product_product    )c  where   c.id = a.product_id    " + \
            " GROUP BY a.log_id) y ON y.log_ID = M.id :: INT    order by m.tm desc "
        cur.execute(s)
        res = cur.fetchall()
        if res:
            for re in res:
                detail_infor=[]
                if re[9]:
                    detail_infor = re[9]
                data['details'].append({"id":re[5],"activity_name":re[0],"event_name":re[1],"dt":re[2], "points":re[3],"remark":re[6],"detail_infor":detail_infor})
        # 返回总金额
        s = "SELECT sum(amount) from logistics.company_pointsredeemed where company_id = " + str(comapny_id) + " and ancestor_id = " + str(r[3]) + ";"
        cur.execute(s)
        totals = cur.fetchone()
        if totals[0]:
            data['total'] = totals[0]
    else:
        data['e'] = '暂无积分信息'
    return JsonResponse(data)
    

@csrf_exempt
def bonuspoints_infor_details(request,activity_name,log_id):
    data = {'e': '', 'info': [], 'details': [], 'list': [],'rule':0}
    k = sK
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    cur = connection.cursor()
    if activity_name == 'send':
        sbool = ' true '
    else:
        sbool = ' false '
    s = "SELECT m.log_id,n.triggers,z.details,m.action  FROM " + \
        "( SELECT COUNT ( * ) num, log_id,action, channelpromotions_id FROM company_pointslogdetails WHERE" + \
        " log_id = " + str(log_id) + " GROUP BY action, log_id, channelpromotions_id )m " + \
        "left outer join (select id,triggers from sales_channelpromotions )n	on m.channelpromotions_id = n.id " + \
        "left outer join ( SELECT json_agg ( json_build_object ( 'points', A.points, 'product', C.NAME, 'qty', A.qty ) ) details, " + \
        "A.log_id  FROM ( SELECT case when "+sbool+" then  SUM ( parent_points ) else SUM (self_points  ) end points, product_id, COUNT ( * ) qty, log_id FROM company_pointslogdetails " + \
        "GROUP BY product_id, log_id ) A, " + \
        "( SELECT NAME, ID FROM product_product ) C  WHERE C.ID = A.product_id GROUP BY A.log_id  )  z on z.log_id = m.log_id"
    cur.execute(s)
    r = cur.fetchone()
    if r:
        detail_infor = []
        rule = []
        if r[1]:
            for i in json.loads(r[1]):
                if r[3] == 1 and int(i['id'])==3:
                    if activity_name == 'send':
                        rule = i['details']['value_level1']
                    elif activity_name == 'receive':
                        rule = i['details']['value_terminal']
                if r[3] == 0 and int(i['id'])==2:
                    rule = i['details']['value']
        if r[2]:
            detail_infor = r[2]
        # data['details'].append({"detail_infor":detail_infor,"rule":rule})
        data['details']=detail_infor
        data['rule']=rule
    s = "select a.label_code,a.label_pkg,b.name,d.name from (select label_code,label_pkg,product_id,log_id from company_pointslogdetails where log_id = "+str(log_id)+ \
        " )a left outer join(SELECT name,id from product_product)b on b.id = a.product_id "+\
        "LEFT OUTER JOIN ( SELECT CASE WHEN "+sbool+" THEN company_id :: TEXT ELSE jsonb_array_elements ( parent_points ) ->> 'company_fr_id' END company_id, ID FROM company_bonuspointslog ) C ON C.ID = A.log_id "+\
        "left outer JOIN (SELECT name,id from company_company )d on d.id=c.company_id::int"
    cur.execute(s)
    for i in cur.fetchall():
        data['list'].append({"label_code":i[0],"label_pkg":i[1],"product":i[2],"agent":i[3]})
    return  JsonResponse(data) 

def delibery_record(request,user_id):
    data = {'e':'',
            'data':[]}
    k = sK
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    us = User.objects.get(id=int(user_id))
    dt = datetime.datetime.now().strftime('%Y-%m-%d')
    dt_fr = request.GET.get('date_fr', dt)
    dt_to = request.GET.get('date_to', dt)
    cid = us.company_id
    cur = connection.cursor()
    cs = Company.objects.get(id=int(cid))
    aid=cs.ancestor_id
    tb_stk = "stkdetails.c" + str(aid)
    sWhere = "company_id=" + str(cid) + " and vtype_id = 2  and (dt between '"+dt_fr+"' and '"+dt_to+"')"

    s=f"""
        select A.batch_id ,to_char(b.tm,'yyyy-mm-dd HH24:MI:SS'),
        (select name from inventory_voucher where id =a.vtype_id),
        b.code,
        (select name from product_product where id=a.product_id),
        (select name from company_company where id = b.company_id),
        (select name from company_company where id = b.company_to_id),
        (select username from company_user where id = b.user_id),
        x,h,p,
        (select batch_id from inventory_receipt e where e.batch_id=A.batch_id)
        from(
            SELECT
                batch_id,
                product_id,
                vtype_id,
                SUM ( x ) x,
                SUM ( h ) h,
                SUM ( P ) P 
            FROM
                (
                SELECT
                    batch_id,
                    product_id,
                    vtype_id,
                    label_pkg,
                    CASE
                            WHEN label_pkg = 3 THEN
                            1 ELSE 0 
                        END x,
                    CASE
                            WHEN label_pkg = 2 THEN
                            1 ELSE 0 
                        END h,
                    CASE
                        WHEN label_pkg = 1 THEN
                        1 ELSE 0 
                    END P 
                FROM
                    {tb_stk} WHERE {sWhere}) d            
            GROUP BY
                batch_id,
                product_id,
                vtype_id
                ) A 
        LEFT JOIN logistics.inventory_batch b ON A.batch_id = b.id
        order by A.batch_id
    """

    cur.execute(s)
    for r in cur.fetchall():
        if r[11]:
            state=1
        else:
            state=2
        data['data'].append( {
            'tm': r[1],  # 时间
            'vtype': r[2],  # 单据类别
            'batch_code': r[3],
            'product': r[4],  # 产品名称
            'company_fr_name': r[5],  # 操作方
            'company_to_name': r[6],  # 客户名称
            'username': r[7],
            'x': r[8],  # 箱
            'h': r[9],  # 盒
            'p': r[10],  # 瓶
            'state': state,  #是否确认收货
        })
    return JsonResponse(data)
    
    
@csrf_exempt
def get_applay_unable(request,company_id):
    data={'e':'','data':[],'total':0}
    k = sK
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    c = Company.objects.get(id=company_id)
    t = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
    dt_fr = request.GET.get('dt_fr',t)
    dt_to = request.GET.get('dt_to',t)
    sDt = " and (tm BETWEEN'" + dt_fr + "'and '" + dt_to + "') "
    sDt = " "
    # 先判断当前是否有符合条件的渠道营销方案正在进行 表名：sales_channelpromotions
    sSaldiv = ''
    sSubdiv = ''
    # 经销商是否含销售战区信息
    if c.division:
        sSaldiv = " and case when array_length(div_ids,1) is null then true else ARRAY[" + str(
            c.division_id) + "] <@ div_ids end "
    # 经销商是否含销售分区信息
    if c.sub_division:
        sSubdiv = " and case when array_length(div_ids,1) is null then true else ARRAY[" + str(
            c.sub_division_id) + "] <@ div_ids end "
    # 当前经销商是否符合渠道营销方案

    aid = str(c.ancestor_id)
    s = "select id,name,awardcategory_id,triggers,point_ratio from sales_channelpromotions " + \
        "where company_id=" + aid + " and ('" + t + "' between tm_start and tm_end) and status=1 " + \
         sSaldiv + sSubdiv
    sTrigger = ''
    cur = connection.cursor()
    sTrigger = " and triggers @> '[{\"id\":\"2\"}]'::jsonb "
    s = s + sTrigger + " order by priority"
    cur.execute(s)
    r = cur.fetchone()
    p_ratio = 1
    if r:
        # 渠道促销活动id
        channelpromotions_id = r[0]
        # 奖励类型id
        # sales_awardcategory 1;"实物"2;"积分 "3;"优惠券 "4;"微信红包"5;"记账现金"6;"代金券"7;"卡券"8;"福袋"
        awd_id = r[2]
        # 宴会申请 返利详情
        # {"package":"1", "value":"1"}
        details = {}
        for d in json.loads(r[3]):
            if d['id'] == '2':
                details = d['details']
        # 有宴会申请设置信息
        if details:
            # 业务逻辑处理
            if details['package'] == 1 or details['package'] == '1' or details['package'] == 2 or details[
                'package'] == '2':
                p_ratio = details['value']

    s = "SELECT	a.id,a.policy,b.ratio from ( SELECT ID, channelpromotions_id,policy  FROM banquet_apply WHERE ancestor_id = "+str(c.ancestor_id)+" AND status = 0 AND " +\
        "company_id = "+str(company_id)+sDt+" )	A " +\
        "LEFT OUTER JOIN ( SELECT ID,n->'details'->>'value' ratio FROM sales_channelpromotions m ,jsonb_array_elements(m.triggers) n  where  " +\
        " n->>'id' ='2') b ON b.ID = A.channelpromotions_id "

    cur.execute(s)
    rs = cur.fetchall()
    total = 0
    for r in rs:
        if r[2]:
            p_ratio = r[2]
        s = "select apply_id, sum (CASE package_id WHEN 3 THEN (SELECT qty_p FROM logistics.product_product WHERE id = banquet_apply_codes.product_id) * "+p_ratio+" " +\
            "WHEN 2 THEN (SELECT qty_h FROM logistics.product_product WHERE id = banquet_apply_codes.product_id)* "+p_ratio+" " +\
            "WHEN 1 THEN (SELECT qty_x FROM logistics.product_product WHERE id = banquet_apply_codes.product_id)* "+p_ratio+" ELSE 0 END  )from banquet_apply_codes  " +\
            "where apply_id = "+str(r[0])+" " +\
			"GROUP BY apply_id "
        cur.execute(s)
        res = cur.fetchone()
        if res:
            total = total +res[1]
            data['data'].append({'apply_policy':r[1],'apply_id':r[0],'points':res[1]})
        else:
            data['data'].append({'apply_policy': r[1], 'apply_id': r[0], 'points': 0})
    data['total'] = total

    return JsonResponse(data)
    
    
@csrf_exempt
def address_update(request,company_id):
    data={'e':''}
    r = json.loads(request.body)
    k = sK
    e = time_key_check(request, k)
    if e:
        data['e'] = e
        return JsonResponse(data)
    if 'lng_lat' not in r or 'address' not in r or 'gis_address' not in r :
        data['e']='经纬度、地址不能为空'
        return JsonResponse(data)
    lng_lat = r['lng_lat']
    c = Company.objects.get(id=company_id)
    c.lng_lat= lng_lat
    if len(r['address'])>0:
        c.address = r['address']
    c.gis_address = r['gis_address']
    c.save()
    return JsonResponse(data)


@login_required
def scan_list_info(request):
    obj = request.GET.get('obj', '')
    if obj != "":
        data = {'data': [], 'clmns': [], 'e': [], 'subtt': ['', ''], 'murl': '', 'dt': False, 'add': True,
                'date_from': '', 'date_to': ''}
    return render(request, 'company/label_scan_details.html')


@login_required
def scan_list_info_data(request, what):
    data = {
        'e': '',
        'dt': False,
        'date_from': '',
        'date_to': '',
        'data': []
    }
    u = request.user
    c = request.user.company
    cur = connection.cursor()

    if what == "query":
        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
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        company_id = str(c.id)

        sql = "select a.label_code,b.name,c.wx_nickname,c.wx_headimgurl,a.address,a.tm FROM " +\
              "(SELECT label_code,address,to_char(tm,'yyyy-mm-dd HH:MI:ss')tm,product_id,consumer_id from sales_labelscan " +\
              "where company_id ="+str(company_id)+" and dt BETWEEN '"+dt_fr+"'and '"+dt_to+"')a "+\
              "LEFT  outer join (select name,id from product_product) b on a.product_id = b.id " + \
              "LEFT  outer join (SELECT wx_nickname,wx_headimgurl,id from sales_consumeraccount) c on a.consumer_id = c.id"
        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            headimg=''
            if r[3]:
                headimg = '<img src="' + r[3] + '" style="width:30px"/> '
            data['data'].append([
                r[0],
                r[1],
                r[2],
                headimg,
                r[4],
                r[5]
            ]) 
    elif what == "ticket":
        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
        data["dt"] = True
        ancestor_id = str(c.ancestor_id)
        company_id = str(c.id)
        cur = connection.cursor()
        sql = "SELECT * from ( select label_code,name,phone,to_char(tm,'yyyy-mm-dd hh:mi:ss')tm, " +\
              "address,activity_name,award_cat,award_img,award_name,product_id from sales_consumerwinner " +\
              "WHERE  company_Id = "+company_id+" and dt BETWEEN '"+dt_fr+"' and '"+dt_to+"')A " +\
              "left outer join (SELECT id,name from product_product )b on b.id = a.product_id " +\
              "where label_code is not null"

        cur.execute(sql)
        rs = cur.fetchall()
        for r in rs:
            img = ''
            if r[7]:
                img = '<img src="' + r[7] + '" style="width:30px"/> '
            data['data'].append([r[0],r[1],r[2], r[3], r[4], r[5], r[6], img, r[8], r[9], r[10]])

    return JsonResponse(data)


def data_visualization(request):
    company_id = request.user.company_id
    cur = connection.cursor()
    s=f"""
        select name from company_company where id={company_id}
    """
    cur.execute(s)
    rs = cur.fetchall()
    for r in rs:
        path = 'F:\\datacenter\\media\\fileupload\\'+ str(r[0])
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['数据可视化', '数据报表']}
    data['clmns'] = ['时间', '文件名称','箱数' , '备注']
    for filenames in os.listdir(path):
        for line in os.listdir(path+"\\" +filenames):
            l=line
            s=l.split('_')
            tm=s[0]
            x=s[4]
            data['data'].append([tm,
                                 "<a href='/media/fileupload/"+ str(r[0])+"/" +
                                 str(tm) + "/"+ str(l)+"' target='_blank'>" + str(l) + "</a>",
                                 x,1 ])
            # print(data['data'])
    return render(request, 'obj/list_points.html', data)


@login_required
def saleman_action_approve(request,id):
    data={'e':''}
    s_action = Action.objects.get(id=int(id))
    user = request.user
    approved = request.GET.get('approved', '')
    rejected = request.GET.get('rejected', '')
 
    if rejected:
        s_action.status = 2
    if approved:
        s_action.status = 1

    s_action.permit_tm = datetime.datetime.now()
    s_action.permiter = user
    s_action.save()
    data = saleman_manage_data(request,'action')
    res = json.loads(data.content)
    if data.status_code == 200 :
        if res['e'] == '':
            return JsonResponse(res)
    else:
        data['e']='网络错误，请稍后再试。'
    # return render(request, 'company/saleman.html', {'data': data})
    return  JsonResponse(data)
    
  
def get_sub_companies(request):
    """
    根据company_id和ancestor_id获取下级Company, 通过company_name对下级名称进行模糊查询
    """
    arguments = dict(request.GET)
    try:
        company_id = arguments.get("company_id", "")
        ancestor_id = arguments.get("ancestor_id", "")
        company_name = arguments.get("name", "")
        kwargs = {}
        if company_id:
            kwargs['parent'] = company_id[0]
        if ancestor_id:
            kwargs['ancestor_id'] = ancestor_id[0]
        if company_name:
            kwargs['name__contains'] = company_name[0]
        sub_companies = Company.objects.values_list("pk", "name")\
            .filter(**kwargs).exclude(level=1)
        subs = []
        for sub in sub_companies:
            subs.append({"id": sub[0], "name": sub[1]})
        return JsonResponse({"sub_companies": subs})
    except Exception as e:
        return JsonResponse({"e": e.args})

@login_required
def error_checking(request):
    data = {'data': [], 'clmns': [], 'e': [],
            'subtt': ['企业管理', '出入库数据错误排查'], 'murl': '', 'dt': True, 'add': True, 'date_from': '', 'date_to': ''}
    data['clmns'] = ['上传时间','单据编号','企业名称', '经销商','单据类型','batch_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
    sWhere = "  (dt between '" + dt_fr + "' and '" + dt_to + "')"
    cur=connection.cursor()
    s=f"""
        select batch_id,err,count(1) from inventory_batchdetails where {sWhere} and err='标签错误'
        group by batch_id,err    
    """
    cur.execute(s)
    for r in cur.fetchall():
        s=f"""
            select to_char(tm,'yyyy-mm-dd HH24:MI:SS'),code,(select name from company_company where id=company_id),
            (select name from logistics.inventory_voucher where id=vtype_id),id,(select name from company_company where id=a.ancestor_id)
            from inventory_batch a where id={r[0]}
        
        """
        cur.execute(s)
        for rr in cur.fetchall():
            btn = '<button style="margin:0;padding:1px 10px;" onclick="catPointsDetailss(' + str(
                r[0]) + ')" class="update btn btn-sm btn-warning">详情</button>'
            data['data'].append([
                rr[0],rr[1],rr[5],rr[2],rr[3],rr[4],r[1],btn
            ])
    return render(request, 'obj/list_obj.html',data)

@login_required
def error_checking_list(request,id):
    data = {'data': [], 'e': [], }
    cur = connection.cursor()
    s=f"""
        select label_code,(select name from product_product where id=product_id),err from inventory_batchdetails where {id}=batch_id and err='标签错误'
    """
    cur.execute(s)
    for r in cur.fetchall():
        data['data'].append([r[0],r[2]])
    return JsonResponse(data)


