/**
 *  view/pc/order/delivery/appointmentPurchase/appointment.ftl
 *  预约送货的供应商配置新增编辑
 */

let el = {
        id: '#id',
        form: '#form',
        viewType: '#viewType',
        ids: '#ids',
        factoryCode: "#factoryCode",
        factoryName: "#factoryName",
        dockerCode: "#dockerCode",
        dockerName: "#dockerName",
        limitDate: '#limitDate',
        appointmentDate: '#appointmentDate',
        appointmentTimeId: '#appointmentTimeId',
        supplierCode: '#supplierCode',
        tb: '#tb',
        bodyHeight: document.documentElement.clientHeight,
    },
    limitDate = $(el.limitDate).val(),
    ids = $(el.ids).val(),
    viewType = $(el.viewType).val();


$(function () {
    $(el.dockerCode).combogrid({
        panelWidth: 450,
        idField: 'dockerCode',
        textField: 'dockerName',
        prompt: '-- 请选择 --',
        editable: false,
        url: g.ctx+'pc/order/appointmentDocker/rest/listAll',
        columns: [[
            {field: 'dockerCode', title: '卸货点编码', width: 60},
            {field: 'dockerName', title: '卸货点名称', width: 100},
            {field: 'factoryCode', title: '工厂编码', width: 100},
            {field: 'factoryName', title: '工厂名称', width: 200}
        ]],
        onSelect: function (value) {
            var g = $(el.dockerCode).combogrid('grid');
            var r = g.datagrid('getSelected');
            $(el.factoryName).textbox('setValue', r.factoryName);
            $(el.factoryCode).val(r.factoryCode);
            $(el.dockerName).val(r.dockerName);
            initCombobox();

            var rows = $(el.tb).datagrid('getRows');
            if (rows.length > 0 && viewType === "1") {
                $(el.tb).datagrid('loadData', []);
            }
        }
    });


    laydate.render({
        elem: '#appointmentDate',
        showBottom: false,
        min: 0,
        calendar: true,
        max: Number(limitDate),
        done: function (value, date, endDate) {
            console.log(value); //得到日期生成的值，如：2017-08-18
            console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            initCombobox();
        }
    });

    loadTable();

    initCombobox();
});

function initCombobox() {
    var dockerCode = $(el.dockerCode).val();
    var appointmentDate = $(el.appointmentDate).val();
    if (dockerCode && appointmentDate) {
        $(el.appointmentTimeId).combobox({
            valueField: 'id',
            textField: 'rangeTime',
            url: g.ctx+"pc/order/appointmentTime/rest/selector",
            editable: false,
            prompt: '请先选择卸货点和预约日期',
            panelHeight: 'auto',
            onBeforeLoad: function (param) {
                var dockerCode = $(el.dockerCode).val();
                var factoryCode = $(el.factoryCode).val();
                param.dockerCode = dockerCode;
                param.factoryCode = factoryCode;
                if (appointmentDate) {
                    param.week = moment(appointmentDate).days() + 1;
                }
            },
        });
    }
}


/**
 * 加载表格
 */
