from django.shortcuts import render

# Create your views here.
import json
import math

import re
from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.conf import settings
from django.db import connection, transaction
import datetime

from utils.sqlinjection import sqlinjections
from utils.cust_data import customer_data
from utils.et_CACC_NO import et_CACC_NO
from utils.examine_ood import examine_ood
from utils.if_account import if_account

from utils.usr_data import usr_data
from utils.monthly_odd import monthly_odd
from utils.executeQuery import executeQuery

# 进货单

class PcOrder(View):
    @transaction.atomic
    def get(self, request):
        context = {
            'a': '进货单'
        }
        #HttpResponse(content=响应体,content_type=响应体数据MIME类型,status=状态码)
        return http.JsonResponse(context)

    @transaction.atomic
    def post(self, request):
        # 1获取参数
        req_data = json.loads(request.body.decode())
        PS_DD = req_data.get("PS_DD")  # 单据日期
        CUS_NO = req_data.get("CUS_NO")  # 客户编码
        CUS_NO_NAME = req_data.get("CUS_NO_NAME",'')  # 客户名称
        PS_NO = req_data.get("PS_NO")  # 单据号码
        TAX_ID = req_data.get("TAX_ID")  # 扣税类别
        ZHANG_ID = req_data.get("ZHANG_ID")  # 立账方式
        VOH_ID = req_data.get("VOH_ID",'')  # 凭证模板
        USR = req_data.get("USR")  # 制单人编码
        USR_NAME = req_data.get("USR_NAME",'')  # 制单人名称
        # TAX_RTO = req_data.get("TAX_RTO")  # 税率   直接取货品资料里面的
        AMT = req_data.get("AMT",0)  # 金额
        DEP = req_data.get("DEP",'')  # 部门代号
        SAL_NO = req_data.get("SAL_NO",'')  # 业务员代号
        KPF = req_data.get("KPF", '')  # 开票否

        #
        # print(PS_DD)
        # print(CUS_NO)
        # print(CUS_NO_NAME)
        # print(PS_NO)
        # print(TAX_ID)
        # print(ZHANG_ID)
        # print(VOH_ID)
        # print(USR)
        # print(USR_NAME)
        # # print(TAX_RTO)
        # print(AMT)
        # print(DEP)
        # print(SAL_NO)
        # 2校验参数
        # 校验日期格式
        # 判断是否有输入单号
        if PS_DD is None:
            return http.HttpResponseForbidden('请输入进货日期')
        # 判断是否有输入单号
        if PS_NO is None:
            return http.HttpResponseForbidden('请输入进货单号')
        if PS_NO[:3] != 'PCA' or len(PS_NO) != 11:
        #判断单号是否合法
            return http.HttpResponseForbidden('进货单号输入不合法，单号必须是PCA开头且长度必须是11位')
        #判断金额是否输入正确
        if re.compile('(^-?[0-9](\d+)?(\.\d{1,6})?$)|(^0$)|(^\d\.\d{1,2}$)').match(str(AMT)) is None:
            return http.HttpResponseForbidden('金额输入不正确')
        # 判断是否有输入供应商
        if CUS_NO is None:
            return http.HttpResponseForbidden('请输入供应商')
        if TAX_ID is None:
            return http.HttpResponseForbidden('请输入扣税类别')
        # 判断扣税类别是否输入正确
        if int(TAX_ID) != 1 and int(TAX_ID) != 2 and int(TAX_ID) != 3:
            return http.HttpResponseForbidden('扣税类别只能是1（不计税）,2（应该税内行），3（应税外加）')
        if ZHANG_ID is None:
            return http.HttpResponseForbidden('请输入立账方式')
        # 判断立账方式是否输入正确
        if int(ZHANG_ID) != 1 and int(ZHANG_ID) != 2 and int(ZHANG_ID) != 3:
            return http.HttpResponseForbidden('立账方式只能是1（单张立账）,2（不立账），3（收到发票才立账）')
        # #判断凭证模板是否输入
        # if VOH_ID is None:
        #     return http.HttpResponseForbidden('请输入凭证模板')
        # 判断制单人是否输入
        if USR is None:
            return http.HttpResponseForbidden('请输入制单人')
        # 判断税率是否输入
        # if TAX_RTO is None:
        #     return http.HttpResponseForbidden('请输入税率')
        # 判断进货单是否存在
        row_PS_NO = examine_ood('MF_PSS', 'PS_NO', PS_NO, 'PS_ID', 'PC')
        if row_PS_NO > 0:
            return http.HttpResponseForbidden('进货单号已存在')
        # 判断供应商是否哦存在，不存在的话创建
        try:
            row_cus_no = customer_data(CUS_NO, CUS_NO_NAME, '2', datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),0)
        except Exception:
            return http.HttpResponseForbidden('创建厂商失败')
        # 判断用户是否存在
        # row_usr = usr_data(USR, USR_NAME, datetime.datetime.strptime(PS_DD, '%Y-%m-%d'))
        try:
            # 判断用户是否存在，不存在则创建
            row_usr = usr_data(USR, USR_NAME, datetime.datetime.strptime(PS_DD, '%Y-%m-%d'))
        except Exception:
            return http.HttpResponseForbidden('创建用户失败')
        #判断单号是否存在
        #判断供应商是否存在
        #判断凭证模板是否存在->->->->->->->->->->->->->->->->->->->->->->待完成
        #判断字段制单人是否存在

        # 3数入库
        with connection.cursor() as cursor:

            # 单张立账或者不立账需要判断凭证模板是否存在，直接判断立账方式不等于3即可
            row_usr=0
            try:
                if VOH_ID !=0:
                    row_usr = cursor.execute("SELECT COUNT(*) FROM MF_VHID WHERE VOH_ID=%s AND BIL_ID='PC'", [VOH_ID]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden('查询凭证模板异常')
            if row_usr <= 0:
                return http.HttpResponseForbidden('凭证模板在ERP里面不存在请重新输入凭证模板')
            # 获取税率
            try:
                PRDT = cursor.execute("SELECT ISNULL(SPC_TAX,0),[NAME] FROM PRDT WHERE PRD_NO='AQ001'").fetchall()[0]
                SPC_TAX=PRDT[0]
                PRD_NAME=PRDT[1]
            except Exception:
                return http.HttpResponseForbidden('获取安装费税率异常')
            # 计算本位币  AMTN_NET：本位币， TAX：税金 ，SPC_TAX：税率
            TAX=0
            AMTN_NET=0
            if int(TAX_ID)==1:
                TAX=0
                AMTN_NET = AMT
            if int(TAX_ID)==2:
                print(SPC_TAX)
                TAX = float(AMT)/(1+float(SPC_TAX)/100)*float(SPC_TAX)/100
                AMTN_NET = float(AMT) - TAX
            if int(TAX_ID)==3:
                TAX = float(AMT) / 100 * float(SPC_TAX)
                AMTN_NET = float(AMT)
            sid = transaction.savepoint()  # 开启事物
            try:
                # 插入进货单表头->->->->->->->->->->->-改CUR_ID  RMB
                if int(ZHANG_ID) == 1:
                    cursor.execute("""INSERT INTO MF_PSS(PS_ID,PS_NO,PS_DD,CUS_NO,ZHANG_ID,USR,CHK_MAN,CLS_DATE,SYS_DATE,EXC_RTO,LZ_CLS_ID,CLSLZ,TAX_ID,ARP_NO,VOH_ID,DEP,SAL_NO)
                                VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   ['PC',
                                    'PC' + PS_NO[2::],
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    CUS_NO,
                                    ZHANG_ID,
                                    USR,
                                    USR,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    1,
                                    'F',
                                    '',
                                    TAX_ID,
                                    'AP' + PS_NO[2::],
                                    VOH_ID,
                                    DEP,
                                    SAL_NO])
                    # 插入自定义栏位表
                    if KPF=='T':
                        cursor.execute("""INSERT INTO MF_PSS_Z(PS_ID,PS_NO,KPF)VALUES(%s,%s,%s)""",['PC','PC' + PS_NO[2::],'T'])
                    # 插入立账单MF_MRP->->->->->->->->->改CUR_ID   RMB
                    cursor.execute("""INSERT INTO MF_ARP(ARP_ID,OPN_ID,ARP_NO,BIL_NO,CUS_NO,PAY_DD,AMT,AMTN,AMTN_NET,EXC_RTO,CLOSE_ID,BIL_ID,SYS_DATE,BIL_DD,DEP,ZHANG_ID)VALUES
                                            (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   [2,
                                    2,
                                    'AP' + PS_NO[2::],
                                    'PC' + PS_NO[2::],
                                    CUS_NO,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    0,
                                    AMT,
                                    AMTN_NET,
                                    1,
                                    'F',
                                    'PC',
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    DEP,
                                    ZHANG_ID])
                if int(ZHANG_ID) !=1:
                    print(3)
                    cursor.execute("""INSERT INTO MF_PSS(PS_ID,PS_NO,PS_DD,CUS_NO,ZHANG_ID,USR,CHK_MAN,CLS_DATE,SYS_DATE,EXC_RTO,LZ_CLS_ID,CLSLZ,TAX_ID,ARP_NO,VOH_ID,DEP,SAL_NO)
                                  VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   ['PC',
                                    'PC' + PS_NO[2::],
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    CUS_NO,
                                    ZHANG_ID,
                                    USR,
                                    USR,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    1,
                                    'F',
                                    '',
                                    TAX_ID,
                                    '',
                                    VOH_ID,
                                    DEP,
                                    SAL_NO])
                # 插入进货单表身
                print(4)
                cursor.execute("""INSERT INTO TF_PSS(PS_ID,PS_NO,PS_DD,WH,PRD_NO,QTY,UP,AMT,AMTN_NET,TAX_RTO,ITM,UNIT,CSTN_SAL,PRE_ITM,TAX,EST_ITM,PRD_NAME)
                        VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                               ['PC',
                                'PC' + PS_NO[2::] ,
                                datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                '0000',
                                'AQ001',
                                1,
                                AMT,
                                AMT,
                                AMTN_NET,
                                SPC_TAX,
                                1,
                                1,
                                AMTN_NET,
                                1,
                                TAX,
                                1,
                                PRD_NAME
                                ])
            except Exception:
                transaction.savepoint_rollback(sid)  # 语句执行错误，进行语句回滚
                return http.HttpResponseForbidden("新增进货单sql语句执行错误")
            transaction.savepoint_commit(sid)  # 提交事物
        # {
        #     "PS_DD": "2019-12-09",
        #     "CUS_NO": "AQ1111",
        #     "CUS_NO_NAME": "天心客户",
        #     "PS_NO": "PCA19C09001",
        #     "TAX_ID": "1",
        #     "ZHANG_ID": "1",
        #     "VOH_ID": "01",
        #     "USR": "a00001",
        #     "USR_NAME": "楠楠",
        #     "AMT": "200",
        #     "DEP": "0000",
        #     "SAL_NO": "A00002",
        #     "user": "123",
        #     "password": "123"
        # }

        context = {
            "message": '新增进货单成功',
            "code":200
        }
        # HttpResponse(content=响应体,content_type=响应体数据MIME类型,status=状态码)
        return http.JsonResponse(context)
        # return http.JsonResponse({"code": RET.OK, "message": "ok"})

    @transaction.atomic
    def put(self, request):
        # 1获取参数
        req_data = json.loads(request.body.decode())
        PS_DD = req_data.get("PS_DD")  # 单据日期
        CUS_NO = req_data.get("CUS_NO")  # 客户编码
        CUS_NO_NAME = req_data.get("CUS_NO_NAME",'')  # 客户名称
        PS_NO = req_data.get("PS_NO")  # 单据号码
        TAX_ID = req_data.get("TAX_ID")  # 扣税类别
        ZHANG_ID = req_data.get("ZHANG_ID")  # 立账方式
        VOH_ID = req_data.get("VOH_ID")  # 凭证模板
        # TAX_RTO = req_data.get("TAX_RTO")  # 税率   直接取货品资料里面的
        AMT = req_data.get("AMT",0)  # 金额
        DEP = req_data.get("DEP",'')  # 部门代号
        SAL_NO = req_data.get("SAL_NO",'')  # 业务员代号
        KPF = req_data.get("KPF", '')  # 开票否
        # {
        #     "PS_DD": "2019-12-09",
        #     "CUS_NO": "AQ1111",
        #     "CUS_NO_NAME": "天心客户",
        #     "PS_NO": "PCA19C09001",
        #     "TAX_ID": "1",
        #     "ZHANG_ID": "1",
        #     "VOH_ID": "01",
        #     "USR": "a00001",
        #     "USR_NAME": "楠楠",
        #     "AMT": "200",
        #     "DEP": "0000",
        #     "SAL_NO": "A00002",
        #     "user": "123",
        #     "password": "123"
        # }
        # 2校验参数
        # 判断是否有输入单号
        if PS_DD is None:
            return http.HttpResponseForbidden('请输入进货日期')
        # 校验日期格式
        try:
            datetime.datetime.strptime(PS_DD, '%Y-%m-%d')
        except Exception:
            return http.HttpResponseForbidden('日期格式输入不正确')
        # 判断是否有输入单号
        if PS_NO is None:
            return http.HttpResponseForbidden('请输入进货单号')
        if PS_NO[:3] != 'PCA' or len(PS_NO) != 11:
            # 判断单号是否合法
            return http.HttpResponseForbidden('进货单号输入不合法，单号必须是PCA开头且长度必须为11位')
        # 判断金额是否输入正确
        if re.compile('(^-?[0-9](\d+)?(\.\d{1,6})?$)|(^0$)|(^\d\.\d{1,2}$)').match(str(AMT)) is None:
            return http.HttpResponseForbidden('金额输入不正确')
        # 判断是否有输入供应商
        if CUS_NO is None:
            return http.HttpResponseForbidden('请输入供应商')
        if TAX_ID is None:
            return http.HttpResponseForbidden('请输入扣税类别')
        # 判断扣税类别是否输入正确
        if int(TAX_ID) != 1 and int(TAX_ID) != 2 and int(TAX_ID) != 3:
            return http.HttpResponseForbidden('扣税类别只能是1（不计税）,2（应该税内行），3（应税外加）')
        if ZHANG_ID is None:
            return http.HttpResponseForbidden('请输入立账方式')
        # 判断立账方式是否输入正确
        if int(ZHANG_ID) != 1 and int(ZHANG_ID) != 2 and int(ZHANG_ID) != 3:
            return http.HttpResponseForbidden('立账方式只能是1（单张立账）,2（不立账），3（收到发票才立账）')
        # # 判断凭证模板是否输入
        # if VOH_ID is None:
        #     return http.HttpResponseForbidden('请输入凭证模板')
            # 判断进货单是否存在
        row_PS_NO = examine_ood('MF_PSS', 'PS_NO', PS_NO, 'PS_ID', 'PC')
        if row_PS_NO <= 0:
            return http.HttpResponseForbidden('进货单号不存在')
        # 判断供应商是否哦存在，不存在的话创建
        try:
            row_cus_no = customer_data(CUS_NO, CUS_NO_NAME, '2', datetime.datetime.strptime(PS_DD, '%Y-%m-%d'), 0)
        except Exception:
            return http.HttpResponseForbidden('创建厂商失败')

        #判断进货单是否产生后续单据===========待完成
        # 3数入库
        with connection.cursor() as cursor:
            # 判断单号是否产生后续单据，立账里面的一冲金额
            try:
                # 获取原来单据的立账方式
                ZHANG_ID_OLD = cursor.execute("SELECT ZHANG_ID FROM MF_PSS WHERE PS_ID='PC' AND PS_NO=%s",['PC' + PS_NO[2::]]).fetchall()[0][0]
                if int(ZHANG_ID_OLD)==1:
                    print('AP' + PS_NO[2::])
                    row_no = cursor.execute("SELECT ISNULL(AMTN_RCV,0) FROM MF_ARP WHERE ARP_NO=%s AND BIL_ID='PC'", ['AP' + PS_NO[2::]]).fetchall()[0][0]
                    if float(row_no)>0 and row_no is not None:
                        return http.HttpResponseForbidden('进货单已产生后续单据不允许修改')
                if int(ZHANG_ID_OLD) != 1:
                    row_no = cursor.execute("SELECT ISNULL(ACC_FP_NO,'') FROM MF_PSS WHERE PS_NO=%s AND PS_ID='PC'",['PC' + PS_NO[2::]]).fetchall()[0][0]
                    if row_no!='':
                        return http.HttpResponseForbidden('进货单已产生后续单据不允许修改')
            except Exception:
                return http.HttpResponseForbidden('判断进货单是否产生后续单据异常')
            # 判断传过来的凭证模板在数据库里面是否存在
            row_usr=0
            try:
                if VOH_ID !=0:
                    row_usr = cursor.execute("SELECT COUNT(*) FROM MF_VHID WHERE VOH_ID=%s AND BIL_ID='PC'", [VOH_ID]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden('查询凭证模板异常')
            if row_usr <= 0:
                return http.HttpResponseForbidden('凭证模板在ERP里面不存在请重新输入凭证模板')
            # 获取税率
            try:
                PRDT = cursor.execute("SELECT ISNULL(SPC_TAX,0),[NAME] FROM PRDT WHERE PRD_NO='AQ001'").fetchall()[0]
                SPC_TAX = PRDT[0]
                PRD_NAME = PRDT[1]
            except Exception:
                return http.HttpResponseForbidden('获取安装费税率异常')
            # 计算本位币  AMTN_NET：本位币， TAX：税金 ，SPC_TAX：税率
            TAX = 0
            AMTN_NET = 0
            if int(TAX_ID) == 1:
                TAX = 0
                AMTN_NET = AMT
            if int(TAX_ID) == 2:
                print(SPC_TAX)
                TAX = float(AMT) / (1 + float(SPC_TAX) / 100) * float(SPC_TAX) / 100
                AMTN_NET = float(AMT) - TAX
            if int(TAX_ID) == 3:
                TAX = float(AMT) / 100 * float(SPC_TAX)
                AMTN_NET = float(AMT)
            sid = transaction.savepoint()  # 开启事物
            try:
                # 插入进货单表头->->->->->->->->->->->-改CUR_ID  RMB
                # 修改自定义栏位表
                if KPF == 'T':
                    cursor.execute("""UPDATE MF_PSS_Z SET KPF=%s WHERE  PS_ID='PC' AND PS_NO=%s""",['T','PC' + PS_NO[2::]])
                if KPF == 'F':
                    cursor.execute("""UPDATE MF_PSS_Z SET KPF=%s WHERE  PS_ID='PC' AND PS_NO=%s""",['F','PC' + PS_NO[2::]])
                if int(ZHANG_ID) == 1:
                    print(1)
                    cursor.execute("""UPDATE MF_PSS SET PS_DD=%s,CUS_NO=%s,ZHANG_ID=%s,TAX_ID=%s,VOH_ID=%s,DEP=%s,SAL_NO=%s,MODIFY_DD=%s,ARP_NO=%s WHERE PS_ID='PC' AND PS_NO=%s """,
                               [
                                   datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                   CUS_NO,
                                   ZHANG_ID,
                                   TAX_ID,
                                   VOH_ID,
                                   DEP,
                                   SAL_NO,
                                   datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                   'AP' + PS_NO[2::],
                                   'PC' + PS_NO[2::]
                               ])
                    print(2)
                    # 如果旧的立账方式是1的话那么会有立账单，那么可以直接修改
                    print(DEP)
                    print(ZHANG_ID)
                    if int(ZHANG_ID_OLD)==1:
                        cursor.execute("""UPDATE MF_ARP SET CUS_NO=%s,PAY_DD=%s,AMTN=%s,AMTN_NET=%s,BIL_DD=%s,DEP=%s,ZHANG_ID=%s WHERE BIL_ID='PC' AND ARP_NO=%s""",
                                   [CUS_NO,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    AMT,
                                    AMTN_NET,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    DEP,
                                    ZHANG_ID,
                                    'AP' + PS_NO[2::]
                                    ])

                    #如果旧是立账方式四不为1，然后改为1那么系统会在生成一张立账单
                    if int(ZHANG_ID_OLD) != 1:
                        cursor.execute("""INSERT INTO MF_ARP(ARP_ID,OPN_ID,ARP_NO,BIL_NO,CUS_NO,PAY_DD,AMT,AMTN,AMTN_NET,EXC_RTO,CLOSE_ID,BIL_ID,SYS_DATE,BIL_DD,DEP,ZHANG_ID)VALUES
                                       (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                       [2,
                                        2,
                                        'AP' + PS_NO[2::],
                                        'PC' + PS_NO[2::],
                                        CUS_NO,
                                        datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                        0,
                                        AMT,
                                        AMTN_NET,
                                        1,
                                        'F',
                                        'PC',
                                        datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                        datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                        DEP,
                                        ZHANG_ID])
                if int(ZHANG_ID) != 1:
                    print(3)
                    cursor.execute(
                        """UPDATE MF_PSS SET PS_DD=%s,CUS_NO=%s,ZHANG_ID=%s,TAX_ID=%s,VOH_ID=%s,DEP=%s,SAL_NO=%s,MODIFY_DD=%s,ARP_NO=%s WHERE PS_ID='PC' AND PS_NO=%s """,
                        [
                            datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                            CUS_NO,
                            ZHANG_ID,
                            TAX_ID,
                            VOH_ID,
                            DEP,
                            SAL_NO,
                            datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                            '',
                            'PC' + PS_NO[2::]
                        ])
                    # 如果立账方式不为1的时候需要删除，立账单
                    cursor.execute(
                        """DELETE FROM MF_ARP WHERE BIL_ID='PC' AND ARP_NO=%s""",
                        [
                            'AP' + PS_NO[2::]
                        ])
                # 插入进货单表身
                print(4)
                cursor.execute("""UPDATE TF_PSS SET PS_DD=%s,UP=%s,AMT=%s,AMTN_NET=%s,CSTN_SAL=%s,TAX=%s,TAX_RTO=%s WHERE PS_ID='PC' AND PS_NO=%s""",
                        [datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                AMT,
                                AMT,
                                AMTN_NET,
                                AMTN_NET,
                                TAX,
                                SPC_TAX,
                                'PC' + PS_NO[2::]
                                ])

            except Exception:
                transaction.savepoint_rollback(sid)  # 语句执行错误，进行语句回滚
                return http.HttpResponseForbidden("修改进货单sql语句执行错误")
            transaction.savepoint_commit(sid)  # 提交事物
        context = {
            "message": '修改进货单成功',
            "code": 200
        }
        return http.JsonResponse(context)

    @transaction.atomic
    def delete(self, request):
        # 1获取参数
        req_data = json.loads(request.body.decode())
        PS_NO = req_data.get("PS_NO")  # 单据日期
        # {
        #     "PS_NO": "PCA19C09001",
        #     "user": "123",
        #     "password": "123"
        # }
        # 判断是否有输入单号
        if PS_NO is None:
            return http.HttpResponseForbidden('请输入进货单号')
        if PS_NO[:3] != 'PCA' or len(PS_NO) != 11:
            # 判断单号是否合法
            return http.HttpResponseForbidden('进货单号输入不合法，单号必须是PCA开头且长度必须为11位')
        # 判断进货单是否存在
        row_PS_NO = examine_ood('MF_PSS', 'PS_NO', PS_NO, 'PS_ID', 'PC')
        if row_PS_NO <= 0:
            return http.HttpResponseForbidden('进货单号不存在')
        # 3数入库
        with connection.cursor() as cursor:
            # 判断单号是否产生后续单据，立账里面的一冲金额
            try:
                # 获取原来单据的立账方式
                ZHANG_ID_OLD = cursor.execute("SELECT ZHANG_ID FROM MF_PSS WHERE PS_ID='PC' AND PS_NO=%s",
                                              ['PC' + PS_NO[2::]]).fetchall()[0][0]
                if int(ZHANG_ID_OLD) == 1:
                    print('AP' + PS_NO[2::])
                    row_no = cursor.execute("SELECT ISNULL(AMTN_RCV,0) FROM MF_ARP WHERE ARP_NO=%s AND BIL_ID='PC'",
                                            ['AP' + PS_NO[2::]]).fetchall()[0][0]
                    if float(row_no) > 0 and row_no is not None:
                        return http.HttpResponseForbidden('进货单已产生后续单据不允许删除')
                if int(ZHANG_ID_OLD) != 1:
                    row_no = cursor.execute("SELECT ISNULL(ACC_FP_NO,'') FROM MF_PSS WHERE PS_NO=%s AND PS_ID='PC'",
                                            ['PC' + PS_NO[2::]]).fetchall()[0][0]
                    if row_no != '':
                        return http.HttpResponseForbidden('进货单已产生后续单据不允许删除')
            except Exception:
                return http.HttpResponseForbidden('判断进货单是否产生后续单据异常')

            sid = transaction.savepoint()  # 开启事物
            try:
                cursor.execute("""DELETE FROM MF_PSS WHERE  PS_NO=%s AND PS_ID='PC'""", ['PC' + PS_NO[2::]])
                cursor.execute("""DELETE FROM TF_PSS WHERE  PS_NO=%s AND PS_ID='PC'""", ['PC' + PS_NO[2::]])
                cursor.execute("""DELETE FROM MF_ARP WHERE  ARP_NO=%s AND BIL_ID='PC'""", ['AP' + PS_NO[2::]])
            except Exception:
                transaction.savepoint_rollback(sid)  # 语句执行错误，进行语句回滚
                return http.HttpResponseForbidden("删除进货单失败")
            transaction.savepoint_commit(sid)  # 提交事物

        context = {
            "message": '删除进货单成功',
            "code": 200
        }
        return http.JsonResponse(context)
# 销货单
class SaOrder(View):

    @transaction.atomic
    def get(self, request):
        context = {
            'a': '销货单'
        }
        # HttpResponse(content=响应体,content_type=响应体数据MIME类型,status=状态码)
        return http.JsonResponse(context)

    @transaction.atomic
    def post(self, request):
        # 1获取参数
        req_data = json.loads(request.body.decode())
        PS_DD = req_data.get("PS_DD")  # 单据日期
        CUS_NO = req_data.get("CUS_NO")  # 客户编码
        CUS_NO_NAME = req_data.get("CUS_NO_NAME", '')  # 客户名称
        PS_NO = req_data.get("PS_NO")  # 单据号码
        TAX_ID = req_data.get("TAX_ID")  # 扣税类别
        ZHANG_ID = req_data.get("ZHANG_ID")  # 立账方式
        VOH_ID = req_data.get("VOH_ID", '')  # 凭证模板
        USR = req_data.get("USR")  # 制单人编码
        USR_NAME = req_data.get("USR_NAME", '')  # 制单人名称
        # TAX_RTO = req_data.get("TAX_RTO")  # 税率   直接取货品资料里面的
        AMT = req_data.get("AMT", 0)  # 金额
        DEP = req_data.get("DEP", '')  # 部门代号
        SAL_NO = req_data.get("SAL_NO", '')  # 业务员代号
        #
        # print(PS_DD)
        # print(CUS_NO)
        # print(CUS_NO_NAME)
        # print(PS_NO)
        # print(TAX_ID)
        # print(ZHANG_ID)
        # print(VOH_ID)
        # print(USR)
        # print(USR_NAME)
        # # print(TAX_RTO)
        # print(AMT)
        # print(DEP)
        # print(SAL_NO)
        # 2校验参数
        # 校验日期格式
        # {
        #     "PS_DD": "2019-12-09",
        #     "CUS_NO": "AQ2222",
        #     "CUS_NO_NAME": "收款",
        #     "PS_NO": "SAB19C09001",
        #     "TAX_ID": "1",
        #     "ZHANG_ID": "1",
        #     "VOH_ID": "01",
        #     "USR": "a00002",
        #     "USR_NAME": "楠楠",
        #     "AMT": "200",
        #     "DEP": "0000",
        #     "SAL_NO": "A00002",
        #     "user": "123",
        #     "password": "123"
        # }
        if PS_DD is None:
            return http.HttpResponseForbidden('请输入日期')
        try:
            datetime.datetime.strptime(PS_DD, '%Y-%m-%d')
        except Exception:
            return http.HttpResponseForbidden('日期格式输入不正确')
        # 判断是否有输入单号
        if PS_NO is None:
            return http.HttpResponseForbidden('请输入销货单号')
        if PS_NO[:3] != 'SAB' or len(PS_NO) != 11:
            # 判断单号是否合法
            return http.HttpResponseForbidden('销货单号输入不合法，单号必须是SAB开头且长度必须为11位')
        # 判断金额是否输入正确
        if re.compile('(^-?[0-9](\d+)?(\.\d{1,6})?$)|(^0$)|(^\d\.\d{1,2}$)').match(str(AMT)) is None:
            return http.HttpResponseForbidden('金额输入不正确')
        # 判断是否有输入供应商
        if CUS_NO is None:
            return http.HttpResponseForbidden('请输入客户')
        if TAX_ID is None:
            return http.HttpResponseForbidden('请输入扣税类别')
        # 判断扣税类别是否输入正确
        if int(TAX_ID) != 1 and int(TAX_ID) != 2 and int(TAX_ID) != 3:
            return http.HttpResponseForbidden('扣税类别只能是1（不计税）,2（应该税内行），3（应税外加）')
        if ZHANG_ID is None:
            return http.HttpResponseForbidden('请输入立账方式')
        # 判断立账方式是否输入正确
        if int(ZHANG_ID) != 1 and int(ZHANG_ID) != 2 and int(ZHANG_ID) != 3:
            return http.HttpResponseForbidden('立账方式只能是1（单张立账）,2（不立账），3（收到发票才立账）')
        # #判断凭证模板是否输入
        # if VOH_ID is None:
        #     return http.HttpResponseForbidden('请输入凭证模板')
        # 判断制单人是否输入
        if USR is None:
            return http.HttpResponseForbidden('请输入制单人')
        # 判断税率是否输入
        # if TAX_RTO is None:
        #     return http.HttpResponseForbidden('请输入税率')
        # 判断进货单是否存在
        row_PS_NO = examine_ood('MF_PSS', 'PS_NO', PS_NO, 'PS_ID', 'SA')
        if row_PS_NO > 0:
            return http.HttpResponseForbidden('销货单号已存在')
        # 判断供应商是否哦存在，不存在的话创建
        try:
            row_cus_no = customer_data(CUS_NO, CUS_NO_NAME, '1', datetime.datetime.strptime(PS_DD, '%Y-%m-%d'), 0)
        except Exception:
            return http.HttpResponseForbidden('创建客户失败')
        # 判断用户是否存在
        # row_usr = usr_data(USR, USR_NAME, datetime.datetime.strptime(PS_DD, '%Y-%m-%d'))
        try:
            # 判断用户是否存在，不存在则创建
            row_usr = usr_data(USR, USR_NAME, datetime.datetime.strptime(PS_DD, '%Y-%m-%d'))
        except Exception:
            return http.HttpResponseForbidden('创建用户失败')
        # 判断单号是否存在
        # 判断供应商是否存在
        # 判断凭证模板是否存在->->->->->->->->->->->->->->->->->->->->->->待完成
        # 判断字段制单人是否存在

        # 3数入库
        with connection.cursor() as cursor:

            # 单张立账或者不立账需要判断凭证模板是否存在，直接判断立账方式不等于3即可
            row_usr = 0
            try:
                if VOH_ID != 0:
                    row_usr = cursor.execute("SELECT COUNT(*) FROM MF_VHID WHERE VOH_ID=%s AND BIL_ID='SA'", [VOH_ID]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden('查询凭证模板异常')
            if row_usr <= 0:
                return http.HttpResponseForbidden('凭证模板在ERP里面不存在请重新输入凭证模板')
            # 获取税率
            try:
                PRDT = cursor.execute("SELECT ISNULL(SPC_TAX,0),[NAME] FROM PRDT WHERE PRD_NO='AQ001'").fetchall()[0]
                SPC_TAX = PRDT[0]
                PRD_NAME = PRDT[1]
            except Exception:
                return http.HttpResponseForbidden('获取安装费税率异常')
            # 计算本位币  AMTN_NET：本位币， TAX：税金 ，SPC_TAX：税率
            TAX = 0
            AMTN_NET = 0
            if int(TAX_ID) == 1:
                TAX = 0
                AMTN_NET = AMT
            if int(TAX_ID) == 2:
                print(SPC_TAX)
                TAX = float(AMT) / (1 + float(SPC_TAX) / 100) * float(SPC_TAX) / 100
                AMTN_NET = float(AMT) - TAX
            if int(TAX_ID) == 3:
                TAX = float(AMT) / 100 * float(SPC_TAX)
                AMTN_NET = float(AMT)
            sid = transaction.savepoint()  # 开启事物
            try:
                # 插入销货单表头->->->->->->->->->->->-改CUR_ID  RMB
                if int(ZHANG_ID) == 1:
                    cursor.execute("""INSERT INTO MF_PSS(PS_ID,PS_NO,PS_DD,CUS_NO,ZHANG_ID,USR,CHK_MAN,CLS_DATE,SYS_DATE,EXC_RTO,LZ_CLS_ID,CLSLZ,TAX_ID,ARP_NO,VOH_ID,DEP,SAL_NO,PRT_SW,YD_ID)
                                    VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   ['SA',
                                    'SA' + PS_NO[2::],
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    CUS_NO,
                                    ZHANG_ID,
                                    USR,
                                    USR,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    1,
                                    'F',
                                    '',
                                    TAX_ID,
                                    'AP' + PS_NO[2::],
                                    VOH_ID,
                                    DEP,
                                    SAL_NO,
                                    'N',
                                    'T'
                                    ])
                    # 插入立账单MF_MRP->->->->->->->->->改CUR_ID   RMB
                    print(222222222)
                    cursor.execute("""INSERT INTO MF_ARP(ARP_ID,OPN_ID,ARP_NO,BIL_NO,CUS_NO,PAY_DD,AMT,AMTN,AMTN_NET,EXC_RTO,CLOSE_ID,BIL_ID,SYS_DATE,BIL_DD,DEP,ZHANG_ID)VALUES
                                                (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   [1,
                                    2,
                                    'AP' + PS_NO[2::],
                                    'SA' + PS_NO[2::],
                                    CUS_NO,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    0,
                                    AMT,
                                    AMTN_NET,
                                    1,
                                    'F',
                                    'SA',
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    DEP,
                                    ZHANG_ID])
                if int(ZHANG_ID) != 1:
                    print(3)
                    cursor.execute("""INSERT INTO MF_PSS(PS_ID,PS_NO,PS_DD,CUS_NO,ZHANG_ID,USR,CHK_MAN,CLS_DATE,SYS_DATE,EXC_RTO,LZ_CLS_ID,CLSLZ,TAX_ID,ARP_NO,VOH_ID,DEP,SAL_NO,PRT_SW,YD_ID)
                                      VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   ['SA',
                                    'SA' + PS_NO[2::],
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    CUS_NO,
                                    ZHANG_ID,
                                    USR,
                                    USR,
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                    1,
                                    'F',
                                    '',
                                    TAX_ID,
                                    '',
                                    VOH_ID,
                                    DEP,
                                    SAL_NO,
                                    'N',
                                    'T'
                                    ])
                # 插入进货单表身
                print(4)
                cursor.execute("""INSERT INTO TF_PSS(PS_ID,PS_NO,PS_DD,WH,PRD_NO,QTY,UP,AMT,AMTN_NET,TAX_RTO,ITM,UNIT,CSTN_SAL,PRE_ITM,TAX,EST_ITM,PRD_NAME)
                            VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                               ['SA',
                                'SA' + PS_NO[2::],
                                datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                '0000',
                                'AQ002',
                                1,
                                AMT,
                                AMT,
                                AMTN_NET,
                                SPC_TAX,
                                1,
                                1,
                                AMTN_NET,
                                1,
                                TAX,
                                1,
                                PRD_NAME])
            except Exception:
                transaction.savepoint_rollback(sid)  # 语句执行错误，进行语句回滚
                return http.HttpResponseForbidden("新增销货单sql语句执行错误")
            transaction.savepoint_commit(sid)  # 提交事物

        context = {
            "message": '新增销货单成功',
            "code": 200
        }
        # HttpResponse(content=响应体,content_type=响应体数据MIME类型,status=状态码)
        return http.JsonResponse(context)
        # return http.JsonResponse({"code": RET.OK, "message": "ok"})

    @transaction.atomic
    def put(self, request):
        # 1获取参数
        req_data = json.loads(request.body.decode())
        PS_DD = req_data.get("PS_DD")  # 单据日期
        CUS_NO = req_data.get("CUS_NO")  # 客户编码
        CUS_NO_NAME = req_data.get("CUS_NO_NAME", '')  # 客户名称
        PS_NO = req_data.get("PS_NO")  # 单据号码
        TAX_ID = req_data.get("TAX_ID")  # 扣税类别
        ZHANG_ID = req_data.get("ZHANG_ID")  # 立账方式
        VOH_ID = req_data.get("VOH_ID")  # 凭证模板
        # TAX_RTO = req_data.get("TAX_RTO")  # 税率   直接取货品资料里面的
        AMT = req_data.get("AMT", 0)  # 金额
        DEP = req_data.get("DEP", '')  # 部门代号
        SAL_NO = req_data.get("SAL_NO", '')  # 业务员代号

        # {
        #     "PS_DD": "2019-12-09",
        #     "CUS_NO": "AQ2222",
        #     "CUS_NO_NAME": "收款",
        #     "PS_NO": "SAB19C09001",
        #     "TAX_ID": "3",
        #     "ZHANG_ID": "3",
        #     "VOH_ID": "01",
        #     "USR": "a00002",
        #     "USR_NAME": "楠楠",
        #     "AMT": "200",
        #     "DEP": "0000",
        #     "SAL_NO": "A00002",
        #     "user": "123",
        #     "password": "123"
        # }
        # 2校验参数
        # 校验日期格式
        if PS_DD is None:
            return http.HttpResponseForbidden('请输入日期')
        try:
            datetime.datetime.strptime(PS_DD, '%Y-%m-%d')
        except Exception:
            return http.HttpResponseForbidden('日期格式输入不正确')
        # 判断是否有输入单号
        if PS_NO is None:
            return http.HttpResponseForbidden('请输入销货单号')
        if PS_NO[:3] != 'SAB' or len(PS_NO) != 11:
            # 判断单号是否合法
            return http.HttpResponseForbidden('销货单号输入不合法，单号必须是SAB开头且长度必须为11位')
        # 判断金额是否输入正确
        if re.compile('(^-?[0-9](\d+)?(\.\d{1,6})?$)|(^0$)|(^\d\.\d{1,2}$)').match(str(AMT)) is None:
            return http.HttpResponseForbidden('金额输入不正确')
        # 判断是否有输入供应商
        if CUS_NO is None:
            return http.HttpResponseForbidden('请输入客户')
        if TAX_ID is None:
            return http.HttpResponseForbidden('请输入扣税类别')
        # 判断扣税类别是否输入正确
        if int(TAX_ID) != 1 and int(TAX_ID) != 2 and int(TAX_ID) != 3:
            return http.HttpResponseForbidden('扣税类别只能是1（不计税）,2（应该税内行），3（应税外加）')
        if ZHANG_ID is None:
            return http.HttpResponseForbidden('请输入立账方式')
        # 判断立账方式是否输入正确
        if int(ZHANG_ID) != 1 and int(ZHANG_ID) != 2 and int(ZHANG_ID) != 3:
            return http.HttpResponseForbidden('立账方式只能是1（单张立账）,2（不立账），3（收到发票才立账）')
        # # 判断凭证模板是否输入
        # if VOH_ID is None:
        #     return http.HttpResponseForbidden('请输入凭证模板')
        # 判断进货单是否存在
        row_PS_NO = examine_ood('MF_PSS', 'PS_NO', PS_NO, 'PS_ID', 'SA')
        if row_PS_NO <= 0:
            return http.HttpResponseForbidden('销货单号不存在')
        # 判断供应商是否哦存在，不存在的话创建
        try:
            row_cus_no = customer_data(CUS_NO, CUS_NO_NAME, '2', datetime.datetime.strptime(PS_DD, '%Y-%m-%d'), 0)
        except Exception:
            return http.HttpResponseForbidden('创建客户失败')

        # 判断进货单是否产生后续单据===========待完成
        # 3数入库
        with connection.cursor() as cursor:

            # 判断单号是否产生后续单据，立账里面的一冲金额
            try:
                # 获取原来单据的立账方式
                ZHANG_ID_OLD = cursor.execute("SELECT ZHANG_ID FROM MF_PSS WHERE PS_ID='SA' AND PS_NO=%s",
                                              ['SA' + PS_NO[2::]]).fetchall()[0][0]
                print('AP' + PS_NO[2::])
                if int(ZHANG_ID_OLD) == 1:
                    print('AP' + PS_NO[2::])
                    row_no = cursor.execute("SELECT ISNULL(AMTN_RCV,0) FROM MF_ARP WHERE ARP_NO=%s AND BIL_ID='SA'",
                                            ['AP' + PS_NO[2::]]).fetchall()[0][0]
                    if float(row_no) > 0 and row_no is not None:
                        return http.HttpResponseForbidden('销货单已产生后续单据不允许修改')
                if int(ZHANG_ID_OLD) != 1:
                    row_no = cursor.execute("SELECT ISNULL(ACC_FP_NO,'') FROM MF_PSS WHERE PS_NO=%s AND PS_ID='SA'",
                                            ['SA' + PS_NO[2::]]).fetchall()[0][0]
                    if row_no != '':
                        return http.HttpResponseForbidden('销货单已产生后续单据不允许修改')
            except Exception:
                return http.HttpResponseForbidden('判断销货单是否产生后续单据异常')
            # 判断传过来的凭证模板在数据库里面是否存在
            row_usr = 0
            try:
                if VOH_ID != 0:
                    row_usr = cursor.execute("SELECT COUNT(*) FROM MF_VHID WHERE VOH_ID=%s AND BIL_ID='PC'", [VOH_ID]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden('查询凭证模板异常')
            if row_usr <= 0:
                return http.HttpResponseForbidden('凭证模板在ERP里面不存在请重新输入凭证模板')
            # 获取税率
            try:
                PRDT = cursor.execute("SELECT ISNULL(SPC_TAX,0),[NAME] FROM PRDT WHERE PRD_NO='AQ001'").fetchall()[0]
                SPC_TAX = PRDT[0]
                PRD_NAME = PRDT[1]
            except Exception:
                return http.HttpResponseForbidden('获取安装费税率异常')
            # 计算本位币  AMTN_NET：本位币， TAX：税金 ，SPC_TAX：税率
            TAX = 0
            AMTN_NET = 0
            if int(TAX_ID) == 1:
                TAX = 0
                AMTN_NET = AMT
            if int(TAX_ID) == 2:
                print(SPC_TAX)
                TAX = float(AMT) / (1 + float(SPC_TAX) / 100) * float(SPC_TAX) / 100
                AMTN_NET = float(AMT) - TAX
            if int(TAX_ID) == 3:
                TAX = float(AMT) / 100 * float(SPC_TAX)
                AMTN_NET = float(AMT)
            sid = transaction.savepoint()  # 开启事物
            try:
                # 插入进货单表头->->->->->->->->->->->-改CUR_ID  RMB
                if int(ZHANG_ID) == 1:
                    print(1)
                    cursor.execute(
                        """UPDATE MF_PSS SET PS_DD=%s,CUS_NO=%s,ZHANG_ID=%s,TAX_ID=%s,VOH_ID=%s,DEP=%s,SAL_NO=%s,MODIFY_DD=%s,ARP_NO=%s WHERE PS_ID='SA' AND PS_NO=%s """,
                        [
                            datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                            CUS_NO,
                            ZHANG_ID,
                            TAX_ID,
                            VOH_ID,
                            DEP,
                            SAL_NO,
                            datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                            'AP' + PS_NO[2::],
                            'SA' + PS_NO[2::]
                        ])
                    print(2)
                    # 如果旧的立账方式是1的话那么会有立账单，那么可以直接修改
                    if int(ZHANG_ID_OLD) == 1:
                        cursor.execute(
                            """UPDATE MF_ARP SET CUS_NO=%s,PAY_DD=%s,AMTN=%s,AMTN_NET=%s,BIL_DD=%s,DEP=%s,ZHANG_ID=%s WHERE BIL_ID='SA' AND ARP_NO=%s""",
                            [CUS_NO,
                             datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                             AMT,
                             AMTN_NET,
                             datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                             DEP,
                             ZHANG_ID,
                             'AP' + PS_NO[2::]
                             ])
                    # 如果旧是立账方式四不为1，然后改为1那么系统会在生成一张立账单
                    if int(ZHANG_ID_OLD) != 1:
                        cursor.execute("""INSERT INTO MF_ARP(ARP_ID,OPN_ID,ARP_NO,BIL_NO,CUS_NO,PAY_DD,AMT,AMTN,AMTN_NET,EXC_RTO,CLOSE_ID,BIL_ID,SYS_DATE,BIL_DD,DEP,ZHANG_ID)VALUES
                                           (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                       [1,
                                        2,
                                        'AP' + PS_NO[2::],
                                        'SA' + PS_NO[2::],
                                        CUS_NO,
                                        datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                        0,
                                        AMT,
                                        AMTN_NET,
                                        1,
                                        'F',
                                        'SA',
                                        datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                        datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                                        DEP,
                                        ZHANG_ID])
                if int(ZHANG_ID) != 1:
                    print(3)
                    cursor.execute(
                        """UPDATE MF_PSS SET PS_DD=%s,CUS_NO=%s,ZHANG_ID=%s,TAX_ID=%s,VOH_ID=%s,DEP=%s,SAL_NO=%s,MODIFY_DD=%s,ARP_NO=%s WHERE PS_ID='SA' AND PS_NO=%s """,
                        [
                            datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                            CUS_NO,
                            ZHANG_ID,
                            TAX_ID,
                            VOH_ID,
                            DEP,
                            SAL_NO,
                            datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                            '',
                            'SA' + PS_NO[2::]
                        ])
                    # 如果立账方式不为1的时候需要删除，立账单
                    cursor.execute(
                        """DELETE FROM MF_ARP WHERE BIL_ID='SA' AND ARP_NO=%s""",
                        [
                            'AP' + PS_NO[2::]
                        ])
                # 插入进货单表身
                print(4)
                cursor.execute(
                    """UPDATE TF_PSS SET PS_DD=%s,UP=%s,AMT=%s,AMTN_NET=%s,CSTN_SAL=%s,TAX=%s,TAX_RTO=%s WHERE PS_ID='SA' AND PS_NO=%s""",
                    [datetime.datetime.strptime(PS_DD, '%Y-%m-%d'),
                     AMT,
                     AMT,
                     AMTN_NET,
                     AMTN_NET,
                     TAX,
                     SPC_TAX,
                     'SA' + PS_NO[2::]
                     ])

            except Exception:
                transaction.savepoint_rollback(sid)  # 语句执行错误，进行语句回滚
                return http.HttpResponseForbidden("新增进货单sql语句执行错误")
            transaction.savepoint_commit(sid)  # 提交事物
        context = {
            "message": '修改进货单成功',
            "code": 200
        }
        return http.JsonResponse(context)

    @transaction.atomic
    def delete(self, request):
        # 1获取参数
        req_data = json.loads(request.body.decode())
        PS_NO = req_data.get("PS_NO")  # 单据日期
        # 判断是否有输入单号
        if PS_NO is None:
            return http.HttpResponseForbidden('请输入销货单号')
        if PS_NO[:3] != 'SAB' or len(PS_NO) != 11:
            # 判断单号是否合法
            return http.HttpResponseForbidden('销货单号输入不合法，单号必须是SAB开头且长度必须为11位')
            # 判断进货单是否存在
        row_PS_NO = examine_ood('MF_PSS', 'PS_NO', PS_NO, 'PS_ID', 'SA')
        if row_PS_NO <= 0:
            return http.HttpResponseForbidden('销货单号不存在')
        # 3数入库
        with connection.cursor() as cursor:
            # 判断单号是否产生后续单据，立账里面的一冲金额
            try:
                # 获取原来单据的立账方式
                ZHANG_ID_OLD = cursor.execute("SELECT ZHANG_ID FROM MF_PSS WHERE PS_ID='SA' AND PS_NO=%s",
                                              ['SA' + PS_NO[2::]]).fetchall()[0][0]
                if int(ZHANG_ID_OLD) == 1:
                    print('AP' + PS_NO[2::])
                    row_no = cursor.execute("SELECT ISNULL(AMTN_RCV,0) FROM MF_ARP WHERE ARP_NO=%s AND BIL_ID='SA'",
                                            ['AP' + PS_NO[2::]]).fetchall()[0][0]
                    if float(row_no) > 0 and row_no is not None:
                        return http.HttpResponseForbidden('销货单已产生后续单据不允许删除')
                if int(ZHANG_ID_OLD) != 1:
                    row_no = cursor.execute("SELECT ISNULL(ACC_FP_NO,'') FROM MF_PSS WHERE PS_NO=%s AND PS_ID='SA'",
                                            ['SA' + PS_NO[2::]]).fetchall()[0][0]
                    if row_no != '':
                        return http.HttpResponseForbidden('销货单已产生后续单据不允许删除')
            except Exception:
                return http.HttpResponseForbidden('判断销货单是否产生后续单据异常')

            sid = transaction.savepoint()  # 开启事物
            try:
                cursor.execute("""DELETE FROM MF_PSS WHERE  PS_NO=%s AND PS_ID='SA'""", ['SA' + PS_NO[2::]])
                cursor.execute("""DELETE FROM TF_PSS WHERE  PS_NO=%s AND PS_ID='SA'""", ['SA' + PS_NO[2::]])
                cursor.execute("""DELETE FROM MF_ARP WHERE  ARP_NO=%s AND BIL_ID='SA'""", ['AP' + PS_NO[2::]])
            except Exception:
                transaction.savepoint_rollback(sid)  # 语句执行错误，进行语句回滚
                return http.HttpResponseForbidden("删除销货单失败")
            transaction.savepoint_commit(sid)  # 提交事物

        context = {
            "message": '删除销货单成功',
            "code": 200
        }
        return http.JsonResponse(context)


#预付款单
class PtPayment(View):
    @transaction.atomic
    def get(self, request):
        context = {
            'a': '客户预收款'
        }
        return http.JsonResponse(context)

    @transaction.atomic
    def post(self, request):
        # 获取参数
        req_data = json.loads(request.body.decode())
        RP_NO = req_data.get("RP_NO")  # 预付款单号         字符类型   ->->->->->->->->1
        RP_DD = req_data.get("RP_DD")  # 预付款日期            字符类型  ->->->->->->->->->->1
        CUS_NO = req_data.get("CUS_NO")  # 预付款客户编码        字符类型  ->->->->->->->->->->->->-1
        CUS_NO_NAME = req_data.get("CUS_NO_NAME",'')  # 预付款客户名称       字符类型  ->->->->->->->->->->-1
        AMTN_BC = req_data.get("AMTN_BC")  # 预付款金额            数字类型  ->->->->->->->->->->->->->-1
        CACC_NO = req_data.get("CACC_NO")  # 预付款银行编码          字符类型    ->->->->->->1
        USR = req_data.get("USR")  # 制单人编码                   字符类型   ->->->->->->->->->1
        USR_NAME = req_data.get("USR_NAME",'')  # 制单人姓名         字符类型   ->->->->->->->->->->->-1
        DEP = req_data.get("DEP",'')  # 部门         字符类型   ->->->->->->->->->->->-1
        SAL_NO = req_data.get("SAL_NO",0)  # 业务员         字符类型   ->->->->->->->->->->->-1
        VOH_ID = req_data.get("VOH_ID",0)  # 凭证模板         字符类型   ->->->->->->->->->->->-1
        # {
        #     "RP_DD": "2019-12-06",
        #     "CUS_NO": "AQ2222",
        #     "CUS_NO_NAME": "收款",
        #     "RP_NO": "RTF9C0202",
        #     "AMTN_BC": "150",
        #     "CACC_NO": "01",
        #     "VOH_ID": "01",
        #     "USR": "a00002",
        #     "USR_NAME": "楠楠",
        #     "DEP": "0000",
        #     "SAL_NO": "A00002",
        #     "user": "123",
        #     "password": "123"
        # }

        # 判断单号的合法性
        if RP_NO[:3] != 'RTF' or len(RP_NO) != 11:
            return http.HttpResponseForbidden('预收款单号输入不合法，单号必须是RTF开头且长度长度必须为11位')
        if RP_DD is None:
            return http.HttpResponseForbidden('请输入日期')
        # 校验日期格式
        try:
            datetime.datetime.strptime(RP_DD, '%Y-%m-%d')
        except Exception:
            return http.HttpResponseForbidden('日期格式输入不正确')
        if RP_NO is None:
            return http.HttpResponseForbidden('请输入预收款单号')
        if CACC_NO is None:
            return http.HttpResponseForbidden('请输入银行代号')
        # //判断有没有输入银行账号
        try:
            sum_CACC_NO = et_CACC_NO(CACC_NO)
        except Exception:
            return http.HttpResponseForbidden('请检查银行账号是否存在或者是否输入正确')
        if sum_CACC_NO == 'NO':
            return http.HttpResponseForbidden('请检查银行账号是否存在或者是否输入正确')
            # 判断金额输入是否正确
        if re.compile('(^-?[0-9](\d+)?(\.\d{1,6})?$)|(^0$)|(^\d\.\d{1,2}$)').match(str(AMTN_BC)) is None:
            return http.HttpResponseForbidden('金额输入不正确')
        # 判断单号是否存在
        row_ZL_NO = examine_ood('TF_MON', 'RP_NO', RP_NO, 'RP_ID', '1')
        if row_ZL_NO > 0:
            return http.HttpResponseForbidden('预付款单号已存在')
        # 判断供应商是否哦存在，不存在的话创建
        try:
            row_cus_no = customer_data(CUS_NO, CUS_NO_NAME, '1', datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), 0)
        except Exception:
            return http.HttpResponseForbidden('创建客户失败')
        # 判断用户是否存在
        # row_usr = usr_data(USR, USR_NAME, datetime.datetime.strptime(PS_DD, '%Y-%m-%d'))
        try:
            # 判断用户是否存在，不存在则创建
            row_usr = usr_data(USR, USR_NAME, datetime.datetime.strptime(RP_DD, '%Y-%m-%d'))
        except Exception:
            return http.HttpResponseForbidden('创建用户失败')
        # 判断账号类别
        try:
            tp_CACC_NO = if_account(CACC_NO)
        except Exception:
            return http.HttpResponseForbidden("账户类型异常(现金)、（银行）")
        if tp_CACC_NO == 'NO':
            return http.HttpResponseForbidden('账户类型不存在(现金)、（银行）')
        with connection.cursor() as cursor:
            row_usr = 0
            try:
                if VOH_ID != 0:
                    row_usr = cursor.execute("SELECT COUNT(*) FROM MF_VHID WHERE VOH_ID=%s AND BIL_ID='RT'", [VOH_ID]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden('查询凭证模板异常')
            if row_usr <= 0:
                return http.HttpResponseForbidden('凭证模板在ERP里面不存在请重新输入凭证模板')
            # 获取银行账号的会计科目
            try:
                Acc_No_km = cursor.execute("""SELECT ISNULL(Acc_No,'') FROM BACC WHERE BACC_NO=%s""", [CACC_NO]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden("银行会计科目异常")
            if Acc_No_km == '':
                return http.HttpResponseForbidden('银行会计科目不存在')
            sid = transaction.savepoint()  # 开启事物
            try:
                # 银行账户
                if int(tp_CACC_NO) == 1:
                    print(11112222)
                    # 插入预收款表头
                    cursor.execute("""INSERT INTO TF_MON(IRP_ID,RP_NO,ITM,RP_ID,CLS_ID,RP_DD,CUS_NO,INCLUDESON,AMTN_BB,AMTN_CLS,BC_NO,BACC_NO,EXC_RTO,DEP,USR,CHK_MAN,CLS_DATE,SYS_DATE,IEA_ID,IOR_ID,SK_TYPE,VOH_ID,USR_NO)VALUES
                                   (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   [
                                       'T',
                                       RP_NO,
                                       1,
                                       1,
                                       'F',
                                       datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                       CUS_NO,
                                       'F',
                                       AMTN_BC,
                                       0,
                                       'BT' + RP_NO[2::],
                                       CACC_NO,
                                       1,
                                       DEP,
                                       USR,
                                       USR,
                                       datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                       datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                       'F',
                                       'F',
                                       1,
                                       VOH_ID,
                                       SAL_NO
                                   ])
                    print(2323)
                # 现金账户
                if int(tp_CACC_NO) == 2:
                    print(1122)
                    print(VOH_ID)
                    print(SAL_NO)
                    # 插入预收款表头
                    cursor.execute("""INSERT INTO TF_MON(IRP_ID,RP_NO,ITM,RP_ID,CLS_ID,RP_DD,CUS_NO,INCLUDESON,AMTN_BC,AMTN_CLS,BC_NO,CACC_NO,EXC_RTO,DEP,USR,CHK_MAN,CLS_DATE,SYS_DATE,IEA_ID,IOR_ID,SK_TYPE,VOH_ID,USR_NO)VALUES
                     (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                                   ['T',RP_NO,1,1,'F',datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), CUS_NO,'F',AMTN_BC,0,'BT' + RP_NO[2::],CACC_NO,1,'0000',USR,USR,datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                    datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),'F','F',1,VOH_ID,SAL_NO])
                print(1)
                # 插入语收款立账金额
                cursor.execute("""INSERT INTO MF_MON(RP_ID,RP_NO,RP_DD,DEP,AMTN,AMTN_ARP,AMTN_REST,FJ_NUM)VALUES
                               (%s,%s,%s,%s,%s,%s,%s,%s)""",
                               [1,
                                RP_NO,
                                datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                DEP,
                                AMTN_BC,
                                0,
                                0,
                                0])
                print(3)
                # 插入账户收支单表头
                cursor.execute("""INSERT INTO MF_BAC(BB_ID,BB_NO,BB_DD,BACC_NO,ACC_NO,DEP,BIL_NO,EXC_RTO,AMTN,USR,CHK_MAN,OPN_ID,CLS_DATE,SYS_DATE,BIL_ID_N,BIL_NO_N)VALUES
                                    (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                               ['BT',
                                'BT' + RP_NO[2::],
                                datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                CACC_NO,
                                Acc_No_km,
                                DEP,
                                'BT' + RP_NO,
                                1,
                                float(AMTN_BC),
                                USR,
                                USR,
                                'F',
                                datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                'RT',
                                RP_NO])
                print(4)
                # 插入收支单表身
                cursor.execute("""INSERT INTO TF_BAC(BB_ID,BB_NO,ITM,BB_DD,EXC_RTO,AMTN,DEP,CUS_NO,ADD_ID,PRE_ITM)values
                                    (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                               ['BT',
                                'BT' + RP_NO[2::],
                                1,
                                datetime.datetime.strptime(RP_DD, '%Y-%m-%d'),
                                1,
                                AMTN_BC,
                                DEP,
                                CUS_NO,
                                '+',
                                1 ])
            except Exception:
                transaction.savepoint_rollback(sid)
                return http.HttpResponseForbidden("预收款单新增sql语句执行异常")
            transaction.savepoint_commit(sid)
        context = {
            "message": '新增客户预付款单成功',
            "code": 200
        }
        return http.JsonResponse(context)

    @transaction.atomic
    def put(self, request):

        # 获取参数
        # 获取参数
        req_data = json.loads(request.body.decode())
        RP_NO = req_data.get("RP_NO")  # 预付款单号         字符类型   ->->->->->->->->1
        RP_DD = req_data.get("RP_DD")  # 预付款日期            字符类型  ->->->->->->->->->->1
        CUS_NO = req_data.get("CUS_NO")  # 预付款客户编码        字符类型  ->->->->->->->->->->->->-1
        CUS_NO_NAME = req_data.get("CUS_NO_NAME", '')  # 预付款客户名称       字符类型  ->->->->->->->->->->-1
        AMTN_BC = req_data.get("AMTN_BC")  # 预付款金额            数字类型  ->->->->->->->->->->->->->-1
        CACC_NO = req_data.get("CACC_NO")  # 预付款银行编码          字符类型    ->->->->->->1
        USR = req_data.get("USR")  # 制单人编码                   字符类型   ->->->->->->->->->1
        USR_NAME = req_data.get("USR_NAME", '')  # 制单人姓名         字符类型   ->->->->->->->->->->->-1
        DEP = req_data.get("DEP", '')  # 部门         字符类型   ->->->->->->->->->->->-1
        SAL_NO = req_data.get("SAL_NO", 0)  # 业务员         字符类型   ->->->->->->->->->->->-1
        VOH_ID = req_data.get("VOH_ID", 0)  # 凭证模板         字符类型   ->->->->->->->->->->->-1
        UP_DD = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # {
        #     "RP_DD": "2019-12-06",
        #     "CUS_NO": "AQ2222",
        #     "CUS_NO_NAME": "收款",
        #     "RP_NO": "RTF9C0201",
        #     "AMTN_BC": "100",
        #     "CACC_NO": "01",
        #     "VOH_ID": "01",
        #     "USR": "a00002",
        #     "USR_NAME": "楠楠",
        #     "DEP": "0000",
        #     "SAL_NO": "A00002",
        #     "user": "123",
        #     "password": "123"
        # }
        if RP_DD is None:
            return http.HttpResponseForbidden('请输入时间')
        if RP_NO[:3] != 'RTF' or len(RP_NO) !=11:
            return http.HttpResponseForbidden('预收款单号输入不合法，单号必须是RTF开头且长度必须是11位')
        # 校验日期格式
        try:
            datetime.datetime.strptime(RP_DD, '%Y-%m-%d')
        except Exception:
            return http.HttpResponseForbidden('日期格式输入不正确')
        if RP_NO is None:
            return http.HttpResponseForbidden('请输入预收款单号')
        if CACC_NO is None:
            return http.HttpResponseForbidden('请输入银行代号')
        # //判断有没有输入银行账号
        try:
            sum_CACC_NO = et_CACC_NO(CACC_NO)
        except Exception:
            return http.HttpResponseForbidden('请检查银行账号是否存在或者是否输入正确')
        if sum_CACC_NO == 'NO':
            return http.HttpResponseForbidden('请检查银行账号是否存在或者是否输入正确')
            # 判断金额输入是否正确
        if re.compile('(^-?[0-9](\d+)?(\.\d{1,6})?$)|(^0$)|(^\d\.\d{1,2}$)').match(str(AMTN_BC)) is None:
            return http.HttpResponseForbidden('金额输入不正确')
        # 判断单号是否存在
        try:
            row_ZL_NO = examine_ood('TF_MON', 'RP_NO', RP_NO, 'RP_ID', '1')
        except Exception:
            return http.HttpResponseForbidden('判断单号是否存在，单号查询异常')
        if row_ZL_NO <= 0:
            return http.HttpResponseForbidden('预付款单号不存在')

        # 判断单号是不是已经产生付款单
        try:
            row_ZL_NO = examine_ood('TF_MON1', 'IRP_NO', RP_NO, 'RP_ID', '1')
        except Exception:
            return http.HttpResponseForbidden('判断单号是否产生后续单据异常')
        if row_ZL_NO > 0:
            return http.HttpResponseForbidden('预付款单已经产生付款单')
        # 判断账号类别
        try:
            tp_CACC_NO = if_account(CACC_NO)
        except Exception:
            return http.HttpResponseForbidden("账户类型异常(现金)、（银行）")
        if tp_CACC_NO == 'NO':
            return http.HttpResponseForbidden('账户类型不存在(现金)、（银行）')
        # 判断供应商是否哦存在，不存在的话创建
        try:
            row_cus_no = customer_data(CUS_NO, CUS_NO_NAME, '1', datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), 0)
        except Exception:
            return http.HttpResponseForbidden('创建客户失败')

        with connection.cursor() as cursor:
            row_usr = 0
            try:
                if VOH_ID != 0:
                    row_usr = cursor.execute("SELECT COUNT(*) FROM MF_VHID WHERE VOH_ID=%s AND BIL_ID='RT'", [VOH_ID]).fetchall()[
                        0][0]
            except Exception:
                return http.HttpResponseForbidden('查询凭证模板异常')
            if row_usr <= 0:
                return http.HttpResponseForbidden('凭证模板在ERP里面不存在请重新输入凭证模板')
            # 获取银行账号的会计科目
            try:
                Acc_No_km = cursor.execute("""SELECT ISNULL(Acc_No,'') FROM BACC WHERE BACC_NO=%s""", [CACC_NO]).fetchall()[0][0]
            except Exception:
                return http.HttpResponseForbidden("银行会计科目异常")
            if Acc_No_km == '':
                return http.HttpResponseForbidden('银行会计科目不存在')
            sid = transaction.savepoint()  # 开启事物
            try:
                # 银行账户
                if int(tp_CACC_NO) == 1:
                    # 修改预付款单
                    print(11111)
                    cursor.execute(
                        """UPDATE TF_MON SET RP_DD=%s,CUS_NO=%s,AMTN_BB=%s,BC_NO=%s,BACC_NO=%s,MODIFY_DD=%s,MODIFY_MAN=%s,VOH_ID=%s,USR_NO=%s,AMTN_BC=NULL,CACC_NO='' WHERE RP_NO=%s""",
                        [datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), CUS_NO, AMTN_BC, 'BT' + RP_NO[2::], CACC_NO,
                         UP_DD,USR,VOH_ID,SAL_NO, RP_NO])
                # 现金账户
                if int(tp_CACC_NO) == 2:
                    print(11222)
                    # 修改预付款单
                    cursor.execute(
                        """UPDATE TF_MON SET RP_DD=%s,CUS_NO=%s,AMTN_BC=%s,BC_NO=%s,CACC_NO=%s,MODIFY_DD=%s,MODIFY_MAN=%s ,VOH_ID=%s,USR_NO=%s,AMTN_BB=NULL,BACC_NO='' WHERE RP_NO=%s""",
                        [datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), CUS_NO, AMTN_BC, 'BT' + RP_NO[2::], CACC_NO,
                         UP_DD,USR,VOH_ID,SAL_NO, RP_NO])
                # 修改立账单金额
                print(2)
                cursor.execute("""UPDATE MF_MON SET RP_DD=%s,AMTN=%s WHERE RP_NO=%s""",
                               [datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), AMTN_BC, RP_NO])
                print(3)
                # 修改账户收支单表头
                cursor.execute("""UPDATE MF_BAC SET BB_DD=%s,BACC_NO=%s,ACC_NO=%s,BIL_NO=%s,AMTN=%s,DEP=%s WHERE BB_NO=%s""",
                               [datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), CACC_NO, Acc_No_km, 'BT' + RP_NO,
                                float(AMTN_BC),DEP, 'BT' + RP_NO[2::]])
                print(4)
                # 修改账户收支单表身
                cursor.execute("""UPDATE TF_BAC SET BB_DD=%s,AMTN=%s,CUS_NO=%s WHERE BB_NO=%s""",
                               [datetime.datetime.strptime(RP_DD, '%Y-%m-%d'), AMTN_BC, CUS_NO, 'BT' + RP_NO[2::]])
            except Exception:
                transaction.savepoint_rollback(sid)
                return http.HttpResponseForbidden("预收款单修改sql语句执行异常")
            transaction.savepoint_commit(sid)
        context = {
            "message": '修改客户预付款单成功',
            "code": 200
        }
        return http.JsonResponse(context)

    @transaction.atomic
    def delete(self, request):
        # 获取参数
        req_data = json.loads(request.body.decode())
        RP_NO = req_data.get("RP_NO")  # 预付款单号
        # {
        #     "RP_NO": "RTX9A300003"
        # }
        # 判断单号的合法性
        if RP_NO[:3] != 'RTF' or len(RP_NO) != 11:
            return http.HttpResponseForbidden('预收款单号输入不合法，单号必须是RTF开头且长度必须为11位')
        if RP_NO is None:
            return http.HttpResponseForbidden('请输入预收款单号')
        # 判断单号是不是已经产生付款单
        try:
            row_ZL_NO = examine_ood('TF_MON1', 'IRP_NO', RP_NO, 'RP_ID', '1')
        except Exception:
            return http.HttpResponseForbidden('判断单号是否产生后续单据异常')
        if row_ZL_NO > 0:
            return http.HttpResponseForbidden('预付款单已经产生付款单')
        # 判断单号是否存在
        row_ZL_NO = examine_ood('TF_MON', 'RP_NO', RP_NO, 'RP_ID', '1')
        if row_ZL_NO == 0:
            return http.HttpResponseForbidden('预付款单号不存在')
        with connection.cursor() as cursor:
            sid = transaction.savepoint()  # 开启事物
            try:
                # 删除付款单
                cursor.execute("""DELETE FROM TF_MON WHERE RP_NO=%s AND RP_ID='1'""", [RP_NO])
                # 删除金额立账单
                cursor.execute("""DELETE FROM MF_MON WHERE RP_NO=%s  AND RP_ID='1'""", [RP_NO])
                # 删除账户收支单表头
                cursor.execute("""DELETE FROM MF_BAC WHERE BB_NO=%s""", ['BT' + RP_NO[2::]])
                # 删除账户收支单表身
                cursor.execute("""DELETE FROM TF_BAC WHERE BB_NO=%s""", ['BT' + RP_NO[2::]])
            except Exception:
                transaction.savepoint_rollback(sid)
                return http.HttpResponseForbidden("预收款单删除sql语句执行异常")
            transaction.savepoint_commit(sid)
        context = {
            "message": '删除客户预付款单成功',
            "code": 200
        }
        return http.JsonResponse(context)

