/**
 * 样品申请创建页面
 * view/supplier/product/demo/add.ftl
 */
var el = {
    form: '#form',
    openProuctChooseDialog: null,
    code: '#code',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    isSupplier: "#isSupplier",
    supplierId: "#supplierId",
    purchaseGroupCode: "#purchaseGroupCode",
    sampleType: "#sampleType",
    returnFlag: "#returnFlag",
    envProtectionFlag: "#envProtectionFlag",
    lifeCycle: "#lifeCycle",
    editindex: undefined
}, isSupplier = $(el.isSupplier).val() !== 'false';
var materialCodeCache = []

$(function () {
    $("#pcnNo").textbox({
        buttonText: '选择',
        iconCls: 'icon-search',
        iconAlign: 'left',
        readonly: isSupplier,
        onClickButton: function () {
            topWin.layer.open({
                title: "OA流程选择",
                type: 2,
                area: ['70%', '70%'],
                content: '/pc/contract/pay/page/choseOaProcess?flag=1',
                btn: ['选择', '关闭'],
                yes: function (index, layero) {
                    var iframeWin = topWin.window[layero.find('iframe')[0]['name']];
                    iframeWin.selectRow(function (code) {
                        if (code != '') {
                            $('#pcnNo').textbox('setValue', code);
                            topWin.layer.close(index);
                        } else {
                            topWin.layer.alert("未选择", {icon: 2})
                        }
                    });
                },
            });
        }
    });
    $(el.purchaseGroupCode).combobox({
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        valueField: 'code',
        textField: 'codeWithDesc',
        readonly: isSupplier,
        required: true,
    });

    $(el.sampleType).combobox({
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=sample_type',
        editable: false,
        readonly: isSupplier,
        required: true,
        tipPosition: 'bottom',
        panelHeight: 'auto'
    });
    $(el.returnFlag).combobox({
        limitToList: 'true',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        readonly: !isSupplier,
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        data: [{code: '1', codeWithDesc: '是'}, {code: '0', codeWithDesc: '否'}],
        editable: false,
        required: isSupplier,
    });
    initItTable()
});


/**
 * 选择物料信息对话框
 */
function openProuctChooseDialog() {

    var selectMaterialElement = openDialog("selectMaterialDialog", g.ctx + 'pc/sys/product/select/dialog?single=0', {
        title: '选择物料',
        width: '80%',
        height: '75%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            selectMaterialElement.dialog('destroy');
        },
        buttons: [{
            text: '确定',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['selectMaterialDialog'].chooseRows(function (data) {
                    console.log(data)
                    let tipMsg = []
                    let rows = []
                    $.each(data, function (idx, itm) {
                        if (materialCodeCache.indexOf(itm.materialCode) > -1) {
                            tipMsg.push(itm.materialCode)
                        }
                        rows.push({
                            materialCode: itm.materialCode,
                            materialName: itm.materialName,
                            materialGroupCode: itm.materialGroupCode,
                            materialGroupName: itm.materialGroupName,
                            needCount: itm.reqNum,
                            envProtectionFlag: "1"
                        })
                        materialCodeCache.push(itm.materialCode)
                    })
                    if (tipMsg.length > 0) {
                        topWin.layer.alert('物料编码：' + tipMsg.join(',') + '已存在，请重新选择', {icon: 2})
                        return
                    }
                    $.each(rows, function (idx, itm) {
                        $("#itb").datagrid('appendRow', itm)
                    })
                    selectMaterialElement.dialog('close');
                })
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                selectMaterialElement.dialog('close');
            }
        }]
    });
}

/**
 * 选择供应商
 */
function openSupplierChooseDialog() {
    var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?single=1", {
        title: common_layer_title.select_supplier_title,
        width: '650px',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            supplierDialogElement.dialog('destroy');
        },
        buttons: [{
            text: '选择',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['supplierDialog'].chooseRow(function (data) {
                    $(el.form).form('load', {
                        supplierId: data.id,
                        supplierCode: data.supplierCode,
                        supplierName: data.supplierName
                    });
                    supplierDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                supplierDialogElement.dialog('close');
            }
        }]
    });
}

var columns = [[
    {
        field: 'ck',
        checkbox: true
    },
    {
        field: 'materialCode',
        title: "物料编码",
        align: 'left',
        width: 130,
        editor: {
            type: 'textbox',
            options: {
                editable: false
            }
        }
    },
    {
        field: 'materialName',
        title: "物料名称",
        align: 'left',
        width: 350,
        editor: {
            type: 'textbox',
            options: {
                editable: false
            }
        }
    },
    {
        field: 'materialGroupCode',
        title: '物料组编码',
        align: 'left',
        width: 120,
        editor: {
            type: 'textbox',
            options: {
                editable: false
            }
        }
    },
    {
        field: 'materialGroupName',
        title: '物料组描述',
        align: 'left',
        width: 300,
        editor: {
            type: 'textbox',
            options: {
                editable: false
            }
        }
    },
    {
        field: 'envProtectionFlag',
        title: "是否需要处理环保",
        align: 'left',
        width: 115,
        editor: {
            type: 'combobox',
            options: {
                editable: false,
                limitToList: 'true',
                panelHeight: 'auto',
                method: 'GET',
                valueField: 'code',
                textField: 'codeWithDesc',
                prompt: '--- 请选择 ---',
                data: [{code: '1', codeWithDesc: '是'}, {code: '0', codeWithDesc: '否'}],
            }
        },
        formatter: function (tt) {
            var value = tt + ''
            if (value === '1') {
                return "是"
            } else if (value === '0') {
                return "否"
            } else {
                return ""
            }
        }
    },
    {
        field: 'needCount',
        title: "需求送样数量",
        align: 'left',
        width: 80,
        editor: {
            type: 'numberbox',
            options: {
                min: 0,
                precision: 2
            }
        }
    },
    {
        field: 'sampleCount',
        title: '实际送货数量<button type="button" onclick="copy(\'sampleCount\')" class="easyui-linkbutton">复制</button>',
        align: 'left',
        width: 120,
        editor: {
            type: 'numberbox',
            options: {
                min: 0,
                precision: 2
            }
        }
    },
    {
        field: 'expressNumber',
        title: '快递单号<button type="button" onclick="copy(\'expressNumber\')" class="easyui-linkbutton">复制</button>',
        align: 'left',
        width: 120,
        editor: {
            type: 'textbox',
            options: {
                prompt: "请输入快递单号"
            }
        }
    }
]];