function loadTable() {
    let searchHeight = $(el.form).outerHeight();
    let pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    var toolbar = [];
    if (viewType === '1') {
        toolbar = [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addPurchaseDetails();
                }
            }, '-', {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteRow();
                }
            }
        ];
    }

    $(el.tb).datagrid({
        iconCls: 'icon-list',
        title: '采购订单明细',
        loadMsg: '数据加载中......',
        url: g.ctx+"pc/order/appointmentPurchase/rest/list",
        height: 500,
        singleSelect: false,
        pagination: true,
        rownumbers: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            ids: ids,
            supplierCode: $(el.supplierCode).val(),
            viewType: viewType
        },
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'appointmentCode',
                    title: '预约编码',
                    width: 120,
                    hidden: viewType === "1",
                },
                {
                    field: 'appointmentDate',
                    title: '当前预约时间',
                    width: '160',
                    align: 'left',
                    hidden: viewType === "1",
                    formatter: function (value, row, index) {
                        if (value) {
                            return value + " " + row.appointmentStartTime + "-" + row.appointmentEndTime;
                        } else {
                            return value;
                        }
                    }
                },
                {
                    field: 'orderCode',
                    title: '采购订单',
                    width: 160,
                },
                {
                    field: 'itemNo',
                    title: '订单行号',
                    width: 100,
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 100,
                },
                {
                    field: 'materialName',
                    title: '物料名称',
                    width: 100,
                },
                {
                    field: 'unclearNum',
                    title: '未清数量',
                    width: 100,
                },
                {
                    field: 'deliveryDate',
                    title: '期望交期',
                    width: 100,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format('YYYY-MM-DD HH:mm:ss');
                        }
                        return '';
                    }
                },
                {
                    field: 'num',
                    title: '订单数量',
                    width: 100,
                },
                {
                    field: 'supReplyDeliverDate',
                    title: '供方回复交期',
                    width: 100,
                    editor: {type: 'datebox', options: {required: true}},
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format('YYYY-MM-DD');
                        }
                        return '';
                    }
                },
                {
                    field: 'supReplyDeliverNum',
                    title: '供方回复数量',
                    width: 100,
                    editor: {type: 'numberbox', options: {required: true}}
                },
                {
                    field: 'supReplyRemark',
                    title: '备注',
                    width: 160,
                    editor: 'textbox'
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 100,
                },
                {
                    field: 'dock',
                    title: '卸货点',
                    width: 100,
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 100,
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 100,
                },

                {
                    field: 'factoryName',
                    title: '工厂名称',
                    width: '120',
                    align: 'left',
                },
            ]
        ],
        onClickRow: function (index, row) {
            onClickRow(index, row)
        },
        toolbar: toolbar
    });
}

/**
 * 自动过滤卸货点不匹配的数据
 * (情景1：先excel导入 在选择采购订单)
 * (情景2：先选择再导入excel)
 * @param rows
 * @param data
 * @returns {[]}
 */
function checkDock(rows, data) {
    if (rows.length > 0) {
        var newSelectArr = [], tipArr = [];
        var dataKey = rows[0].factoryCode;
        for (let i = 0; i < data.length; i++) {
            if (data[i].factoryCode  !== dataKey) {
                newSelectArr.push(data[i]);
            } else {
                tipArr.push(data[i].orderCode+"_"+data[i].itemNo)
            }
        }
        if (tipArr.length > 0) {
            parent.layer.msg(tipArr.join(",") + "和现有的工厂不匹配，已自动过滤！");
        }
        data = newSelectArr;
    }
    return data;
}

/**
 * 选择采购订单明细行
 */
function addPurchaseDetails() {
    let dockerCode = $(el.dockerCode).val();
    if(!dockerCode){
        layer.alert("请选择卸货点");
        return;
    }
    $(el.tb).datagrid("acceptChanges");
    editIndex = undefined;
    parent.layer.open({
        title: '选择订单明细行数据',
        type: 2,
        area: ['90%', '85%'],
        content: g.ctx+'pc/order/purchaseOrderDetail/page/chosePurchaseDetail?singleSelect=0&supplierCode=' + $(el.supplierCode).val() +
            '&factoryCode=' + $(el.factoryCode).val(),
        btn: ['选择', '取消'],
        yes: function (index, layero) {
            var iframe = parent.window[layero.find('iframe')[0]['name']];
            iframe.chooseMuliteDetails(function (data) {
                var rows = $(el.tb).datagrid("getRows");
                data = checkDock(rows, data);
                array_remove_repeat(rows,data);
                parent.layer.close(index);
            });
        }
    });

}

/**
 * 添加
 * @param rows
 * @param data
 */
