var self = this
var page = {
    tableEditIndex: -1,
    dictCodes: ['payment_method', 'payment_way', 'supplier_accetp_deadline', 'controlling_accounts', 'currency'],
    loadNecessaryData: function () {
        initNecessaryData("pc/sys/tax/rest/listAll")
        initNecessaryData("pc/sys/purchaseOrg/rest/listAll")
        initNecessaryData("pc/sys/company/rest/listAll")
        initDict(page.dictCodes.join(','))
    },
    columns: [],
    loadGrid: function () {
        let height = document.documentElement.clientHeight - 500;
        height = height > 200 ? height : 200;
        page.columns = [{
            field: 'state', title: '类型', width: '45', formatter: function (value) {
                switch (value) {
                    case 1:
                        return '<span style="color:blue;">新增</span>';
                    case 2:
                        return '<span style="color:green;">编辑</span>';
                    case 3:
                        return '<span style="color:red;">删除</span>';
                    default:
                        return '初始';
                }
            }
        }, {
            field: 'purchaseCategoryCode',
            title: '<span style="color: red;">*</span>采购品类编码',
            width: '100',
            editor: {
                type: 'textbox', options: {
                    required: true, editable: false, icons: [{
                        iconCls: 'icon-search', handler: function () {
                            var supplierType = $("#supplierType").val();
                            if (supplierType == "") {
                                topWin.layer.msg("请先选择供应商类型");
                                return;
                            }
                            var purchaseCategoryDialog = openDialog("purchaseCategoryDialog", g.ctx + 'pc/sys/purchaseCategory/index?select=1', {
                                title: '采购品类选择器',
                                width: '80%',
                                height: '80%',
                                cache: false,
                                modal: true,
                                border: false,
                                draggable: true,
                                shadow: false,
                                onClose: function () {
                                    purchaseCategoryDialog.dialog('destroy');
                                },
                                buttons: [{
                                    text: itablei8n.save, handler: function () {
                                        topWin.frames['purchaseCategoryDialog'].chooseRow(function (row) {
                                            purchaseCategoryDialog.dialog('close');
                                            let productTypeName = $("#tb").datagrid('getEditor', {
                                                index: page.tableEditIndex, field: 'purchaseCategoryName'
                                            }).target;
                                            productTypeName.textbox("setValue", row.firstLevelPurchaseName)
                                            let productType = $("#tb").datagrid('getEditor', {
                                                index: page.tableEditIndex, field: 'purchaseCategoryCode'
                                            }).target;
                                            productType.textbox("setValue", row.firstLevelPurchaseCode)
                                        });
                                    }
                                }, {
                                    text: itablei8n.close, handler: function () {
                                        purchaseCategoryDialog.dialog('close');
                                    }
                                }]
                            })
                        }
                    }]
                }
            }
        }, {
            field: 'purchaseCategoryName', title: '采购品类名称', width: '100', formatter: function (value) {
                if (!value) {
                    return '全部物料组';
                } else {
                    return value;
                }
            }, editor: {
                type: 'textbox', options: {
                    readonly: true
                }
            }
        }, {
            field: 'currencyCode', title: '<span style="color: red;">*</span>币种', width: '105', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    limitToList: true,
                    required: true,
                    editable: false,
                    data: getDictList('currency'),
                    onChange: function (newVal) {
                        if ($("#tb").datagrid('getEditor', {
                            index: page.tableEditIndex, field: 'paymentTerms'
                        }) == null) {
                            return
                        }
                        let paymentTerms = $("#tb").datagrid('getEditor', {
                            index: page.tableEditIndex, field: 'paymentTerms'
                        }).target;
                        //需要过滤一下这个地方的内容
                        let cnyKeys = ['K001', 'K002', 'K003', 'K004', 'K005', 'K006', 'K007', 'K008', 'K009', 'K010', 'K011', 'K012', 'K013', 'K014', 'K015', 'K016', 'K017', 'K018', 'K019', 'K020', 'K021', 'K022', 'K023', 'K024', 'K025', 'K026', 'K027', 'K028', 'K029', 'K030', 'K031', 'K032', 'K033', 'K034', 'Z001'];
                        let otherKeys = ['K001', 'K002', 'K003', 'K004', 'K005', 'K006', 'K007', 'K008', 'K009', 'K010', 'K011', 'K012', 'K013', 'K014', 'K015', 'K016', 'K017', 'K018', 'K019', 'K020', 'K021', 'K034', 'K601', 'K602', 'K603', 'K604', 'K605', 'K651', 'K652', 'K653', 'K654', 'K655', 'K656', 'K657', 'Z001'];
                        let data = getDictList('payment_method')
                        //需要根据newVla是不是CNY来过滤
                        if(newVal==='CNY'){
                            let tmp =  data.filter(a=>cnyKeys.includes(a.code))
                            paymentTerms.combobox("clear")
                            paymentTerms.combobox('loadData',tmp)
                        }else{
                            let tmp =  data.filter(a=>otherKeys.includes(a.code))
                            paymentTerms.combobox("clear")
                            paymentTerms.combobox('loadData',tmp)
                            let taxCode = $("#tb").datagrid('getEditor', {
                                index: page.tableEditIndex, field: 'taxCode'
                            }).target;
                            taxCode.combobox("setValue", 'J0')
                        }
                    }
                }
            }, formatter: function (value) {
                return getDicName('currency', value)
            }
        }, {
            field: 'paymentTerms', title: '<span style="color: red;">*</span>付款条件', width: '145', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    limitToList: true,
                    required: true,
                    editable: true,
                    data: getDictList('payment_method')
                }
            }, formatter: function (value) {
                if (value) {
                    return getDicName('payment_method', value)
                }
                return ''
            }
        }, {
            field: 'paymentMethod', title: '<span style="color: red;">*</span>付款方式', width: '100', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    editable: true,
                    data: getDictList('payment_way'),
                    onSelect: function (newVal) {
                        setTimeout(function () {
                            let paymentMethod = $("#tb").datagrid('getEditor', {
                                index: page.tableEditIndex, field: 'acceptanceMethod'
                            }).target;
                            let oldVal = paymentMethod.combobox("getValue")
                            paymentMethod.combobox("clear")
                            if (newVal.code === 'C') {
                                paymentMethod.combobox({"required": true})
                                paymentMethod.combobox("enable")
                            } else {
                                paymentMethod.combobox({"required": false})
                                paymentMethod.combobox("disable")
                            }
                        }, 50)
                    }
                }
            }, formatter: function (value) {
                return getDicName('payment_way', value)
            }
        }, {
            field: 'acceptanceMethod', title: '承兑期限', width: '100', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    required: false,
                    editable: true,
                    data: getDictList('supplier_accetp_deadline')
                }
            }, formatter: function (value) {
                return getDicName('supplier_accetp_deadline', value)
            }
        }, {
            field: 'companyCode', title: '<span style="color: red;">*</span>公司', width: '240', editor: {
                type: 'combobox', options: {
                    valueField: 'code', // 'dicId',
                    textField: 'codeWithDesc',  // 'dicTxt',
                    panelHeight: '200',
                    limitToList: true,
                    required: true,
                    editable: false,
                    data: getDictList('pc/sys/company/rest/listAll'),
                    onChange: function (newVal) {
                        if ($("#tb").datagrid('getEditor', {
                            index: page.tableEditIndex, field: 'purchaseOrgCode'
                        }) == null) {
                            return
                        }
                        let purchaseOrgCode = $("#tb").datagrid('getEditor', {
                            index: page.tableEditIndex, field: 'purchaseOrgCode'
                        }).target;
                        initNecessaryData("pc/sys/purchaseOrg/rest/listAll", 'code', 'codeWithDesc', {companyCodes: newVal + ',8000'})
                        purchaseOrgCode.combobox("loadData", getDictList('pc/sys/purchaseOrg/rest/listAll'))
                        purchaseOrgCode.combobox("clear")
                        purchaseOrgCode.combobox("setValue", "8000");
                    }

                }
            }, formatter: function (value) {
                if (value) {
                    return getNecessaryDataName("pc/sys/company/rest/listAll", value)
                }
                return ''
            }
        }, {
            field: 'taxCode', title: '<span style="color: red;">*</span>税率', width: '80', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    limitToList: true,
                    required: true,
                    editable: false,
                    data: getNecessaryDataList("pc/sys/tax/rest/listAll")
                }
            }, formatter: function (value) {
                return getNecessaryDataName('pc/sys/tax/rest/listAll', value)
            }
        }, {
            field: 'controlSubject', title: '<span style="color: red;">*</span>统御科目', width: '255', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    required: true,
                    limitToList: true,
                    editable: false,
                    data: getDictList('controlling_accounts')
                }
            }, formatter: function (value) {
                if (value) {
                    return getDicName('controlling_accounts', value)
                }
                return ''
            }
        }, {
            field: 'purchaseOrgCode', title: '<span style="color: red;">*</span>采购组织', width: '180', editor: {
                type: 'combobox', options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: '200',
                    required: true,
                    limitToList: true,
                    editable: false,
                    readonly: false,
                    data: getDictList('pc/sys/purchaseOrg/rest/listAll')
                }
            }, formatter: function (value) {
                if (value) {
                    return getNecessaryDataName('pc/sys/purchaseOrg/rest/listAll', value)
                }
                return ''
            }
        }];
        let url = ''
        if ($("#id").val()) {
            url = g.ctx + 'pc/supplier/purchaseCategory/rest/listByInvitation'
        }
        $("#tb").edatagrid({
            url: url,
            method: "GET",
            height: height,
            width: '200px    ',
            singleSelect: true,
            rownumbers: true,
            loadMsg: '数据正在加载中...',
            striped: true,
            queryParams: {
                invitationId: $("#id").val()
            },
            onEdit: function (index) {
                page.tableEditIndex = index
            },
            columns: [page.columns],
            toolbar: [
                {
                    text: '新增',
                    iconCls: 'icon-add',
                    handler: function () {
                        let supplierGroup = $("input[comboname='supplierGroup']").combobox("getValue")
                        let row = {'controlSubject': '2202010101'}
                        if (supplierGroup === 'Z002') {
                            row['currencyCode'] = "CNY"
                        } else if (supplierGroup === 'Z003') {
                            row['currencyCode'] = "USD"
                            row['taxCode'] = "J0"
                        }
                        $("#tb").datagrid("appendRow", row)
                    }
                },
                {
                    text: '删除',
                    iconCls: 'icon-remove',
                    handler: function () {
                        var row = $("#tb").datagrid("getSelected")
                        if (!row) {
                            topWin.layer.msg("请选中需要删除的数据!");
                            return false;
                        }
                        $("#tb").datagrid("deleteRow", $("#tb").datagrid("getRowIndex", row))
                    }
                },
                {
                    text: '复制',
                    iconCls: 'icon-plan-copy',
                    handler: function () {
                        $("#tb").edatagrid("saveRow")
                        var row = $("#tb").datagrid("getSelected")
                        if (!row) {
                            topWin.layer.msg("请选中需要复制的数据!");
                            return false;
                        }
                        $("#tb").datagrid("appendRow", row)
                    }
                }
            ]
        });
    },
    saveOrUpdate: function (call) {
        let validate = $('#form').form('validate');
        if (!validate) {
            topWin.layer.msg("必填项不得为空!");
            return false;
        }
        var formData = $('#form').serializeJson();
        if (Number(formData.templateId) === 20) {
            topWin.layer.msg("请修改模板!")
            return
        }
        $("#tb").edatagrid("saveRow")
        let v = []
        var editors = $('#tb').datagrid('getEditors', page.tableEditIndex)
        if (editors.length > 0) {
            $.each(editors, function (index, editor) {
                if ($(editor.target)[0].classList.contains("combobox-f'")) {
                    if (!$(editor.target).combobox("isValid")) {
                        v.push(1)
                    }
                } else {
                    if (!$(editor.target).textbox("isValid")) {
                        v.push(1)
                    }
                }
            });
        }
        if (v.length > 0) {
            return false;
        }
        const tipMsg = []
        //需要校验品类
        var rows = $("#tb").datagrid("getRows")
        if (rows.length <= 0) {
            topWin.layer.msg("品类不得为空!");
            return false;
        }

        const validateClum = {}
        $.each(page.columns, function (idx, it) {
            if (it.field != 'state') {
                validateClum[it.field] = it.title.replace('<span style="color: red;">*</span>', '')
            }
        })
        $.each(rows, function (idx, row) {
            let tt = []
            $.each(validateClum, function (k, v) {
                if (k === 'acceptanceMethod') {
                    if (row['paymentMethod'] === 'C') {
                        if (!row[k]) {
                            tt.push(v)
                        }
                    }
                } else {
                    if (!row[k]) {
                        tt.push(v)
                    }
                }
            })
            if (tt.length > 0) {
                tipMsg.push((idx + 1) + "行:" + tt.join(',') + "不能为空;")
            }
        })
        if (tipMsg.length > 0) {
            topWin.layer.msg(tipMsg.join("<br/>"));
            return false;
        }
        formData['items'] = rows
        $.ajax({
            url: g.ctx + 'pc/supplier/invitation/rest/saveOrUpdate',
            method: "post",
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function (data) {
                topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    call()
                });
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    },
    attrChange: function (val) {
        if (val === '1' || val === '6') {
            $("input[textboxname='customer1Code']").textbox({required: true})
            $("input[textboxname='customer1Name']").textbox({required: true})
        } else {
            $("input[textboxname='customer1Code']").textbox({required: false})
            $("input[textboxname='customer1Name']").textbox({required: false})
        }
    },
    assessChange: function (val) {
        if (val === '3') {
            $("input[textboxname='specialRemark']").textbox({required: true, editable: true})
        } else {
            $("input[textboxname='specialRemark']").textbox({required: false, editable: false})
        }
    },
    addCustomer1: function () {
        page.openCustomerDialog(function (data) {
            $("input[textboxname='customer1Code']").textbox("setValue", data.customerCode)
            $("input[textboxname='customer1Name']").textbox("setValue", data.customerName1)
        })
    },
    clearCustomer1: function () {
        $("input[textboxname='customer1Code']").textbox("clear")
        $("input[textboxname='customer1Name']").textbox("clear")
    },
    addCustomer2: function () {
        page.openCustomerDialog(function (data) {
            $("input[textboxname='customer2Code']").textbox("setValue", data.customerCode)
            $("input[textboxname='customer2Name']").textbox("setValue", data.customerName1)
        })
    },
    openCustomerDialog: function (call) {
        var customerDialog = openDialog("customerDialog", g.ctx + 'pc/supplier/customer/page/select', {
            title: "客户选择",
            width: '60%',
            height: '95%',
            cache: false,
            modal: true,
            border: false,
            draggable: true,
            shadow: false,
            onClose: function () {
                customerDialog.dialog('destroy');
            },
            buttons: [{
                text: '确定',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['customerDialog'].getChecked(function (data) {
                        call(data)
                        customerDialog.dialog('close');
                    });

                }
            }, {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    customerDialog.dialog('close');
                }
            }]
        })
    }
}