#回传进货票
class PcInvoice(View):
    def post(self, request):
        with connection.cursor() as cursor:
            # 判断表是否存在
            is_table=cursor.execute("""SELECT table_name FROM information_schema.TABLES WHERE table_name ='MF_LZ1_Z01'""", []).fetchall()
            if len(is_table)==0:
                return http.HttpResponseForbidden("MF_LZ1_Z01,此表不存在请先创建此表")
            #判断表中是否存在数据
            pc_count=cursor.execute("""SELECT COUNT(*) FROM MF_LZ1_Z01""", []).fetchall()[0][0]
            if pc_count==0:
                return http.HttpResponseForbidden("表数据为空请先增加数据")
            #查询未被拉取的数据
            pc_date = cursor.execute("""SELECT ISNULL(A_LZ_DD,'') AS A_LZ_DD,ISNULL(A_CUS_NO ,'') AS A_CUS_NO,ISNULL(C_NAME,'') AS C_NAME,ISNULL(A_LZ_NO,'') AS A_LZ_NO,ISNULL(A_INV_NO,'') AS A_INV_NO,
                                    ISNULL(A_AMT,0) AS A_AMT,ISNULL(A_AMTN_NET,0) AS A_AMTN_NET,ISNULL(A_TAX,0) AS A_TAX,ISNULL(A_TAX_ID,'') AS A_TAX_ID,ISNULL(A_ZHANG_ID,'') AS A_ZHANG_ID,
                                    ISNULL(B_PS_NO,'') AS B_PS_NO,ISNULL(B_QTY,0) AS B_QTY,ISNULL(B_UP,0) AS B_UP,ISNULL(B_AMT,0) AS B_AMT,ISNULL(B_TAX_RTO,0) AS B_TAX_RTO,OK FROM MF_LZ1_Z01 WHERE OK ='N'""", []).fetchall()
            # print(pc_date)
            # print(len(pc_date))
            if len(pc_date)==0:
                return http.HttpResponseForbidden("没有需要拉取的数据")
            data=[]
            LZ_NO=[]
            for i in pc_date:
                # print(1111)
                LZ_NO.append(i[3])
                # data.append({"A_LZ_DD": i[0], "A_CUS_NO": i[1]})
                data.append({"A_LZ_DD":str(i[0]),"A_CUS_NO":i[1],"C_NAME":i[2],"A_LZ_NO":i[3],
                "A_INV_NO":i[4],"A_AMT":float(i[5]),"A_AMTN_NET":float(i[6]),"A_TAX":float(i[7]),"A_TAX_ID":i[8],
                "A_ZHANG_ID":i[9],"B_PS_NO":i[10],"B_QTY":float(i[11]),"B_UP":float(i[12]),"B_AMT":float(i[13]),"B_TAX_RTO":float(i[14]),"OK":i[15].strip()})
            for i in LZ_NO:
                cursor.execute("""UPDATE MF_LZ1_Z01 SET OK='Y' WHERE A_LZ_NO=%s""", [i])
        context = {
            "data":data,
            "message": "进货开票数据回传app成功",
            "code":200
        }
        return http.JsonResponse(context)