function array_remove_repeat(rows,data) { // 去重
    var r = [];
    for (var i = 0; i < data.length; i++) {
        var flag = true;
        var temp = data[i];
        for (var j = 0; j < rows.length; j++) {
            if (temp.supplierErpCode + temp.orderCode + temp.orderRow === r[j].supplierCode + r[j].orderCode + r[j].itemNo) {
                flag = false;
                break;
            }
        }
        if (flag) {
            r.push(temp);

            $(el.tb).datagrid('appendRow',{
                orderCode:data[i].orderCode,
                itemNo:data[i].orderRow,
                materialCode:data[i].materialCode,
                materialName:data[i].materialName,
                unclearNum:data[i].noClearNum,
                deliveryDate:data[i].requireDate,
                num:data[i].num,
                supReplyDeliverDate:data[i].replayRequireDate,
                supReplyDeliverNum:data[i].replayNum,
                supReplyRemark:data[i].replayRemark,
                currencyCode:data[i].currencyCode,
                dock:$(el.dockerCode).val(),
                supplierCode:data[i].supplierErpCode,
                supplierName:data[i].supplierName,
                factoryName:data[i].factoryName
            });
        }
    }
}

// 当前编辑的行
var editIndex = undefined;

// 验证当前编辑行 是否可以结束编辑（validateRow）
function endEditing() {
    if (editIndex == undefined) {
        return true;
    }
    if ($(el.tb).datagrid('validateRow', editIndex)) {
        $(el.tb).datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

// 点击行，触发编辑
function onClickRow(index, row) {
    if (viewType !== '1') {
        return
    }

    $(el.tb).datagrid("acceptChanges");
    if (editIndex != index) {
        if (endEditing()) {
            editIndex = index;
            $(el.tb).datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
        } else {
            $(el.tb).datagrid('selectRow', editIndex);
        }
    } else {
        editIndex = index;
        $(el.tb).datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
    }
}


// 删除bom组件编辑行
function deleteRow() {
    $(el.tb).datagrid("acceptChanges");
    editIndex = undefined;

    var rows = $(el.tb).datagrid('getSelections');
    for (var i = rows.length - 1; i >= 0; i--) {
        $(el.tb).datagrid('deleteRow', i);
    }
}


/**
 * 表单提交warehouseCode
 */
function submitForm(callback) {
    $(el.tb).datagrid("acceptChanges");
    editIndex = undefined;

    var validate = $(el.form).form('validate');
    if (!validate) {
        parent.layer.msg('请完善基础信息', {icon: 2});
        return false;
    }
    //
    // var pattern = /^[1-9]/d{3}-((0[1-9]{1})|(1[0-2]{1}))-((0[1-9]{1})|([1-2]{1}/d{1})|(3[0-1]{1}))$/;
    // var appointmetDate = $(elappointmentTimeId).combobox('getText');
    // if (!pattern.test(appointmetDate)) {
    //     parent.layer.msg('请选择时间段',{icon: 2})
    //     return false;
    // }


    var checkDateArr = [], checkNum = [];
    var rows = $(el.tb).datagrid('getRows');
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        if (!row.supReplyDeliverDate) {
            checkDateArr.push((i + 1));
        }

        if (!row.supReplyDeliverNum) {
            checkNum.push((i + 1));
        }
    }

    if (checkDateArr.length > 0) {
        parent.layer.msg("第" + checkDateArr.join(",") + "行的回复日期未填写", {icon: 2});
        return;
    }

    if (checkNum.length > 0) {
        parent.layer.msg("第" + checkNum.join(",") + "行的回复数据未填写", {icon: 2});
        return;
    }

    parent.layer.load(1);
    $.post(g.ctx+'pc/order/appointmentPurchase/rest/saveOrUpdate',
        {
            appointmentTimeId: $(el.appointmentTimeId).combobox('getValue'),
            appointmentDate: $(el.appointmentDate).val(),
            appointmentRecordIds: ids,
            detail: JSON.stringify(rows)
        },
        function (data) {
            callback(data)
        }).error(function (data) {
        let msg = JSON.parse(data['responseText'])['message'];
        parent.layer.msg('保存失败！ ' + msg);
    }).complete(function () {
        parent.layer.closeAll('loading');
    });
}