/**
 * 表格校验提示信息
 * @type {Record<string, {
 *   domestic: string,
 *   foreign: string,
 *   current: string
 * }>}
 */
let validationMessages = {};
$(function () {
    page.loadNecessaryData()
    page.loadGrid()
    $("input[comboname='assessType']").combobox("setValue", dd)

    //初始化表单校验规则
    initValidation();
})

function initValidation() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/validationRuleSetting/rest/getFieldValidationById',
        data: {
            fieldId: 255    // 业务扩展字段表，供应商简称id
        },
        success: function (data) {
            initValidationRule(data);
        },
        error: function (data) {
            layer.msg(data);
        }
    });
}

/**
 * 注册所有验证规则
 * @param rules 验证规则
 */
function initValidationRule(rules) {
    const rule = rules.filter(item => {
        return item.currencyType === "CNY";
    })
    const fieldName = "shortName";
    if (rule && rule.length) {
        validationMessages[fieldName] = {
            current: ""
        };
        const config = rule[0];
        $.fn.validatebox.defaults.rules[fieldName] = {
            validator: function(value) {
                // 如果有设置校验规则
                const pattern = "^[" + config.pattern + "]+$"
                const result = new RegExp(pattern).test(value);
                if (!result) {
                    validationMessages[fieldName].current = config.validationMsg;
                    return false;
                }
                // 前后不允许出现空格
                if (value !== value.trim()) {
                    validationMessages[fieldName].current = "前后不允许有空格";
                    return false;
                }
                // 最小长度校验
                if (config.minLength && value.length < config.minLength) {
                    validationMessages[fieldName].current = "至少输入" + config.minLength + "个字符";
                    return false;
                }
                // 最大长度校验
                if (config.maxLength && value.length > config.maxLength) {
                    validationMessages[fieldName].current = "至多输入" + config.maxLength + "个字符";
                    return false;
                }
                // 固定长度校验
                if (config.fixedLength && value.length !== config.fixedLength) {
                    validationMessages[fieldName].current = "只能" + config.fixedLength + "个字符";
                    return false;
                }
                // 当前币种未设置时不校验
                return true;

            },
            get message() {
                return validationMessages[fieldName].current;
            }
        };
    }
}