#回传销货票
class SaInvoice(View):
    def post(self, request):
        with connection.cursor() as cursor:
            # 判断表是否存在
            is_table=cursor.execute("""SELECT table_name FROM information_schema.TABLES WHERE table_name ='MF_LZ_Z01'""", []).fetchall()
            if len(is_table)==0:
                return http.HttpResponseForbidden("MF_LZ1_Z01,此表不存在请先创建此表")
            #判断表中是否存在数据
            sa_count=cursor.execute("""SELECT COUNT(*) FROM MF_LZ_Z01""", []).fetchall()[0][0]
            if sa_count==0:
                return http.HttpResponseForbidden("表数据为空请先增加数据")
                # 查询未被拉取的数据
            sa_date = cursor.execute("""SELECT ISNULL(A_LZ_DD,'') AS A_LZ_DD,ISNULL(A_CUS_NO,'') AS A_CUS_NO,ISNULL(C_NAME,'') AS C_NAME,ISNULL(A_LZ_NO,'') AS A_LZ_NO,ISNULL(A_INV_NO,'') AS A_INV_NO,
                                    ISNULL(A_AMT,0) AS A_AMT,ISNULL(A_AMTN_NET,0) AS A_AMTN_NET,ISNULL(A_TAX,0) AS A_TAX,ISNULL(A_TAX_ID,'') AS A_TAX_ID,ISNULL(A_ZHANG_ID,'') AS A_ZHANG_ID,
                                    ISNULL(B_CK_NO,'') AS B_CK_NO,ISNULL(B_QTY,0) AS B_QTY,ISNULL(B_UP,0) AS B_UP,ISNULL(B_AMT,0) AS B_AMT,ISNULL(B_TAX_RTO,0) AS B_TAX_RTO,OK FROM MF_LZ_Z01 WHERE OK ='N'""",[]).fetchall()
            if len(sa_date)==0:
                return http.HttpResponseForbidden("没有需要拉取的数据")
            data = []
            LZ_NO = []
            for i in sa_date:
                # print(1111)
                LZ_NO.append(i[3])
                # data.append({"A_LZ_DD": i[0], "A_CUS_NO": i[1]})
                data.append({"A_LZ_DD": str(i[0]), "A_CUS_NO": i[1], "C_NAME": i[2], "A_LZ_NO": i[3],
                             "A_INV_NO": i[4], "A_AMT": float(i[5]), "A_AMTN_NET": float(i[6]), "A_TAX": float(i[7]),
                             "A_TAX_ID": i[8],"A_ZHANG_ID": i[9], "B_CK_NO": i[10], "B_QTY": float(i[11]), "B_UP": float(i[12]),
                             "B_AMT": float(i[13]), "B_TAX_RTO": float(i[14]), "OK": i[15].strip()})
            for i in LZ_NO:
                cursor.execute("""UPDATE MF_LZ_Z01 SET OK='Y' WHERE A_LZ_NO=%s""", [i])
            context = {
                "data": data,
                "message": "销货开票数据回传app成功",
                "code": 200
            }
            return http.JsonResponse(context)

