

var editor = undefined
$(function () {

    initDict('pcn_subject,stock_deal,change_time_node,pcn_fileType');

    initMaterial();

    initFile();

    initColumns();

    initSubject();


});


function initColumns(){

    $('#supplierNo').textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            topWin.layer.open({
                title: "供应商选择",
                type: 2,
                area: ['650px', '550px'],
                content: g.ctx+'pc/contract/manage/page/choseSupplier?type=2',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if(name!=undefined&&code!=''){
                        $('#supplierNo').textbox('setValue',code);
                        $('#supplierName').textbox('setValue',name);
                        topWin.layer.close(index);
                    }else{
                        topWin.layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });



    $("#stockDeal").combobox({
        valueField: 'code',
        textField: 'name',
        data: getDictList("stock_deal"),
        editable: false,
        panelHeight: 'auto',
    })

    $("#changeTimeNode").combobox({
        valueField: 'code',
        textField: 'name',
        data: getDictList("change_time_node"),
        editable: false,
        panelHeight: 'auto',
        onSelect: function (data) {
            if (data.code === "2"){
                $('#changeStageEnd').datebox('setValue', '');
            }
        }
    })

    $("#sqeUserName").textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            var formData = $("#searchForm").serializeJson();
            // var purchaseGroupCode = formData.purchaseGroupCode
            // var purchaseGroupId = formData.purchaseGroupId
            var supplierFlag = formData.supplierFlag
            var roleCodes = "role_sqe";
            // var sqeUserNameDialogElement = openDialog("sqeUserNameDialog", g.ctx + "pc/sys/user/index?select=1&single=0" + "&purchaseGroupCode=" + purchaseGroupCode + "&supplierFlag=" + supplierFlag + "&purchaseGroupId=" + purchaseGroupId, {
            var sqeUserNameDialogElement = openDialog("sqeUserNameDialog", g.ctx + "pc/sys/user/index?select=1&single=0" + "&roleCodes=" + roleCodes + "&supplierFlag=" + supplierFlag, {
                title: "用户选择",
                width: '80%',
                height: '80%',
                cache: false,
                modal: true,
                border: false,
                draggable: false,
                shadow: false,
                onClose: function () {
                    sqeUserNameDialogElement.dialog('destroy');
                },
                buttons: [{
                    text: itablei8n.save,
                    handler: function () {
                        topWin.frames['sqeUserNameDialog'].chooseRow(function (rows) {
                            if(rows.length!=1){
                                topWin.layer.alert("请选中一条数据")
                            }else{
                                //数组得用rows[0]
                                $('#sqeUserName').textbox('setValue', rows[0].username);
                                $('#sqeUserId').val(rows[0].accountName);
                                sqeUserNameDialogElement.dialog('close');
                            }

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

//选择采购人员信息
    // $("#purchaseUserName").textbox({
    //     buttonText:'选择',
    //     iconCls:'icon-man',
    //     iconAlign:'left',
    //     onClickButton:function () {
    //         var formData = $("#searchForm").serializeJson();
    //         // var purchaseGroupCode = formData.purchaseGroupCode
    //         var supplierFlag = formData.supplierFlag
    //         var roleCodes = "business";
    //         var purchaseUserNameDialogElement = openDialog("purchaseUserNameDialog", g.ctx + "pc/sys/user/index?select=1&single=0" + "&roleCodes=" + roleCodes + "&supplierFlag=" + supplierFlag, {
    //         // var purchaseUserNameDialogElement = openDialog("purchaseUserNameDialog", g.ctx + "pc/sys/user/index?select=1&single=0" + "&purchaseGroupCode=" + purchaseGroupCode + "&supplierFlag=" + supplierFlag, {
    //             title: "用户选择",
    //             width: '80%',
    //             height: '80%',
    //             cache: false,
    //             modal: true,
    //             border: false,
    //             draggable: false,
    //             shadow: false,
    //             onClose: function () {
    //                 purchaseUserNameDialogElement.dialog('destroy');
    //             },
    //             buttons: [{
    //                 text: itablei8n.save,
    //                 handler: function () {
    //                     topWin.frames['purchaseUserNameDialog'].chooseRow(function (rows) {
    //                         if(rows.length!=1){
    //                             topWin.layer.alert("请选中一条数据")
    //                         }else{
    //                             $('#purchaseUserName').textbox('setValue', rows[0].username);
    //                             $('#purchaseUserId').val(rows[0].accountName);
    //                             purchaseUserNameDialogElement.dialog('close');
    //                         }
    //
    //                     });
    //                 }
    //             }, {
    //                 text: '关闭', iconCls: 'icon-cancel', handler: function () {
    //                     purchaseUserNameDialogElement.dialog('close');
    //                 }
    //             }]
    //         })
    //     }
    // })


}


function initSubject() {
    var param = {"subjectType": "pcn_subject"};
    let subjectDivs = getDictList("pcn_subject");
    if (subjectDivs) {
        for (var i = 0; i < subjectDivs.length; i++) {
            var html = "  <label class='my_protocol'> &nbsp;  &nbsp;&nbsp;  &nbsp;" + "<input class='input_agreement_protocol' style='width: 14px;height: 14px'    id='name'   name='subject' type='radio'  value='" + subjectDivs[i].code + "' ><span></span>&nbsp;  &nbsp;" + subjectDivs[i].name + " </label><br><br>";
            $("#subjectDiv").append(html);
        }
    }
}

function initMaterial() {
    $('#MaterialCol').datagrid({
        iconCls: 'icon-list',
        title: '',
        autoHeight: true,
        singleSelect: true,
        width: '100%',
        height: 250,
        title: '受影响物料明细'+ '<span style="color:red">  *  </span>' ,
        loadMsg: "数据加载中......",
        fit: false,
        columns: [[
            {
                field: 'materialCode',
                title: '物料编码',
                width: '33%',
                align: 'center'
            },
            {
                field: 'materialName',
                title: '物料描述',
                width: '67%',
                align: 'center'
            }
            // ,
            // {
            //     field: 'operator',
            //     title: '操作',
            //     width: '33%',
            //     align: 'center'
            // }
        ]],
        toolbar: [
            "-", {
                id: 'addMaterial',
                text: '新增',
                iconCls: 'icon-add',
                handler: function () {
                    addMaterial();
                }
            }, {
                text: '删除',
                id: 'btnMaterial',
                iconCls: 'icon-filter',
                handler: function (d) {
                    delMaterial();
                }
            }]
    })


    function addMaterial() {
        var selectMaterialElement = openDialog("selectMaterialDialog", g.ctx + 'pc/sys/product/select/dialog', {
            title: '选择物料',
            width: '80%',
            height: '75%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                selectMaterialElement.dialog('destroy');
            },
            buttons: [{
                text: '确定',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['selectMaterialDialog'].chooseRows(function (data) {
                        if(data.length>0){

                            var d = $("#MaterialCol").datagrid('getRows');
                            // let ps = $(el.tbMaterial).datagrid('getRows');
                            for (let i = 0; i < data.length; i++) {
                                let product = data[i];
                                let sameFlag = false;
                                for (let j = 0; j < d.length; j++) {
                                    if (product.materialCode === d[j].materialCode) {
                                        sameFlag = true;
                                        break;
                                    }
                                }
                                if (sameFlag) {
                                    continue;
                                }
                                $("#MaterialCol").datagrid('appendRow',data[0]);
                            }
                            selectMaterialElement.dialog('close');
                        }


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


    function delMaterial() {
        let row = $("#MaterialCol").datagrid('getSelected');
        if (!row) {
            layer.msg("请选中一条记录");
            return;
        }
        topWin.layer.confirm("是否删除", function (index) {
            var rowIndex = $("#MaterialCol").datagrid('getRowIndex', row);
            $("#MaterialCol").datagrid('deleteRow', rowIndex);
            topWin.layer.close(index);
        })
    }

}



function initFile() {

    $('#FileCol').datagrid({
        iconCls: 'icon-list',
        title: '',
        autoHeight: true,
        loadMsg: "数据加载中......",
        width: '100%',
        height: 250,
        title: '添加附件',
        fit: false,
        singleSelect: true,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'fileType',
                title: '文件类型',
                width: '40%',
                align: 'center',
                panelHeight: 'auto',
                formatter: function (value, row) {
                    let pcnFileType = getDictList("pcn_fileType");
                    if (pcnFileType) {
                        for (var i = 0; i < pcnFileType.length; i++) {
                            if (row.fileType == pcnFileType[i].code) {
                                return pcnFileType[i].name;
                            }
                        }
                    }
                    return '--';
                },
                editor: {
                    type: 'combobox',
                    required:true,
                    options: {
                        valueField: 'code',
                        textField: 'name',
                        data: getDictList("pcn_fileType"),
                        editable: false,
                        panelHeight: 'auto',
                    }
                }
            },
            {
                field: 'fileName',
                title: '插入附件',
                width: '60%',
                align: 'center',
                formatter: function (value, row, index) {
                    if (row.fileName) {
                        return '<a style="color: #108ee9" onclick="replyDownload(\'' + row.fileId + '\')">'+row.fileName+'</a>';
                    } else {
                        return '--'
                    }
                },
                editor: {
                    type: 'filebox',
                    options: {
                        editable: false,
                        buttonText: '选择文件',
                        onChange(e){
                            var fileName = $(this).filebox('getValue');
                            var files = $(this).next().find('input[type=file]')[0].files;
                            var formData = new FormData();
                            formData.append('files', files[0]);//默认的文件数据名为“Filedata”
                            var index_wait;
                            $.ajax({
                                url: g.ctx+'pc/sys/file/rest/upload/files', //单文件上传
                                type: 'POST',
                                processData: false,
                                contentType: false,
                                data: formData,
                                beforeSend: function(){
                                    index_wait = topWin.layer.load(0, {  //发送请求前调用load方法
                                        shade: [0.5, '#fff'],  //0.5透明度的白色背景
                                    });
                                },
                                complete: function () {
                                    topWin.layer.close(index_wait);
                                },
                                success: function (result) {
                                    let d = $('#FileCol').datagrid('selectRow', editor);
                                    let drow = d.datagrid("getRows");
                                    drow[editor].fileId = result[0].id;
                                    drow[editor].fileName = result[0].fileName;
                                    d.datagrid('updateRow', { index: editor, row: drow[editor]  });
                                    $("#FileCol").edatagrid("endEdit", editor);
                                    $("#FileCol").edatagrid('refreshRow',editor);
                                    topWin.layer.msg('上传成功', {icon: 1, title: '温馨提示'});
                                },
                                error: function (xhr, status, error) {
                                    topWin.layer.msg('文件上传失败', {icon: 2, title: '温馨提示'})
                                }
                            });
                        }
                    }
                },
            },
        ]],
        toolbar: [
            "-", {
                id: 'addFile',
                text: '新增',
                iconCls: 'icon-add',
                handler: function () {
                    addFile();
                }
            },{
                text: '删除',
                id: 'btnFile',
                iconCls: 'icon-filter',
                handler: function (d) {
                    delFile();
                }
            }],
        onSelect: function (index) {
            editor = index;
        }
    })


}


function addFile() {
    $('#FileCol').datagrid('appendRow', {fileId:'',fileType: '1', filePath: "", realName: "", url: "", fileTypeName: ""});
    editIndex = $('#FileCol').datagrid('getRows').length - 1;
    $('#FileCol').datagrid('selectRow', editIndex)
        .datagrid('beginEdit', editIndex);
}


function delFile(target) {

    let row = $("#FileCol").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    topWin.layer.confirm("是否删除", function (index) {
        var rowIndex = $("#FileCol").datagrid('getRowIndex', row);
        $("#FileCol").datagrid('deleteRow', rowIndex);
        topWin.layer.close(index);
    })

}


function getFileName(o){
    var pos=o.lastIndexOf("\\");
    return o.substring(pos+1);
}


function submitForm(status,call) {
    let b;
    if (!$("#searchForm").form('validate')) {
        return;
    }

    let formData = $("#searchForm").serializeJson();
    editIndex = $('#FileCol').datagrid('getRows').length - 1;
    var beforeChangeAttach = $("#beforeChangeAttachment").attr('data-fileIds')
    formData.beforeChangeAttachment = beforeChangeAttach
    var afterChangeAttach = $("#afterChangeAttachment").attr('data-fileIds')
    formData.afterChangeAttachment = afterChangeAttach
    $("input[name='subject']:checked").each(function (i, n) {
        var value = $(this).val();//
        formData.subjectValue = value;
    })
    if (formData.subjectValue=='') {
        topWin.layer.msg("请选择变更主题");
        return;
    }
    if (formData.beforeChangeAttachment === null || formData.beforeChangeAttachment === undefined || formData.beforeChangeAttachment === "") {
        topWin.layer.msg("请上传变更前附件");
        return;
    }
    if (formData.afterChangeAttachment === null || formData.afterChangeAttachment === undefined || formData.afterChangeAttachment === "") {
        topWin.layer.msg("请上传变更后附件");
        return;
    }
    let changeTimeNode = $("#changeTimeNode").combobox('getValue');
    let changeStageTime = $("#changeStageTime").datebox('getValue');
    let changeStageEnd = $("#changeStageEnd").datebox('getValue');
    if (changeTimeNode==1 && (changeStageTime=='' || changeStageEnd=='')) {
        topWin.layer.msg("请填写阶段性变更时间范围!");
        return;
    }
    if (changeTimeNode==2&&changeStageTime=='') {
        topWin.layer.msg("请填写阶段性变更时间开始时间!");
        return;
    }
    var materialRows = $("#MaterialCol").datagrid("getRows");
    if(materialRows.length <= 0){
        topWin.layer.msg("请添加受影响物料明细数据!");
        return;
    }

    let FileColRows = $('#FileCol').datagrid('getRows');

    if ($("#searchForm").form('validate')) {
        for (var i=0;i<FileColRows.length;i++) {
            $('#FileCol').datagrid('endEdit', i);
        }
        FileColRows = $('#FileCol').datagrid('getRows');

        formData.status = status ;
        formData.materialRows=JSON.stringify(materialRows);
        formData.FileColRows=JSON.stringify(FileColRows)
        let loadindex = topWin.layer.load();
        $.ajax({
            url: g.ctx+'pc/order/pcn/rest/save/form',
            type: 'POST',
            async: false,
            data: formData,
            success: function (res) {
                topWin.layer.alert("保存成功!", {icon: 1}, function (idx) {
                    call() ;
                    topWin.layer.close(loadindex);
                    topWin.layer.close(idx);
                });
            },
            error: function (res) {
                topWin.layer.close(loadindex);
                topWin.layer.alert(res.responseJSON.message, {icon: 2});
            }
        });
    }

    return b;
}

function replyDownload(fileId){
    window.location.href = g.ctx+'pc/sys/file/rest/download/'+fileId;
}