from django.shortcuts import render

# Create your views here.
from .models import *
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext_lazy as _
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.db import connection
from django.shortcuts import render


#2020-06-28 销售订单
@login_required
def salesorder(request,id=None):
    cur=connection.cursor()
    cid=str(request.user.company.id)
    if id:  #查看当前订单        
        html='salseorder_view.html'              
        clmns=[
            _('产品编码'),
            _('产品名称'),
            _('数量'),
            _('单位'),
            _('仓库'),
            _('订单类型'),
        ]
        s="select id,product_code,product_name,qty,coalesce(unit_name,''),coalesce(store_name,''),coalesce(ordertype_name,'') "+\
            "from erp_salesorderdetails where salesorder_id="+id
        cur.execute(s)
        data=[]
        for r in cur.fetchall():
            data.append([
                r[1],
                r[2],r[3],r[4],r[5],r[6]
            ])
        c=''
        cur.execute("select coalesce(customer_name,'') from erp_salesorder where id="+id)
        r=cur.fetchone()        
        if r:
            c=r[0]     
        return render(request,'erp/'+html,{'clmns':clmns,'data':data,'customer':c})  
        
    else:   #销售订单列表
        html='salseorder_list.html'
        clmns=[
            _('订单编号'),
            _('经销商'),
            _('经销商编码'),
            _('生成时间'),
            _('喷码信息'),
        ]
        s="select id,code,customer_name,customer_code,to_char(tm,'yyyy-mm-dd HH24:MI:SS'),coalesce(marking,'') "+\
            "from erp_salesorder where company_id="+cid
        cur.execute(s)
        data=[]
        for r in cur.fetchall():
            data.append([
                "<a href='/erp/salesorder/"+str(r[0])+"/'>"+r[1]+"</a>",
                r[2],r[3],r[4],r[5]
            ])
        return render(request,'erp/'+html,{'clmns':clmns,'data':data})        
        