#客户预收冲应收
# SELECT ISNULL(C_CUS_NO,'') AS C_CUS_NO,ISNULL(D_NAME,'') AS D_NAME,ISNULL(C_RP_DD,'') AS C_RP_DD,
# ISNULL(C_RP_NO,'') AS C_RP_NO,ISNULL(B_BIL_NO,'') AS B_BIL_NO,ISNULL(A_AMTN_CLS,0)AS A_AMTN_CLS,
# ISNULL(OK,'') AS OK,ISNULL(IRP_NO,'') AS IRP_NO,ISNULL(AMTN_IRP,0) AS AMTN_IRP,ISNULL(B_BIL_ID,'') AS B_BIL_ID
#  FROM TC_MON_PC WHERE C_RP_ID=1 AND ISNULL(IRP_NO,'')<>''
class yrt(View):
    def post(self, request):
        with connection.cursor() as cursor:
            # 判断表是否存在
            is_table=cursor.execute("""SELECT table_name FROM information_schema.TABLES WHERE table_name ='TC_MON_PC'""", []).fetchall()
            if len(is_table)==0:
                return http.HttpResponseForbidden("TC_MON_PC,此表不存在请先创建此表")
            #判断表中是否存在数据
            sa_count=cursor.execute("""SELECT COUNT(*) FROM TC_MON_PC""", []).fetchall()[0][0]
            if sa_count==0:
                return http.HttpResponseForbidden("表数据为空请先增加数据")
                # 查询未被拉取的数据
            sa_date = cursor.execute("""SELECT ISNULL(C_CUS_NO,'') AS C_CUS_NO,ISNULL(D_NAME,'') AS D_NAME,ISNULL(C_RP_DD,'') AS C_RP_DD,
                                    ISNULL(C_RP_NO,'') AS C_RP_NO,ISNULL(B_BIL_NO,'') AS B_BIL_NO,ISNULL(A_AMTN_CLS,0)AS A_AMTN_CLS,
                                    ISNULL(OK,'') AS OK,ISNULL(IRP_NO,'') AS IRP_NO,ISNULL(AMTN_IRP,0) AS AMTN_IRP,ISNULL(B_BIL_ID,'') AS B_BIL_ID
                                    FROM TC_MON_PC WHERE C_RP_ID=1 AND ISNULL(IRP_NO,'')<>'' AND OK='N'""",[]).fetchall()
            if len(sa_date)==0:
                return http.HttpResponseForbidden("没有需要拉取的数据")
            data = []
            RT_NO = []
            for i in sa_date:
                # print(1111)
                RT_NO.append(i[3])
                data.append({"C_CUS_NO": i[0], "D_NAME": i[1], "C_RP_DD": i[2], "C_RP_NO": str(i[3]),
                             "B_BIL_NO": i[4], "A_AMTN_CLS": i[5], "OK": i[6], "IRP_NO": i[7].strip(),
                             "AMTN_IRP": i[8], "B_BIL_ID": i[9]})
            for i in RT_NO:
                cursor.execute("""UPDATE TC_MON_PC SET OK='Y' WHERE C_RP_NO=%s""", [i])
            context = {
                "data": data,
                "message": "客户预收冲应收数据回传app成功",
                "code": 200
            }
            return http.JsonResponse(context)