function initItTable() {
    if (isSupplier) {
        $.each(columns[0], function (index, item) {
            if (item.field === 'sampleCount' || item.field === 'expressNumber') {
            } else {
                delete item.editor
            }
        })
    } else {
        $.each(columns[0], function (index, item) {
            if (item.field === 'sampleCount' || item.field === 'expressNumber') {
                delete item.editor
            }
        })
    }
    $("#itb").edatagrid({
        iconCls: 'icon-list',
        height: 200,
        method: 'GET',
        url: g.ctx + 'pc/supplier/materialDemo/rest/listByHeader?id=' + $("#id").val(),
        singleSelect: false,
        pagination: false,
        autoSave: true,
        loadMsg: commonMsg.loadData,
        rownumbers: true,
        fitColumns: false,
        columns: columns,
        onBeforeEdit: function (index) {
            el.editIndex = index
        },
        toolbar: [{
            text: '新建',
            id: 'add',
            iconCls: 'icon-add',
            handler: function () {
                $("#itb").edatagrid("saveRow")
                openProuctChooseDialog()
            }
        }, {
            text: '删除',
            iconCls: 'icon-remove',
            handler: function () {
                var cbox = $("#itb").datagrid('getChecked');
                if (cbox.length === 0) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                var indexRows = []
                $.each(cbox, function (i, v) {
                    const indexRow = $("#itb").datagrid("getRowIndex", v)
                    indexRows.push(indexRow)
                })
                indexRows.reverse()
                $.each(indexRows, function (i, v) {
                    $("#itb").datagrid("deleteRow", v)
                })
                materialCodeCache = []
                var rows = $("#itb").datagrid("getRows")
                $.each(rows, function (i, t) {
                    materialCodeCache.push(t.materialCode)
                })
            }
        }]
    })
}

function copy(type) {
    $("#itb").edatagrid("saveRow")
    let allRows = $("#itb").datagrid('getRows');
    for (let i = 0;i<allRows.length;i++){
        $("#itb").datagrid('endEdit', i);

    }
    for (let i = 0; i < allRows.length; i++) {
        $("#itb").datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}

/**
 * 提交
 * @param state 1暂存 2 提交
 * @returns {boolean}
 */
function saveDemo(state, call) {
    //供应商角色&提交
    if (isSupplier && (state === 2 || state === 3)) {
        if (!$(el.form).form('validate')) {
            topWin.layer.msg(commonMsg.msg2);
            return false;
        }
    }
    if (!isSupplier) {//工程师
        var supplierId = $(el.supplierId).val();
        if (!supplierId) {
            topWin.layer.msg('请选择供应商');
            return false;
        }

        var purchaseCode = $(el.purchaseGroupCode).combobox('getValue');
        if (!purchaseCode) {
            topWin.layer.msg('请选择采购组');
            return false;
        }
    }
    $("#itb").edatagrid("saveRow")
//需要校验数据
    var rows = $("#itb").edatagrid("getRows")
    if (rows.length === 0) {
        topWin.layer.msg('请添加物料信息');
        return false;
    }
    var tipMsg = []
    $.each(rows, function (i, v) {
        $.each(columns[0], function (ii, vv) {
            if (vv.title !== undefined && vv.editor != undefined) {
                if (v[vv.field] === '' || v[vv.field] === undefined) {
                    tipMsg.push('第' + (i + 1) + '行,' + vv.title + '不能为空')
                }
            }
        })
    })
    if (tipMsg.length > 0) {
        topWin.layer.msg(tipMsg.join("<br/>"))
        return false;
    }
    let postData = $(el.form).serializeJson()
    postData['state'] = state
    postData['fileIds'] = $("#fileIds").attr('data-fileIds')

    postData['supplierFileIds'] = $("#supplierFileIds").attr('data-fileIds')
    if (isSupplier) {
        if (!postData['supplierFileIds']) {
            topWin.layer.msg("请上传承认书")
            return false;
        }
    }
    postData['items'] = rows
    $.ajax({
        url: g.ctx + "pc/supplier/materialDemo/rest/save",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(postData),
        success: function (data) {
            call()
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

function openPcnChooseDialog() {

}



