
var editor = undefined
$(function () {

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

    initColumns();

    initSubject();

    initMaterial();


});


function initColumns(){
    //查看和审核所有控件只读
    // 设置所有 datetimebox 为只读模式
    $('.easyui-datetimebox').datetimebox('readonly', true);
    $('.easyui-datebox').datetimebox('readonly', true);

    // 设置所有 NumberBox 为只读模式
    $('.easyui-numberbox').numberbox('readonly', true);

    // 设置所有 TextBox 为只读模式
    // $('.easyui-textbox').textbox('readonly', true);

    // 设置所有 ComboBox 为只读模式
    $('.easyui-combobox').combobox('readonly', true);

    // $('input[type="radio"]').prop('disabled', true);
    //
    // $('.easyui-radiobutton').radiobutton('disable');

    $('#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',
    })


    $("#sqeUserName").textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            var sqeUserNameDialogElement = openDialog("sqeUserNameDialog", g.ctx + "pc/sys/user/index?select=1&single=0", {
                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 purchaseUserNameDialogElement = openDialog("purchaseUserNameDialog", g.ctx + "pc/sys/user/index?select=1&single=0", {
                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 initMaterial() {

    $("#FileCol").datagrid({
        iconCls: 'icon-list',
        url: g.ctx+'pc/order/pcn/files/rest/getFileList',
        autoHeight: true,
        loadMsg: "数据加载中......",
        width: '100%',
        height: 250,
        title: '添加附件',
        fit: false,
        singleSelect: false,
        queryParams: {appListId: $("#id").val()},
        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: '30%',
                align: 'center',
                formatter: function (value, row, index) {
                    if (row.fileName) {
                        return '<a style="color: #108ee9" onclick="replyDownload(\'' + row.fileId + '\')">'+row.fileName+'</a>';
                        // return getFileName(row.fileName) ;
                    } 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) {
                                    $("#FileCol").edatagrid("endEdit", editor);
                                    $("#FileCol").edatagrid('refreshRow',editor);
                                    let d = $('#FileCol').datagrid('selectRow', editor);
                                    let drow = d.datagrid("getRows");
                                    drow[editor].fileId = result[0].id;
                                    drow[editor].realName = getFileName(fileName);
                                    d.datagrid('updateRow', { index: editor, row: drow[editor]  });
                                    let a = $("#FileCol").datagrid("getRows")
                                    topWin.layer.msg('上传成功', {icon: 1, title: '温馨提示'});
                                },
                                error: function (xhr, status, error) {
                                    topWin.layer.msg('文件上传失败', {icon: 2, title: '温馨提示'})
                                }
                            });
                        }
                    }
                },
            },
            {
                field: 'options',
                title: '操作',
                width: '30%',
                align: 'center',
                formatter: function (value, row, index) {
                    if (row.fileName) {
                        // var fileSpan = '';
                        return  '<div class="file-content-span-preview"><a data-fileId="' + row.fileId + '" onclick="previewFileForm(this,' + JSON.stringify(row.fileName).replace(/\"/g, "'") + ')">预览</a></div>';
                    } else {
                        return '--'
                    }
                }
            },
        ]],
    })


    $("#MaterialCol").datagrid({
        iconCls: 'icon-list',
        url:g.ctx+'pc/order/pcn/material/rest/getMaterialList',
        autoHeight: true,
        width: '100%',
        height: 250,
        title: '受影响物料明细',
        loadMsg: "数据加载中......",
        queryParams: {appListId: $("#id").val()},
        fit: false,
        singleSelect: false,
        columns: [[
            {
                field: 'materialCode',
                title: '物料编码',
                width: '33%',
                align: 'center'
            },
            {
                field: 'materialName',
                title: '物料描述',
                width: '67%',
                align: 'center'
            }
        ]],
    })


    var id = $("#typeListId").val();
    $('#approvalList').datagrid({
        iconCls: 'icon-list',
        title: '',
        height: gridheight - 23,
        width: gridwidth,
        url: g.ctx+'pc/order/pcn/approv/rest/queryPcnApprovalByPage',
        pagination: true,
        singleSelect: true,
        idField: 'id',
        autoHeight: true,
        queryParams: {applyListId: id},
        loadMsg: "数据加载中......",
        fit: false,
        page: 1,
        pageSize: 10,
        columns: [[
            {
                field: 'type',
                title: '审批类型',
                width: '20%',
                align: 'center',
                formatter: function (type) {
                    if (type == 1) {
                        return '是否受理';
                    } else if (type == 2) {
                        return '是否同意';
                    }
                }
            },
            {
                field: 'result',
                title: '审批结果',
                width: '20%',
                align: 'center',
                formatter: function (result) {
                    if (result == 0) {
                        return '否';
                    } else if (result == 1) {
                        return '是';
                    } else if (result == 2) {
                        return '是，首批发货需要通知光迅';
                    }
                }
            },
            {
                field: 'remark',
                title: '说明',
                width: '20%',
                align: 'center'
            },
            {
                field: 'userName',
                title: '审批人',
                width: '20%',
                align: 'center'
            },
            {
                field: 'approveTime',
                title: '审批时间',
                width: '20%',
                align: 'center'
            }
        ]]
    })
}

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


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) {
                    $("#MaterialCol").datagrid('appendRow',data[0]);
                    var d = $("#MaterialCol").datagrid('getRows');
                    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 initSubject() {


    var param = {"subjectType": "pcn_subject"};
    let subjectDivs = getDictList("pcn_subject");
    var id = $("#id").val();
    var param = { "applayListId": id};
    $.ajax({
        type: 'POST',
        url: g.ctx+"pc/order/pcn/subject/rest/queryDetailDict",
        data: param,
        dataType: 'json',
        statusCode: {
            200: function (data) {
                let sub = data.subjectValue;
                for (var j = 0; j < subjectDivs.length; j++) {

                    if (sub.indexOf(subjectDivs[j].code) > -1) {
                        var html = " <label style='font-size: 12px;' class='my_protocol'> &nbsp;  &nbsp;&nbsp;  &nbsp;" + "<input class='input_agreement_protocol' id='name' name='subject' type='radio' value='" + subjectDivs[j].code + "' checked ><span></span>&nbsp;  &nbsp;" + subjectDivs[j].name + "(" + subjectDivs[j].name + ")" + "</label><br><br>";
                        $("#subjectDiv").append(html);
                    } else {
                        var html = "<label style='font-size: 12px;'  class='my_protocol'> &nbsp;  &nbsp;&nbsp;  &nbsp;" + "<input  <input class='input_agreement_protocol'id='name' name='subject' type='radio' value='" + subjectDivs[j].code + "'  ><span></span>&nbsp;  &nbsp;" + subjectDivs[j].name + "(" + subjectDivs[j].name + ")" + "</label><br><br>";
                        $("#subjectDiv").append(html);
                    }
                }
            },
            500: function () {
                layer.msg('初始化主题内容出现异常，请联系管理员');
                return;
            },
            400: function () {
                layer.msg('请检查是否配置主题内容');
                return;
            }
        }
    });


    // var param = {"subjectType": "pcn_subject"};
    // let subjectDivs = getDictList("pcn_subject");
    // console.log(subjectDivs);
    //
    // 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='checkbox'  value='" + subjectDivs[i].code + "' ><span></span>&nbsp;  &nbsp;" + subjectDivs[i].name + "(" + subjectDivs[i].name + ")" + " </label><br><br>";
    //         $("#subjectDiv").append(html);
    //     }
    // }
}


function addFile() {
    $('#FileCol').datagrid('appendRow', {fileId:'',fileType: '', 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 submitForm1(status,call) {
    let b;
    if (!$("#searchForm").form('validate')) {
        return;
    }
    let formData = $("#searchForm").serializeJson();
    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 submitForm(status,call) {
    let b ;
    if (!$("#searchForm").form('validate')) {
        return;
    }
    let formData = $("#searchForm").serializeJson();
    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=='') {
        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");
    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) {
                    topWin.layer.close(idx);
                    topWin.layer.close(loadindex);
                    call();
                });
            },
            error: function (res) {
                topWin.layer.close(loadindex);
                topWin.layer.alert(res.responseJSON.message, {icon: 2});
            }
        });
    }

    return b ;
}