#客户收款单
# SELECT ISNULL(C_CUS_NO,'') AS C_CUS_NO,ISNULL(D_NAME,'') AS D_NAME,ISNULL(C_RP_DD,'') AS C_RP_DD,
# ISNULL(C_CACC_NO,'') AS C_CACC_NO,ISNULL(C_AMTN_BC,0) AS C_AMTN_BC,ISNULL(C_RP_NO,'') AS C_RP_NO,
# ISNULL(B_BIL_NO,'') AS B_BIL_NO,ISNULL(B_BIL_ID,'') AS B_BIL_ID,ISNULL(A_AMTN_CLS,0)AS A_AMTN_CLS,
# ISNULL(OK,'') AS OK
#  FROM TC_MON_PC WHERE C_RP_ID=1 AND ISNULL(B_BIL_ID,'')<>'' AND ISNULL(IRP_NO,'')=''
class rt(View):
    def post(self, request):
        with connection.cursor() as cursor:
            # 判断表是否存在
            is_table=cursor.execute("""SELECT table_name FROM information_schema.TABLES WHERE table_name ='TC_MON_PC'""", []).fetchall()
            if len(is_table)==0:
                return http.HttpResponseForbidden("TC_MON_PC,此表不存在请先创建此表")
            #判断表中是否存在数据
            sa_count=cursor.execute("""SELECT COUNT(*) FROM TC_MON_PC""", []).fetchall()[0][0]
            if sa_count==0:
                return http.HttpResponseForbidden("表数据为空请先增加数据")
                # 查询未被拉取的数据
            sa_date = cursor.execute("""SELECT ISNULL(C_CUS_NO,'') AS C_CUS_NO,ISNULL(D_NAME,'') AS D_NAME,ISNULL(C_RP_DD,'') AS C_RP_DD,
            ISNULL(C_CACC_NO,'') AS C_CACC_NO,ISNULL(C_AMTN_BC,0) AS C_AMTN_BC,ISNULL(C_RP_NO,'') AS C_RP_NO,
            ISNULL(B_BIL_NO,'') AS B_BIL_NO,ISNULL(B_BIL_ID,'') AS B_BIL_ID,ISNULL(A_AMTN_CLS,0)AS A_AMTN_CLS,
            ISNULL(OK,'') AS OK FROM TC_MON_PC WHERE C_RP_ID=1 AND ISNULL(B_BIL_ID,'')<>'' AND ISNULL(IRP_NO,'')='' AND OK='N'""",[]).fetchall()
            if len(sa_date) == 0:
                return http.HttpResponseForbidden("没有需要拉取的数据")
            data = []
            RT_NO = []
            for i in sa_date:
                # print(1111)
                RT_NO.append(i[5])
                data.append({"C_CUS_NO": i[0], "D_NAME": i[1], "C_RP_DD": i[2], "C_CACC_NO": str(i[3]),
                             "C_AMTN_BC": float(i[4]), "C_RP_NO": i[5], "B_BIL_NO": i[6], "B_BIL_ID": i[7].strip(),
                             "A_AMTN_CLS": float(i[8]), "OK": i[9]})
            for i in RT_NO:
                cursor.execute("""UPDATE TC_MON_PC SET OK='Y' WHERE C_RP_NO=%s""", [i])
            context = {
                "data": data,
                "message": "客户收款单数据回传app成功",
                "code": 200
            }
            return http.JsonResponse(context)
# 厂商付款单
# SELECT ISNULL(C_CUS_NO,'') AS C_CUS_NO,ISNULL(D_NAME,'') AS D_NAME,ISNULL(C_RP_DD,'') AS C_RP_DD,
# ISNULL(C_CACC_NO,'') AS C_CACC_NO,ISNULL(C_AMTN_BC,0) AS C_AMTN_BC,ISNULL(C_RP_NO,'') AS C_RP_NO,
# ISNULL(B_BIL_NO,'') AS B_BIL_NO,ISNULL(B_BIL_ID,'') AS B_BIL_ID,ISNULL(A_AMTN_CLS,0)AS A_AMTN_CLS,
# ISNULL(OK,'') AS OK
#  FROM TC_MON_PC WHERE C_RP_ID=2 AND ISNULL(B_BIL_ID,'')<>'' AND ISNULL(IRP_NO,'')=''
class pt(View):
    def post(self, request):
        with connection.cursor() as cursor:
            # 判断表是否存在
            is_table=cursor.execute("""SELECT table_name FROM information_schema.TABLES WHERE table_name ='TC_MON_PC'""", []).fetchall()
            if len(is_table)==0:
                return http.HttpResponseForbidden("TC_MON_PC,此表不存在请先创建此表")
            #判断表中是否存在数据
            sa_count=cursor.execute("""SELECT COUNT(*) FROM TC_MON_PC""", []).fetchall()[0][0]
            if sa_count==0:
                return http.HttpResponseForbidden("表数据为空请先增加数据")
                # 查询未被拉取的数据
            sa_date = cursor.execute("""SELECT ISNULL(C_CUS_NO,'') AS C_CUS_NO,ISNULL(D_NAME,'') AS D_NAME,ISNULL(C_RP_DD,'') AS C_RP_DD,
                                    ISNULL(C_CACC_NO,'') AS C_CACC_NO,ISNULL(C_AMTN_BC,0) AS C_AMTN_BC,ISNULL(C_RP_NO,'') AS C_RP_NO,
                                    ISNULL(B_BIL_NO,'') AS B_BIL_NO,ISNULL(B_BIL_ID,'') AS B_BIL_ID,ISNULL(A_AMTN_CLS,0)AS A_AMTN_CLS,
                                    ISNULL(OK,'') AS OK FROM TC_MON_PC WHERE C_RP_ID=2 AND ISNULL(B_BIL_ID,'')<>'' AND ISNULL(IRP_NO,'')='' AND OK='N'""",[]).fetchall()
            if len(sa_date) == 0:
                return http.HttpResponseForbidden("没有需要拉取的数据")
            data = []
            RT_NO = []
            for i in sa_date:
                # print(1111)
                RT_NO.append(i[5])
                data.append({"C_CUS_NO": i[0], "D_NAME": i[1], "C_RP_DD": i[2], "C_CACC_NO": str(i[3]),
                             "C_AMTN_BC": float(i[4]), "C_RP_NO": i[5], "B_BIL_NO": i[6], "B_BIL_ID": i[7].strip(),
                             "A_AMTN_CLS": float(i[8]), "OK": i[9]})
            for i in RT_NO:
                cursor.execute("""UPDATE TC_MON_PC SET OK='Y' WHERE C_RP_NO=%s""", [i])
            context = {
                "data": data,
                "message": "客户收款单数据回传app成功",
                "code": 200
            }
            return http.JsonResponse(context)

# 获取部门数据
class dept(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection =sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' DEP LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + '[NAME] LIKE ' + "'" + '%%' + search_no + '%%' + "'"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT DEP,NAME FROM DEPT WHERE {0}""".format(search_no)
        else:
            sql = """SELECT top 100 DEP, NAME FROM DEPT """
        data = []
        result = executeQuery(sql)
        # print(result)
        if len(result) != 0:
            for i in result:
                data.append({"id": i["DEP"].replace(" ", ""), "text": i["DEP"] + '->' + i["NAME"].replace(" ", "")})
        context = {
            "data": data,
            "message": "获取部门成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 获取货品资料
class Prdt(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' PRD_NO LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + '[NAME] LIKE ' + "'" + '%%' + search_no + '%%' + "'"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT PRD_NO,NAME FROM PRDT WHERE {0}""".format(search_no)
        else:
            sql = """SELECT top 100 PRD_NO,NAME FROM PRDT """
        data = []
        # print(sql)
        with connection.cursor() as cursor:
            try:
                dep_data = cursor.execute(sql, []).fetchall()
            except Exception:
                context = {
                    "data": data,
                    "message": "没有获取到数据",
                    "code": 510
                }
                return http.JsonResponse(context)
        if len(dep_data) != 0:
            for i in dep_data:
                data.append({"id": i[0].replace(" ", ""), "text": i[0].replace(" ", "") + '->' + i[1]})
        # print(data)
        context = {
            "data": data,
            "message": "获取货品成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 获取客户信息
class Cust(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' CUS_NO LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + '[NAME] LIKE ' + "'" + '%%' + search_no + '%%' + "'"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT  CUS_NO,NAME FROM CUST WHERE {0}""".format(search_no)
        else:
            sql = """SELECT top 100 CUS_NO,NAME FROM CUST """
        data = []
        # print(sql)
        with connection.cursor() as cursor:
            try:
                dep_data = cursor.execute(sql, []).fetchall()
            except Exception:
                context = {
                    "data": data,
                    "message": "没有获取到数据",
                    "code": 510
                }
                return http.JsonResponse(context)
        if len(dep_data) != 0:
            for i in dep_data:
                data.append({"id": i[0].replace(" ", ""), "text": i[0].replace(" ", "") + '->' + i[1]})
        # print(data)
        context = {
            "data": data,
            "message": "获取部门成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 获取BOM信息
class Bom(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' BOM_NO LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + '[NAME] LIKE ' + "'" + '%%' + search_no + '%%' + "'"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT BOM_NO,NAME FROM MF_BOM WHERE {0}""".format(search_no)
        else:
            sql = """SELECT top 100 BOM_NO,NAME FROM MF_BOM """
        data = []
        # print(sql)
        with connection.cursor() as cursor:
            try:
                dep_data = cursor.execute(sql, []).fetchall()
            except Exception:
                context = {
                    "data": data,
                    "message": "没有获取到数据",
                    "code": 510
                }
                return http.JsonResponse(context)
        if len(dep_data) != 0:
            for i in dep_data:
                data.append({"id": i[0].replace(" ", ""), "text": i[0].replace(" ", "") + '->' + i[1]})
        # print(data)
        context = {
            "data": data,
            "message": "BOM配方成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 查询缴库单号
class MfmmooddNo(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' A.MM_NO LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + 'B.NAME LIKE ' + "'" + '%%' + search_no + '%%' + "'"+"ORDER BY A.MM_NO DESC"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT A.MM_NO AS MM_NO,B.NAME AS NAME FROM MF_MM0 A,DEPT B WHERE A.DEP=B.DEP AND {0}""".format(search_no)
        else:
            sql = """SELECT TOP 20 A.MM_NO AS MM_NO,B.NAME AS NAME FROM MF_MM0 A,DEPT B WHERE A.DEP=B.DEP ORDER BY A.MM_NO DESC"""
        # print(sql)
        data = []
        result = executeQuery(sql)
        # print(result)
        if len(result) != 0:
            for i in result:
                data.append({"id": i["MM_NO"], "text": i["MM_NO"] + '->' + i["NAME"]})
        # print(data)
        context = {
            "data": data,
            "message": "获取缴库单号成功",
            "code": 200
        }
        return http.JsonResponse(context)

# 查询IE工艺文件号
class IeFileNo(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' iefile_no LIKE' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + 'file_serial LIKE ' + "'" + '%%' + search_no + '%%' + "'" + "ORDER BY iefile_no DESC"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """select iefile_no,file_serial from MF_IEFILE WHERE {0}""".format(
                search_no)
        else:
            sql = """select iefile_no,file_serial from MF_IEFILE ORDER BY iefile_no DESC"""
        print(sql)
        data = []
        result = executeQuery(sql)
        # print(result)
        if len(result) != 0:
            for i in result:
                data.append({"id": i["iefile_no"], "text": i["iefile_no"] + '->' + i["file_serial"]})
        # print(data)
        context = {
            "data": data,
            "message": "获取缴库单号成功",
            "code": 200
        }
        return http.JsonResponse(context)


# 查询单号
class oddNo(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if search_no != '':
            search_no = ' NO LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + 'DEP_NAME LIKE ' + "'" + '%%' + search_no + '%%' + "'"+"ORDER BY NO DESC"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT NO,DEP_NAME FROM MCAF WHERE {0}""".format(search_no)
        else:
            sql = """SELECT top 20 NO, DEP_NAME FROM MCAF ORDER BY NO DESC"""
        # print(sql)
        data = []
        result = executeQuery(sql)
        # print(result)
        if len(result) != 0:
            for i in result:
                data.append({"id": i["NO"], "text": i["NO"] + '->' + i["DEP_NAME"]})
        # print(data)
        context = {
            "data": data,
            "message": "获取单号成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 渲染order.html模板数据订单一览表
class index(View):
    def get(self, request):
        return render(request, 'order.html')
# 订单一览表数据接口
class listtb(View):
    def get(self, request):
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        st_time = request.GET["st_time"]  # 开始时间
        sh_time = request.GET['sh_time']
        cus_no = request.GET['cus_no'].split('->')[0]#客户编码->这里需要进行切割，因为传过来的是编码+名称（’编码->名称‘）
        cls_id = request.GET['cls_id']
        PMC_REM = request.GET['pmc_ok']
        sort = request.GET['sort']
        business_time = request.GET['business_time']  #业务交期
        prd_no = request.GET['prd_no'].split('->')[0] #货品编码->这里需要进行切割，因为传过来的是编码+名称（’编码->名称‘）
        sc_dep = request.GET['sc_dep'].split('->')[0]  #生产部门
        # print(sc_dep)
        ym_type = request.GET['ym_type']  #研磨类型
        os_type = request.GET['os_type']  #订单类型
        capacity = request.GET['capacity']  #容量
        vessel = request.GET['vessel']  #容器
        select = request.GET['select']  #用于判断是否查询
        ifmerge = request.GET['ifmerge']#是否合并
        # print(ifmerge)
        th_time = datetime.datetime.now().strftime('%Y-%m')  # 获取年月
        t_today = datetime.datetime.now().strftime('%Y-%m-%d')  # 获取年月日
        page_size = settings.PAGE_SIZE #每页记录数
        page = int(request.GET['page'])-1  #页码
        total_page = 0 #总页数
        total_count = 0  #总记录数
        # print(page)
        # 处理客户代号
        if len(cus_no)>0:
            cus_no = ' AND '+ 'CUS_NO='+"'"+cus_no+"'"
        # 处理结案否
        if cls_id:
            if cls_id =='1':
                cls_id = ''
            elif cls_id == '2':
                cls_id = 'T'
                cls_id = ' AND '+ 'A.CLS_ID ='+"'"+cls_id+"'"
            else:
                cls_id = ' AND ' + 'A.CLS_ID !=' + "'" + 'T' + "'"
        # 处理是否回复
        if PMC_REM:
            if PMC_REM =='1':
                PMC_REM = ''
            elif PMC_REM == '2':
                PMC_REM = ' AND '+ "ISNULL(C.PMC_REM,'') != ''"
            else:
                PMC_REM = ' AND ' + "ISNULL(C.PMC_REM,'') = ''"
        # 处理业务交期
        if business_time !='':
            business_time = ' AND '+ 'EST_DD='+"'"+business_time+"'"
        # 处理货品编码
        if prd_no != '':
            prd_no = ' AND ' + 'PRD_NO=' + "'" + prd_no + "'"
        # 处理部门============================================================
        if sc_dep != '':
            sc_dep = ' AND ' + 'DEP=' + "'" + sc_dep + "'"
        # 处理研磨类型
        # if ym_type !='':
        #     ym_type = ' AND ' + 'B.PRD_NO=' + "'" + ym_type + "'"
        # 订单类型
        if os_type == '1':
            os_type=''
        if os_type == '2':
            os_type = ' AND ' + "ORDER0 LIKE '%%订单%%'"
        if os_type == '3':
            os_type = ' AND ' + "ORDER0 LIKE '%%返工%%'"
        # 处理容量
        if capacity != '':
            capacity = ' AND ' + 'DZRL=' + "'" + capacity + "'"
        # # 处理容器
        # if vessel != '':
        #     vessel = ' AND ' + 'B.PRD_NO=' + "'" + vessel + "'"
        if select=='2':
            conditional = ' left(Convert(varchar(100), OS_DD, 23), 7) >=' + "'" + th_time + "'"
        else:
            conditional = ' left(Convert(varchar(100), OS_DD, 23), 11) >=' + "'" + st_time + "'" + ' AND ' + 'left(Convert(varchar(100), OS_DD, 23), 11) <=' + "'" + sh_time + "'" + cus_no + cls_id + PMC_REM +\
                         business_time + prd_no + sc_dep + os_type + capacity
            # 定义sql语句
        # 这里是不合并的处理
        data = [
                    {"ORDER0": "类别", "OS_DD": '下单日期', "CUS_SNM": "客户名称",
                     "OS_NO":"计划单号","PRD_NO":"产品编码","DZRL":"容量（ML）",
                     "QY":"容器","YSSL":"套装颜色数","YMXH":"研磨品类型",
                     "QTY":"订单数量","GZSL":"灌装支数量","EST_DD":"业务交期",
                     "PD_DEP":"生产部门","REM":"备注","PMC_DD":"PMC回复交期","WH_REM":"大货备注",
                     "operation":"操作","ITM":"项次"},
                ]
        if ifmerge=='1':
            # 排序规则
            if sort:
                # F.SPC_NO
                if sort == '1':
                    sort = ' ORDER BY OS_NO,OS_NO+Convert(varchar(100), ITM, 23) DESC'
                    sort_if = '1'
                if sort == '2':
                    sort = ' ORDER BY SPC_NO,OS_NO+Convert(varchar(100), ITM, 23) DESC'
                if sort == '3':
                    sort = ' ORDER BY CUS_NO,OS_NO+Convert(varchar(100), ITM, 23) DESC'
                if sort == '4':
                    sort = ' ORDER BY PMC_DD,OS_NO+Convert(varchar(100), ITM, 23) DESC'
                else:
                    sort = ' ORDER BY OS_NO,OS_NO+Convert(varchar(100), ITM, 23) DESC'
            # conditional  where条件
            # 排序 sort
            sql_count = ("""SELECT COUNT(OS_NO) AS total FROM View_aa WHERE {0}""".format(conditional))
            print(sql_count)
            result = executeQuery(sql_count)
            if len(result) == 0 or result[0]["total"]==0:
                context = {
                    "data": data,
                    "total_page": 0,
                    "total_count": 0,
                    "message": "没有获取到数据",
                    "code": 510
                }
                return http.JsonResponse(context)
            total_count = result[0]["total"]   #总记录数
            total_page = math.ceil(result[0]["total"]/page_size)  #计算总页数,总记录数除以每页记录数
            print(total_page)
            sql = """SELECT TOP {0}
    ORDER0 AS ORDER0 ,ISNULL(OS_DD,'') AS OS_DD,
    ISNULL(CUS_SNM,'') AS CUS_SNM,OS_NO AS OS_NO,PRD_NO AS PRD_NO,ISNULL(DZRL,'') AS DZRL,'' AS RQ,ISNULL(YSSL,'') AS YSSL,'' AS YMXH,
    ISNULL(QTY,0) AS QTY,ISNULL(GZSL,0) AS GZSL,left(Convert(varchar(100), EST_DD, 23), 11) AS EST_DD,PD_DEP AS PD_DEP,ISNULL(REM,'') AS REM,PMC_DD AS PMC_DD,WH_REM AS WH_REM,
     ITM AS ITM,SPC_NO,CUS_NO,PMC_REM
     FROM View_aa WHERE {1} AND OS_NO+PRD_NO+Convert(varchar(100), ITM, 23) NOT IN(SELECT TOP {2} OS_NO+PRD_NO+Convert(varchar(100), ITM, 23) FROM View_aa WHERE {3} {4}) {5}""".\
    format(page_size,conditional,page_size*page,conditional,sort,sort)
        # 这里是合并处理
        else:
            # 排序规则
            if sort:
                # F.SPC_NO
                if sort == '1':
                    sort = ' ORDER BY OS_NO,OS_NO+PRD_NO DESC'
                    sort_if = '1'
                if sort == '2':
                    sort = ' ORDER BY SPC_NO,OOS_NO+PRD_NO DESC'
                if sort == '3':
                    sort = ' ORDER BY CUS_NO,OS_NO+PRD_NO DESC'
                if sort == '4':
                    sort = ' ORDER BY PMC_DD,OS_NO+PRD_NO DESC'
                else:
                    sort = ' ORDER BY OS_NO,OS_NO+PRD_NO DESC'
            # =这里需要加分组gurup_by  然后加 sort
            # conditional  条件
            # gurup_by   分组
            # sort  排序
            gurup_by =  ' GROUP BY OS_NO,PRD_NO,OS_DD,PMC_DD,ORDER0,CUS_SNM,DZRL,RQ,PD_DEP,REM '
            conditional = ' left(Convert(varchar(100), OS_DD, 23), 11) >=' + "'" + st_time + "'" + ' AND ' + 'left(Convert(varchar(100), OS_DD, 23), 11) <=' + "'" + sh_time + "'" + cus_no + cls_id + PMC_REM + \
                          business_time + prd_no + sc_dep + os_type + capacity
            sql_count = ("""SELECT COUNT(OS_NO) AS total FROM (SELECT OS_NO FROM View_aa WHERE {0} {1}) A""".format(conditional,gurup_by))
            # sql_count = ("""SELECT COUNT(OS_NO) AS total FROM View_aa WHERE {0} {1}""".format(conditional,gurup_by))
            print(sql_count)
            result = executeQuery(sql_count)
            if len(result) == 0 or result[0]["total"]==0:
                context = {
                    "data": data,
                    "total_page": 0,
                    "total_count": 0,
                    "message": "没有获取到数据",
                    "code": 510
                }
                return http.JsonResponse(context)
            total_count = result[0]["total"]  # 总记录数
            print(total_count)
            total_page = math.ceil(result[0]["total"] / page_size)  # 计算总页数,总记录数除以每页记录数
            print(total_page)
            sql = """SELECT TOP {0} ORDER0 AS ORDER0 ,ISNULL(OS_DD,'') AS OS_DD,
ISNULL(CUS_SNM,'') AS CUS_SNM,OS_NO AS OS_NO,PRD_NO AS PRD_NO,ISNULL(DZRL,'') AS DZRL,'' AS RQ,SUM(ISNULL(YSSL,0)) AS YSSL,'' AS YMXH,
SUM(ISNULL(QTY,0)) AS QTY,SUM(ISNULL(GZSL,0)) AS GZSL,
stuff((SELECT ';' + replace(CONVERT(CHAR(19), left(Convert(varchar(100), B.EST_DD, 23), 11), 120),' ','') FROM View_aa B WHERE A.OS_NO=B.OS_NO AND B.PRD_NO=A.PRD_NO FOR xml path('')),1,1,'')AS EST_DD
,PD_DEP AS PD_DEP,ISNULL(REM,'') AS REM,PMC_DD AS PMC_DD,
stuff((SELECT ';' + CAST(B.WH_REM AS VARCHAR(500)) FROM View_aa B WHERE A.OS_NO=B.OS_NO AND B.PRD_NO=A.PRD_NO FOR xml path('')),1,1,'')AS WH_REM,
stuff((SELECT ';' + CAST(B.ITM AS VARCHAR(500)) FROM View_aa B WHERE A.OS_NO=B.OS_NO AND B.PRD_NO=A.PRD_NO FOR xml path('')),1,1,'')AS ITM
 FROM View_aa A WHERE {1} AND OS_NO+PRD_NO NOT IN(SELECT TOP {2} OS_NO+PRD_NO FROM View_aa WHERE {3} {4} {5}){6} {7}""".\
    format(page_size,conditional,page_size*page,conditional,gurup_by,sort,gurup_by,sort)
        # print(sql)
        with connection.cursor() as cursor:
            no_data = cursor.execute(sql,[]).fetchall()

        # OS_NO = []  啊啊撒打算梵蒂冈git add .
        for i in no_data:
            # print(1111)
            # OS_NO.append(i[5])
            data.append({"ORDER0": i[0], "OS_DD": str(i[1])[:10] , "CUS_SNM": i[2], "OS_NO": str(i[3]),
                         "PRD_NO": i[4], "DZRL": i[5], "QY": i[6], "YSSL": i[7],
                         "YMXH": i[8], "QTY": float(i[9]),"GZSL": float(i[10]),"EST_DD": str(i[11]),
                         "PD_DEP": i[12],"REM":i[13],"PMC_DD": str(i[14]),"WH_REM": i[15],"operation": "保存","ITM":i[16]})

        # print(data)啊
        # print(sql)
        context = {
            "data": data,
            "total_page":total_page,
            "total_count":total_count,
            "message": "一览表获取成功",
            "code": 200
        }
        return http.JsonResponse(context)
    def put(self, request):
        req_data = json.loads(request.body.decode())["data"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(req_data)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        OS_NO = req_data.get("OS_NO")
        WH_REM = req_data.get("WH_REM",'')
        ITM = req_data.get("ITM")
        try:
            PMC_DD = req_data.get("PMC_DD", '')
            if len(PMC_DD)<=0:
                return http.HttpResponseForbidden("请输选择日期")
        except Exception:
            return http.HttpResponseForbidden("日期格式有问题或者日期不能为空")
        if OS_NO is None or ITM is None:
            return http.HttpResponseForbidden("参数不能为空")
        with connection.cursor() as cursor:
            cursor.execute(
                """UPDATE TF_POS_Z SET PMC_REM=%s,WH_REM=%s WHERE OS_ID='SO' AND OS_NO=%s AND ITM=%s """,
                [PMC_DD,WH_REM,OS_NO,ITM])
        context = {
            "message": "保存成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 渲染dep_ps.html月度产能评估模板
class depps(View):
    def get(self, request):
        return render(request, 'dep_ps.html')
# 月度产能评估功能类
class DepMacf(View):
    def get(self,request):
        # st_time = request.GET["st_time"]  # 开始时间
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        data_timeqi = request.GET["data_timeqi"]
        data_timezhi = request.GET["data_timezhi"]
        serch_dep = request.GET["serch_dep"].split('->')[0]  #部门编码->这里需要进行切割，因为传过来的是编码+名称（’编码->名称‘）
        serch_no = request.GET["serch_no"].split('->')[0]  #单号->这里需要进行切割，因为传过来的是编码+名称（’单号->成品名称‘）
        if len(data_timeqi)==10:
            data_time = "WHERE "+"left(Convert(varchar(100), dd, 23), 11)>="+"'"+data_timeqi+"'"+' AND '+"left(Convert(varchar(100), dd, 23), 11)<="+"'"+data_timezhi+"'"
        else:
            return http.HttpResponseForbidden("输入的时间有问题")
        if len(serch_dep)>0:
            serch_dep =" AND " + "DEP="+"'"+serch_dep+"'"
        else:
            serch_dep = ''
        if len(serch_no)>0:
            serch_no = " AND "+"NO="+"'"+serch_no+"'"
        else:
            serch_no = ''
        conditional = data_time+serch_dep+serch_no+" ORDER BY NO,ITM ASC"
        sql = """SELECT itm,no as no,dep,dep_name as dep_name,cast(ok_qty as float) as ok_qty,cast(un_qty as float) as un_qty,
    cast(s_capacity as float) as s_capacity ,cast(s_d_staffing as float) as s_d_staffing ,cast(e_capacity as float) as e_capacity ,cast(tolf_days as float) as tolf_days ,cast(epl_personnel as float) as epl_personnel ,cast(p_d_f_e_configurations as float) as p_d_f_e_configurations,
    a_strength as a_strength ,cast(e_a_workers as float) as e_a_workers ,cast(work_sum as float) as work_sum,cast(zj_274_24 as float) as zj_274_24 ,cast(a_274_24 as float) as a_274_24 ,cast(new_personnel as float) as new_personnel ,rem as rem ,cast(need_hours as float) as need_hours, cast(a_25 as float) as a_25 ,
    cast(e_d_workers as float) as e_d_workers ,cast(p_gap as float) as p_gap
    from MCAF {0}""".format(conditional)
        print(sql)
        data = executeQuery(sql)
        # print(sql)
        if len(data)<=0:
            return http.HttpResponseForbidden("没有查询单数据")
        print(data)
        context = {
            "data":data,
            "message": "查询成功",
            "code": 200
        }
        return http.JsonResponse(context)
    def post(self,request):
        # 获取数据
        req_data = json.loads(request.body.decode())["data"]
        # 校验参数合法性
        print(req_data)
        for i in req_data["data_list"]:
            sqlinjection = sqlinjections().ifsql(i)
            if sqlinjection:
                return http.HttpResponseForbidden("参数非法")
        # print(req_data["data_list"])
        # t_today = datetime.datetime.now().strftime('%Y-%m-%d')  # 获取年月日
        t_today = req_data.get("data_time_no")  # 获取年月日
        itm = 1 #定义项次
        with connection.cursor() as cursor:
            # 获取数据里面当天最大的单号，然后处理生产单号
            sql_no = """SELECT MAX(NO) AS NO FROM MCAF WHERE DD='{0}'""".format(t_today)
            # print(sql_no)
            monthly_odd_new = monthly_odd(sql_no)  # 生产单号
            for i in req_data["data_list"]:
                # 计算订单可维持天数
                try :
                    tolf_days = float(i["un_qty"])/float(i["s_capacity"])
                except Exception:
                    return http.HttpResponseForbidden('计算订单可维持天数，被除数不能为零')
                #计算现有配置可生产天数
                try:
                    p_d_f_e_configurations = float(i["un_qty"])/float(i["e_capacity"])
                except Exception:
                    return http.HttpResponseForbidden('计算现有可配置天数，被除数不能为零')
                #计算现有出勤人员合计
                work_sum = float(i["e_a_workers"])+float(i["e_d_workers"])
                # 计算直接工人274小时/25天
                zj_274_24 = (float(i["ok_qty"])/(float(i["s_capacity"])+float(i["s_d_staffing"])))/25
                #计算按274小时/25天配置人员
                a_274_24 = (float(i["ok_qty"])/(float(i["s_capacity"])+float(i["s_d_staffing"])))/25+float(i["e_a_workers"])
                #计算计划新增人员配置
                new_personnel = (float(i["ok_qty"])/(float(i["s_capacity"])+float(i["s_d_staffing"])))/25-float(i["e_d_workers"])
                #计算需求工时
                need_hours = float(i["s_d_staffing"])*(float(i["un_qty"])/float(i["s_capacity"]))*11
                #计算按25个工作日计算人员需求
                a_25 = float(i["s_d_staffing"])*(float(i["un_qty"])/float(i["s_capacity"]))*11/274*1.2
                #计算人员缺口
                p_gap = float(i["s_d_staffing"])*(float(i["un_qty"])/float(i["s_capacity"]))*11/274*1.2-float(i["e_d_workers"])
                sql = """INSERT INTO mcaf(itm,dep,no,dep_name,dd,un_qty,s_capacity,s_d_staffing,e_capacity,tolf_days,epl_personnel,p_d_f_e_configurations,
                a_strength,e_a_workers,work_sum,zj_274_24,a_274_24,new_personnel,rem,need_hours,a_25,e_d_workers,p_gap,ok_qty)
                VALUES ({0},'{1}','{2}','{3}','{4}',{5},{6},{7},{8},{9},{10},{11},'{12}',{13},{14},{15},{16},{17},'{18}',{19},{20},{21},{22},{23})
                """.format(itm,i["dep"],monthly_odd_new,i["dep_name"],t_today,i["un_qty"],i["s_capacity"],i["s_d_staffing"],i["e_capacity"]	,
                           tolf_days,i["epl_personnel"],p_d_f_e_configurations,i["a_strength"],i["e_a_workers"]	,work_sum,
                           zj_274_24,a_274_24,new_personnel,i["rem"],need_hours,a_25,i["e_d_workers"],p_gap,i["ok_qty"])
                itm +=1
                # print(sql)
                cursor.execute(sql,[])
        # data = {"monthly_odd_new":monthly_odd_new}
        context = {
            "data": monthly_odd_new,
            "message": "保存成功",
            "code": 200
        }
        return http.JsonResponse(context)
    def put(self,request):
        # with connection.cursor() as cursor:
        req_data = json.loads(request.body.decode())["data"]["data"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(req_data[0])
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        # print(req_data)
        with connection.cursor() as cursor:
            for i in req_data:
                print(i)
                # 计算订单可维持天数
                try:
                    tolf_days = float(i["un_qty"]) / float(i["s_capacity"])
                except Exception:
                    return http.HttpResponseForbidden('计算订单可维持天数，被除数不能为零')
                # 计算现有配置可生产天数
                try:
                    p_d_f_e_configurations = float(i["un_qty"]) / float(i["e_capacity"])
                except Exception:
                    return http.HttpResponseForbidden('计算现有可配置天数，被除数不能为零')
                # 计算现有出勤人员合计
                work_sum = float(i["e_a_workers"]) + float(i["e_d_workers"])
                # 计算直接工人274小时/25天
                zj_274_24 = (float(i["ok_qty"]) / (float(i["s_capacity"]) + float(i["s_d_staffing"]))) / 25
                # 计算按274小时/25天配置人员
                a_274_24 = (float(i["ok_qty"]) / (float(i["s_capacity"]) + float(i["s_d_staffing"]))) / 25 + float(
                    i["e_a_workers"])
                # 计算计划新增人员配置
                new_personnel = (float(i["ok_qty"]) / (float(i["s_capacity"]) + float(i["s_d_staffing"]))) / 25 - float(
                    i["e_d_workers"])
                # 计算需求工时
                need_hours = float(i["s_d_staffing"]) * (float(i["un_qty"]) / float(i["s_capacity"])) * 11
                # 计算按25个工作日计算人员需求
                a_25 = float(i["s_d_staffing"]) * (float(i["un_qty"]) / float(i["s_capacity"])) * 11 / 274 * 1.2
                # 计算人员缺口
                p_gap = float(i["s_d_staffing"]) * (
                float(i["un_qty"]) / float(i["s_capacity"])) * 11 / 274 * 1.2 - float(i["e_d_workers"])
                cursor.execute("""UPDATE MCAF SET ok_qty=%s, un_qty=%s, s_capacity=%s, s_d_staffing=%s, e_capacity=%s, tolf_days=%s, epl_personnel=%s,
              p_d_f_e_configurations=%s, a_strength=%s, e_a_workers=%s, work_sum=%s, zj_274_24=%s, a_274_24=%s, new_personnel=%s, rem=%s,need_hours=%s, a_25=%s,
              e_d_workers=%s, p_gap=%s
              WHERE  dep=%s AND no=%s AND itm=%s""", [i["ok_qty"],i["un_qty"],i["s_capacity"],i["s_d_staffing"],i["e_capacity"],tolf_days,i["epl_personnel"]
                    , p_d_f_e_configurations,i["a_strength"],i["e_a_workers"],work_sum,zj_274_24,a_274_24,new_personnel,i["rem"],need_hours,a_25
                    ,i["e_d_workers"],p_gap,i["dep"], i["no"], i["itm"]])
        context = {
            "message": "修改成功",
            "code": 200
        }
        return http.JsonResponse(context)
    def delete(self,request):
        # 获取参数
        req_data = json.loads(request.body.decode())
        dep = req_data["dep"]
        no = req_data["no"]
        itm = req_data["itm"]
        data = req_data["data"]
        # print(dep)
        # print(no)
        # print(itm)
        # print(data)
        with connection.cursor() as cursor:
            # 删除行
            if dep!='':
                cursor.execute("""DELETE FROM MCAF WHERE  dep=%s AND no=%s AND itm=%s""", [dep,no,itm])
            #删除整张单
            for i in data:
                cursor.execute("""DELETE FROM MCAF WHERE  dep=%s AND no=%s AND itm=%s""", [i["dep"], i["no"], i["itm"]])
        context = {
            "message": "删除成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 月度产能评估表更具部门获取数据
class DepMacfDepData(View):
    def get(self, request):
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        try:
            dep = request.GET["dep"].split('->')[0]  #部门编码->这里需要进行切割，因为传过来的是编码+名称（’编码->名称‘）
        except Exception:
            dep = request.GET["dep"]
        try:
            selected = executeQuery(f"SELECT selected FROM DSCSETTING WHERE DEP='{dep}'")[0]["selected"]
        except Exception:
            return http.HttpResponseForbidden("部门不存在")
        if selected == 'T':
            dep = "AND b.dep=" + "'" + dep + "' "
        else:
            dep = "AND b.UP=" + "'" + dep + "' " +"AND b.selected='T'"
        sql = ("""SELECT b.dep,b.dep_name as dep_name,cast(sum(isnull(a.QTY_FIN,0)) as decimal(14,2)) as ok_qty,cast(sum(ISNULL(a.QTY,0)-isnull(a.QTY_FIN,0)) as decimal(14,2)) as un_qty,
    cast(max(B.s_capacity) as float) as s_capacity ,cast(max(B.s_d_staffing) as float) as s_d_staffing ,0 as e_capacity ,0 as tolf_days ,0 as epl_personnel ,0 as p_d_f_e_configurations,
    '' as a_strength ,0 as e_a_workers ,0 as work_sum,0 as zj_274_24 ,0 as a_274_24 ,0 as new_personnel ,'' as rem ,0 as need_hours, 0 as a_25 ,
    0 as e_d_workers ,0 as p_gap
    from mf_mo a left join DSCSETTING b on a.dep=b.dep where isnull(a.CLOSE_ID,'')!='T' {0} group by b.dep,b.dep_name""".format(dep))
        print(sql)
        try:
            result = executeQuery(sql)
            print(result)
        except Exception:
            return http.HttpResponseForbidden("没有查询到数据")
        if len(result)<=0:
            return http.HttpResponseForbidden("数据量为0，")
        context = {
            "data": result,
            "message": "获取部门数据成功",
            "code": 200
        }
        return http.JsonResponse(context)
# 生成月度产能评估表单号
class monthly(View):
    def get(self, request):
        monthly_odd_old='20200219009'
        monthly_odd_new = monthly_odd(monthly_odd_old)
        # data = {"monthly_odd_new":monthly_odd_new}
        context = {
            "data": monthly_odd_new,
            "message": "获取部门成功",
            "code": 200
        }
        return http.JsonResponse(context)
#车间标准产能设置渲染模板
class DesSettingtm(View):
    def get(self,request):
        return render(request,'dessetting.html')
# 车间标准产能设置渲染功能接口
class DesSetting(View):
    def get(self, request):
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        try:
            dep = request.GET["dep"].split('->')[0]
        except Exception:
            dep = request.GET["dep"]
        if len(dep)>0:
            try:
                selected = executeQuery(f"SELECT selected FROM DSCSETTING WHERE DEP='{dep}'")[0]["selected"]
            except Exception:
                return http.HttpResponseForbidden("部门不存在")
            if selected=='T':
                dep = "dep=" + "'" + dep + "'"
            else:
                dep = "UP=" + "'" + dep + "'"
            sql = """SELECT isnull(dep,'') as dep,isnull(dep_name,'') as dep_name,isnull(up_dd,'') as up_dd,
        cast(isnull(s_capacity,0) as varchar(20)) as s_capacity,cast(isnull(s_d_staffing,0) as varchar(20)) as s_d_staffing,up,selected FROM DSCSETTING WHERE {} """.format(dep)
        else:
            sql = """SELECT isnull(dep,'') as dep,isnull(dep_name,'') as dep_name,isnull(up_dd,'') as up_dd,
        isnull(s_capacity,0) as s_capacity,isnull(s_d_staffing,0) as s_d_staffing,up,selected FROM DSCSETTING"""
        try:
            result = executeQuery(sql)
        except Exception:
            return http.HttpResponseForbidden('没有查询到数据')
        data = [{"dep":"部门编码","dep_name":"部门名称","up_dd":"上次修改时间","s_capacity":"标准/满线产能","s_d_staffing":"标准直接人员配置","operation":"操作","up":"所属部门","selected":"产线否"}]
        if len(result) != 0:
            for i in result:
                data.append({"dep": i["dep"], "dep_name": i["dep_name"] ,"up_dd": i["up_dd"].strftime('%Y-%m-%d'),"s_capacity": float(i["s_capacity"]),"s_d_staffing": float(i["s_d_staffing"]),"up":i["up"],"selected":i["selected"]})
        # print(data)
        context = {
            "data":data,
            "message":'获取信息成功',
            "code":'200'
        }
        return http.JsonResponse(context)
    def put(self,request):
        req_data = json.loads(request.body.decode())["data"]
        print(req_data)
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(req_data)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        dep = req_data.get("dep")
        s_capacity = req_data.get("s_capacity")
        s_d_staffing = req_data.get("s_d_staffing")
        # up_dd = datetime.datetime.now()
        up_dd = datetime.datetime.now().strftime('%Y-%m-%d')
        selected = 'T' if str(req_data.get("selected"))=='True' else ''
        print(selected)
        if dep is None:
            return http.HttpResponseForbidden("部门不能为空值")
        sql = f"""UPDATE DSCSETTING SET s_capacity={s_capacity},s_d_staffing={s_d_staffing},up_dd=convert(datetime,'{up_dd}', 20),selected = '{selected}'
         WHERE DEP='{dep}'"""
        print(sql)
        with connection.cursor() as cursor:
            cursor.execute(sql,[])
        context = {
            "message": "修改成功",
            "code": 200
        }
        return http.JsonResponse(context)
# ie文件号管理模板渲染
class IeFiletm(View):
    def get(self,request):
        return render(request,'iefile.html')
# ie文件号管理功能接口
class IeFile(View):
    def get(self,request):
        try:
            iefile_no = request.GET["iefile_no"]
        except Exception:
            return http.HttpResponseForbidden("参数不存在")
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        # 查询表头
        sql1 = """select iefile_no,cast(hr_up as float) as hr_up,left(Convert(varchar(100), ae_date, 23), 11)as ae_date,cast(postil_up as float)as postil_up,rem,file_serial,
cast(total_manpower as float)as total_manpower,user_no,workshop_name,cast(point as float)as point,dep,dep_name,
cast(job_time as float)as job_time,left(Convert(varchar(100), sys_date, 23), 11)as sys_date from MF_IEFILE WHERE iefile_no='{0}'""".format(iefile_no)
        try:
            mfiefile = executeQuery(sql1)
        except Exception:
            return http.HttpResponseForbidden("数据查询有问题mf")
        # print(len(mfiefile))
        if len(mfiefile)>1:
            return http.HttpResponseForbidden("数据查询有问题mf")
        #查询表身BOM
        sql2 = """SELECT iefile_no,bom_no,cast(itm as FLOAT ) as itm FROM TF_IEFILE_BOM WHERE iefile_no='{}' ORDER BY ITM ASC""".format(iefile_no)
        # print(sql2)
        try:
            tfiefilebom = executeQuery(sql2)
        except Exception:
            return http.HttpResponseForbidden("数据查询异常bom")
        # 查询表身qty
        sql3 = """SELECT iefile_no,cast(qty as FLOAT ) as qty,cast(up as FLOAT ) as up,cast(itm as FLOAT ) as itm
        FROM TF_IEFILE_UP WHERE iefile_no='{}' ORDER BY ITM ASC""".format(iefile_no)
        try:
            tfiefileqty = executeQuery(sql3)
        except Exception:
            return http.HttpResponseForbidden("数据查询查询非法qty")
        content = {
            "datamf":mfiefile,
            "tfiefilebom":tfiefilebom,
            "tfiefileqty":tfiefileqty,
            "mssage":"ie文件查询成功",
            "code":200
        }
        return http.JsonResponse(content)
    @transaction.atomic
    def post(self,request):
        req_data = json.loads(request.body.decode())["data"]
        hr_up = req_data["hr_up"]  #1小时管理费用（元/小时）
        da_date = req_data["da_date"]  #收件日期
        postil_up = req_data["postil_up"]  #文件批注单价
        rem = req_data["rem"]  #文件批注单价
        file_serial = req_data["file_serial"]  #IE工艺文件编号
        total_manpower = req_data["total_manpower"]  #标准总人力(人)
        workshop_name = req_data["workshop_name"]  #工段名称
        point = req_data["point"]  #瓶颈时间（秒）
        dep = req_data["dep"].split('->')[0]  #作业线体(部门)
        dep_name = req_data["dep"].split('->')[1] #作业线体(部门名称)
        job_time = req_data["job_time"]  #文作业时间（秒）
        username = req_data["username"]  #输单电脑
        sys_date = req_data["sys_date"]  #输单日期
        list_bom = req_data["list_bom"]  #选择bom
        list_qty = req_data["list_qty"]  #阶梯单价
        # 校验参数合法性表头
        data_list = ['iefile_no', 'hr_up', 'da_date', 'postil_up', 'rem', 'file_serial', 'total_manpower',
                     'workshop_name', 'point', 'dep',
                     'dep_name', 'job_time', 'username', 'sys_date']
        data_dict = {}
        for i, (k, v) in enumerate(req_data.items()):
            if k in data_list:
                data_dict[k] = str(v)
        sqlinjection = sqlinjections().ifsql(data_dict)
        if sqlinjection:
            return http.HttpResponseForbidden("mf参数非法")
        print(data_dict)
        # 校验参数合法性bom
        for i in list_bom:
            sqlinjection = sqlinjections().ifsql(i)
            if sqlinjection:
                return http.HttpResponseForbidden("bom参数非法")
        for i in list_qty:
            # 校验参数合法性qty
            sqlinjection = sqlinjections().ifsql(i)
            if sqlinjection:
                return http.HttpResponseForbidden("qty参数非法")
        # 判断部门
        if len(req_data["dep"])<=0:
            return http.HttpResponseForbidden("请选择部门")
        t_today = datetime.datetime.now().strftime('%Y-%m-%d')  # 获取年月日,用于插叙单号
        with connection.cursor() as cursor:
            # 获取数据里面当天最大的单号，然后处理生产单号
            try:
                sql_no = """SELECT MAX(right(iefile_no,LEN(iefile_no)-2)) AS NO FROM MF_IEFILE WHERE sys_date='{0}'""".format(t_today)
                monthly_odd_new = monthly_odd(sql_no)  # 生产单号
                monthly_odd_new = 'IE' + str(monthly_odd_new)
            except Exception:
                return http.HttpResponseForbidden("生成单号异常，请检查数据")
            # print(monthly_odd_new)
            sid = transaction.savepoint()  # 开启事物
            try:
                # 插入ie文件号表头
                sql = """INSERT INTO MF_IEFILE(IEFILE_NO,HR_UP,AE_DATE,postil_up,rem,file_serial,total_manpower,user_no,workshop_name,point,dep,dep_name,job_time,sys_date)
                VALUES('%s',%s,'%s',%s,'%s','%s',%s,'%s','%s',%s,'%s','%s',%s,'%s')"""\
                %(str(monthly_odd_new),hr_up,da_date,postil_up,rem,file_serial,total_manpower,username,workshop_name,point,dep,dep_name,job_time,sys_date)
                cursor.execute(sql, [])
                # 插入表身BOM数据
                if len(list_bom)>0:
                    bom_itm = 1
                    for i in list_bom:
                        sql1 = """INSERT INTO TF_IEFILE_BOM(IEFILE_NO,BOM_NO,ITM)VALUES('%s','%s','%s')"""%(monthly_odd_new,i["bom_no"],bom_itm)
                        cursor.execute(sql1, [])
                        bom_itm +=1
                        # print(sql1)
                # 插入表身阶梯单价
                if len(list_qty)>0:
                    qty_itm = 1
                    for i in list_qty:
                        sql2 = """INSERT INTO TF_IEFILE_UP(IEFILE_NO,QTY,UP,ITM)VALUES('%s','%s','%s','%s')""" % (
                        monthly_odd_new, i["qty"], i["up"],qty_itm)
                        cursor.execute(sql2, [])
                        qty_itm += 1
                        # print(sql1)
            except Exception:
                # print(111)
                transaction.savepoint_rollback(sid)
                return http.HttpResponseForbidden("数据增加失败")
            transaction.savepoint_commit(sid)  # 提交事物
            # print(111)
        content = {
            "data": monthly_odd_new,
            "mssage":"ie文件新增成功",
            "code":200
        }
        return http.JsonResponse(content)
    @transaction.atomic
    def put(self,request):
        req_data = json.loads(request.body.decode())["data"]
        iefile_no = req_data.get("iefile_no")
        hr_up = req_data.get("hr_up")  # 1小时管理费用（元/小时）
        da_date = req_data.get("da_date") # 收件日期
        postil_up = req_data.get("postil_up")  # 文件批注单价
        rem = req_data.get("rem")  # 文件批注单价
        file_serial = req_data.get("file_serial")  # IE工艺文件编号
        total_manpower = req_data.get("total_manpower")  # 标准总人力(人)
        workshop_name = req_data.get("workshop_name")  # 工段名称
        point = req_data.get("point")  # 瓶颈时间（秒）
        dep = req_data.get("dep").split('->')[0]  # 作业线体(部门)
        dep_name = req_data.get("dep").split('->')[1]  # 作业线体(部门名称)
        job_time = req_data.get("job_time")  # 文作业时间（秒）
        username = req_data.get("username")  # 输单电脑
        sys_date = req_data.get("sys_date")  # 输单日期
        list_bom = req_data.get("list_bom")  # 选择bom
        list_qty = req_data.get("list_qty")  # 阶梯单价
        # print(req_data)
        # 校验参数合法性表头
        data_list = ['iefile_no','hr_up','da_date','postil_up','rem','file_serial','total_manpower','workshop_name','point','dep',
        'dep_name','job_time','username','sys_date']
        data_dict={}
        for i, (k, v) in enumerate(req_data.items()):
            if k in data_list:
                data_dict[k] = str(v)
        sqlinjection = sqlinjections().ifsql(data_dict)
        if sqlinjection:
            return http.HttpResponseForbidden("mf参数非法")
        print(data_dict)
        # 校验参数合法性bom
        for i in list_bom:
            sqlinjection = sqlinjections().ifsql(i)
            if sqlinjection:
                return http.HttpResponseForbidden("bom参数非法")
        for i in list_qty:
            # 校验参数合法性qty
            sqlinjection = sqlinjections().ifsql(i)
            if sqlinjection:
                return http.HttpResponseForbidden("qty参数非法")
        with connection.cursor() as cursor:
            sid = transaction.savepoint()  # 开启事物
            try:
                # 修改ie文件号表头
                sql = """UPDATE MF_IEFILE SET HR_UP=%s,AE_DATE='%s',postil_up=%s,rem='%s',file_serial='%s',total_manpower=%s,
                user_no='%s',workshop_name='%s',point=%s,dep='%s',dep_name='%s',job_time=%s,sys_date='%s' WHERE IEFILE_NO='%s'"""\
                %(hr_up,da_date,postil_up,rem,file_serial,total_manpower,username,workshop_name,point,dep,dep_name,job_time,sys_date,iefile_no)
                # print(sql)
                cursor.execute(sql, [])
                # 修改表身qty
                for i in list_qty:
                    # print(i)
                    if "iefile_no" in i.keys():
                        sql2 = """UPDATE TF_IEFILE_UP SET QTY=%s,UP=%s WHERE IEFILE_NO='%s' AND ITM='%s'""" % (
                            i["qty"], i["up"],iefile_no, i["itm"])
                        cursor.execute(sql2, [])
                    else:
                        sql3 = """SELECT MAX(ITM) AS ITM FROM TF_IEFILE_UP WHERE IEFILE_NO='%s'"""%(iefile_no)
                        mfiefile = executeQuery(sql3)[0]["ITM"]
                        if mfiefile is None:
                            mfiefile = 0
                        sql4 = """INSERT INTO TF_IEFILE_UP(IEFILE_NO,QTY,UP,ITM)VALUES('%s','%s','%s','%s')""" % (
                            iefile_no, i["qty"], i["up"], mfiefile+1)
                        print(sql4)
                        i["iefile_no"]=iefile_no
                        i["itm"] = mfiefile + 1
                        cursor.execute(sql4, [])
                #修改表身BOM
                for i in list_bom:
                    # print(i)
                    if "iefile_no" not in i.keys():
                        sql5 = """SELECT MAX(ITM) AS ITM FROM TF_IEFILE_BOM WHERE IEFILE_NO='%s'"""%(iefile_no)
                        mfiefile_bom = executeQuery(sql5)[0]["ITM"]
                        if mfiefile_bom is None:
                            mfiefile_bom = 0
                        sql6 = """INSERT INTO TF_IEFILE_BOM(IEFILE_NO,BOM_NO,ITM)VALUES('%s','%s','%s')""" % (
                            iefile_no, i["bom_no"], mfiefile_bom+1)
                        i["iefile_no"]=iefile_no
                        i["itm"] = mfiefile_bom + 1
                        cursor.execute(sql6, [])
            except Exception:
                # print(111)
                transaction.savepoint_rollback(sid)
                return http.HttpResponseForbidden("数据修改失败")
            transaction.savepoint_commit(sid)  # 提交事物
        content = {
            "list_qty":list_qty,
            "list_bom":list_bom,
            "mssage": "修改成功",
            "code": 200
        }
        return http.JsonResponse(content)
    def delete(self,request):
        req_data = json.loads(request.body.decode())
        iefile_no = req_data["iefile_no"]
        # print(iefile_no)
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(req_data)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        with connection.cursor() as cursor:
            sid = transaction.savepoint()  # 开启事物
            try:
                # 删除表头
                sql1 = """DELETE FROM MF_IEFILE WHERE  iefile_no = '{0}'""".format(iefile_no)
                cursor.execute(sql1, [])
                # 删除BOM
                sql2 = """DELETE FROM TF_IEFILE_BOM WHERE  iefile_no = '{0}'""".format(iefile_no)
                cursor.execute(sql2, [])
                # 删除QTY
                sql3 = """DELETE FROM TF_IEFILE_UP WHERE  iefile_no = '{0}'""".format(iefile_no)
                cursor.execute(sql3, [])
            except Exception:
                # print(111)
                transaction.savepoint_rollback(sid)
                return http.HttpResponseForbidden("删除数据失败")
            transaction.savepoint_commit(sid)  # 提交事物
        content = {
            "mssage": "删除成功",
            "code": 200
        }
        return http.JsonResponse(content)
# 查询ie文件号管理表头及删除表身
class MfIeFile(View):
    def get(self, request):
        date_qi = request.GET["date_qi"]
        date_zhi = request.GET["date_zhi"]
        select_file_serial = request.GET["select_file_serial"]
        select_dep = request.GET["select_dep"]
        select_iefile_no = request.GET["select_iefile_no"]
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(request.GET)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if date_qi is None or date_zhi is None:
            return http.HttpResponseForbidden("参数不全")
        parameter = " WHERE left(Convert(varchar(100), ae_date, 23), 11)>="+"'"+date_qi+"'"+" AND "+"left(Convert(varchar(100), ae_date, 23), 11)<="+"'"+date_zhi+"'"
        # 处理IE文件编号
        if len(select_file_serial)>0:
            select_file_serial = " AND file_serial LIKE"+"'%%"+select_file_serial+"%%'"
        else:
            select_file_serial=''
        #处理部门
        if len(select_dep) > 0:
            select_dep = " AND dep LIKE" + "'%%" + select_dep + "%%'"
        else:
            select_dep = ''
        # 处理IE文件单号
        if len(select_iefile_no) > 0:
            select_iefile_no = " AND iefile_no LIKE" + "'%%" + select_iefile_no + "%%'"
        else:
            select_iefile_no = ''
        parameter = parameter + select_file_serial + select_dep + select_iefile_no
        # print(parameter)
        sql = """select iefile_no,cast(hr_up as float) as hr_up,left(Convert(varchar(100), ae_date, 23), 11)as ae_date,cast(postil_up as float)as postil_up,rem,file_serial,
    cast(total_manpower as float)as total_manpower,user_no,workshop_name,cast(point as float)as point,dep,dep_name,
    cast(job_time as float)as job_time,left(Convert(varchar(100), sys_date, 23), 11)as sys_date from MF_IEFILE {0}""".format(parameter)
        # print(sql)
        result = executeQuery(sql)
        content = {
            "data": result,
            "mssage": "ie文件查询成功",
            "code": 200
        }
        return http.JsonResponse(content)
    def delete(self,request):
        req_data = json.loads(request.body.decode())
        iefile_no = req_data["iefile_no"]
        try:
            bom = req_data["bom"]
        except Exception:
            return http.HttpResponseForbidden("bom异常")
        itm = req_data["itm"]
        if not all([iefile_no,itm]):
            return http.HttpResponseForbidden("参数不全")
        # 校验参数合法性
        sqlinjection = sqlinjections().ifsql(req_data)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        if len(bom)<=0:
            sql = """DELETE FROM TF_IEFILE_UP WHERE iefile_no='{0}' AND itm='{1}'""".format(iefile_no,itm)
        else:
            sql="""DELETE FROM TF_IEFILE_BOM WHERE iefile_no='{0}' AND itm='{1}'""".format(iefile_no,itm)
        with connection.cursor() as cursor:
            try:
                cursor.execute(sql, [])
            except Exception:
                return http.HttpResponseForbidden("异常操作，删除失败")
        content = {
            "mssage": "删除成功",
            "code": 200
        }
        return http.JsonResponse(content)
# ie工艺号文件维护
class IeFileMaintaintm(View):
    def get(self,request):
        return render(request,'iefilemaintain.html')

# 测试
class text(View):
    def get(self, request):
        return render(request, 'text.html')