/**
 * jiw
 * 2019.01.21
 * 工作组
 */
 import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE,UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_INTERFACE_SERVICE} from '@/config/serviceSettings.js';
 import { getSelectGJ, querySysPicture } from '@/utils/prolog.ajax.js';
export default () => {
    var userinfo = {
    p_id: '',
    p_username: '',
    p_workernumber: '',
    p_nickname: '',
    p_phone: null,
    p_email: null,
    p_companyid: '',
    p_enterpriseid: '',
    p_organizationid: '',
    p_companyname: '',
    p_orgname: '',
    p_enterprisename: '',
    p_usertype: '',
    p_lastlogindate: '',
    p_lastmodipassdate: null,
    p_validdate: '',
    p_import_batchno: null,
    p_data_source: null,
    forceModifyPasswdFlag: false,
    vehicle: null,
  }
    var userTable = {
        columns: [
            { id: "p_id", name: "id", type: "ro", width: "130", hidden: true },
            { id: "p_workernumber", name: "工号", type: "ro" },
            { id: "p_nickname", name: "人员名称", type: "ro" },
            { id: "p_companyname", name: "所属仓", type: "ro" }
        ],
        multiselect: false,
        toolbar: [
            { type: "settings", position: "label-left", width: 300, labelWidth: 80 },
            {
                type: "block", id: "bk", blockOffset: 0, list: [
                    { type: "input", name: "search", label: "人员编号/名称:", width: 190 },
                    { type: "newcolumn", offset: 30 },
                    { type: "button", name: "querycarr", value: "查询" }, { type: "newcolumn" },
                    { type: "button", name: "car_Reset", className: " normal", value: "重置" }, { type: "newcolumn" }]
            }],
        imagePath: "/prologui/dist/images/PlgGrid",
        url: "/users/users/operators",//数据接口
        type: "post",//数据提交方式，默认为get
        params: {},//查询提交参数，分页参数默认为pageNum,pageSize
        page: true, //是否启用分页
        pagebar: { type: "simple" },
        totalCount: "totalCount" //总记录数字段，默认totalCount
    };
    //库别
    var warehouse = [];
    var rsp_businesstype = [], rsp_worktype = [], rsp_packcode = [];
    if (userinfo != null) {
        userinfo = JSON.parse(userinfo);
    }
    var par = [{ "branchid": userinfo.p_companyid }];
    utilSyncAjaxGJ("/basic/area/sub-list", "post", JSON.stringify(par), function (data) {
        warehouse.push({ "value": "", "text": "" });
        data.data.forEach(t => { warehouse.push(t); });
    }, "application/json");
    //获取下拉框
    getSelectGJ([{ "objectcode": "businesstype" }, { "objectcode": "was_worktype" }, { "objectcode": "packcode" }], function (data) {
        bindRefdata(rsp_businesstype, data.data.businesstype, true);
        bindRefdata(rsp_worktype, data.data.was_worktype, true);
        bindRefdata(rsp_packcode, data.data.packcode, true);
    });
    var grid = null, operType = 0, form1;
    var param = { pageNum: 1, pageSize: 10 };
    //滑屏
    var carousel = layui.carousel;
    var car = carousel.render({
        elem: "#workAreaSet_grid",
        autoplay: false,
        index: 0,
        arrow: "none",
        indicator: "none",
        anim: "fade",
        width: "100%", //设置容器宽度
        height: "100%"
    });
    function changePanel(name) {
        car.slide(name);
    }
    //返回主页面
    $("#workAreaSet_btn_back").click(function () {
        changePanel("workAreaSet_grid_01");
        return false;
    });
    gridInit();
    function gridInit() {
        var workAreaSet_opt = {
            skin: "card",
            rowId: "itemid",
            columns: [
                { id: "workid", name: "ID", type: "ro", hidden: true, width: 110 }, // 主键，必须是唯一，放在第一行
                { id: "nickname", name: "人员名称", type: "ro", width: 110 },
                { id: "workernumber", name: "工号", type: "ro", width: 110 },
                {
                    id: "businesstype", name: "业务类型", type: "ro", width: 110, render: function (v) {
                        return Prolog.getNameByID(rsp_businesstype, v);
                    }
                },
                {
                    id: "worktype", name: "作业类型", type: "ro", width: 110, render: function (v) {
                        return Prolog.getNameByID(rsp_worktype, v);
                    }
                },
                {
                    id: "workarea", name: "作业区域", type: "ro", width: 110, render: function (v) {
                        return Prolog.getNameByID(warehouse, v);
                    }
                },
                { id: "priority", name: "优先级", type: "ro", width: 110 },
                {
                    id: "packcode", name: "包装方式", type: "ro", width: 110, render: function (v) {
                        return Prolog.getNameByID(rsp_packcode, v);
                    }
                },
                { id: "personid", name: "人员id", type: "ro", hidden: true, width: 110 },
                { id: "createdate", name: "创建时间", type: "ro", width: 110, hidden: true },
                { id: "createby", name: "创建人", type: "ro", width: 110, hidden: true },
                { id: "branchid", name: "仓号", type: "ro", width: 110, hidden: true },
                { id: "remark", name: "备注", type: "ro", width: 50 },
                {
                    id: "op", name: "操作", type: "button", align: "center", width: 200, render: function () {
                        return "详情^workAreaSet_detailClick,修改^workAreaSet_editClick,复制^workAreaSet_copy,删除^workAreaSet_deleteClick";
                    }
                }
            ],
            multiselect: true,
            fixedLast: true,
            toolbar: [
                { type: "input", name: "personcodenamehrno", label: "查询条件:", inputWidth: 300, placeholder: "人员名称/工号" }, { type: "newcolumn" },
                { type: "button", name: "searchBtn", value: "查询", offsetLeft: 10 }, { type: "newcolumn" },
                { type: "button", name: "refreshBtn", className: "normal", value: "重置" }, { type: "newcolumn" },
                { type: "button", name: "exportBtn", width: 70, className: "plg-toolbar-right", value: "<i class='layui-icon layui-icon-download-circle'></i>导出" }, { type: "newcolumn" },
                { type: "button", name: "addBtn", className: "plg-toolbar-right", value: "<i class='layui-icon layui-icon-add-1'></i>添加" }, { type: "newcolumn" }
            ],
            pagebar: {
                buttons: [
                    { text: "删除", className: "layui-btn-danger", name: "delete" }
                ]
            },
            imagePath: "/prologui/dist/images/PlgGrid",
            url: "/basic/workgrp/list",//数据接口
            type: "post",//数据提交方式，默认为get
            params: JSON.stringify(param),//查询提交参数，分页参数默认为pageNum,pageSize
            contentType: "application/json",
            page: true, //是否启用分页
            totalCount: "totalCount" //总记录数字段，默认totalCount
        };
        //分页参数 pageSize pageNum
        grid = new PlgGrid(workAreaSet_opt);
        grid.renderTo("workAreaSet_grid_01");
        grid.loadData();

        //工具栏键盘事件
        grid.getToolBarForm().attachEvent("onKeyDown", function (inp, ev) {
            if (ev.key == "Enter") {
                let fdata = grid.getToolBarForm().getFormData();
                grid.setParams(JSON.stringify(fdata));
                grid.reload();
            }
        });

        grid.attachToolBarEvent("onButtonClick", function (name) {
            if (name == "searchBtn") { // 查询
                let fdata = grid.getToolBarForm().getFormData();
                grid.setParams(JSON.stringify(fdata));
                grid.reload();
            }
            else if (name == "addBtn") { // 添加
                addworkAreaSet();
            }
            else if (name == "refreshBtn") { // 重置
                grid.getToolBarForm().clear();
                let fdata = grid.getToolBarForm().getFormData();
                fdata.consignname = "";
                grid.setParams(JSON.stringify(fdata));
                grid.reload();
            }
            else if (name == "exportBtn") {
                unfilledWorktime_export();
            }
        });

        //分页栏按钮事件
        grid.attachPageBarEvent(function (name) {
            if (name == "delete") {
                let rowId = grid.getCheckedIds();
                let rowIds = rowId.split(",");
                let checkedIds = [];
                rowIds.forEach(v => {
                    checkedIds.push(
                        { workid: v }
                    );
                });
                Prolog.delGridRowData(grid, "/basic/workgrp/delete", "post", "application/json", JSON.stringify(checkedIds), true);
            }
        });

        // 双击行
        grid.on("onRowDblClicked", function () {
            workAreaSet_detailClick(grid.getSelectedRowId(), grid.getSelectedRowData());
        });
    }


    //主界面导出事件
    function unfilledWorktime_export() {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        if (grid.getRowsNum() <= 0) {
            PlgDialog.close(pload);
            PlgDialog.msg("没有要导出的数据");
            return;
        }
        let url = "/basic/workgrp/export";
        let name = "工作组" + Prolog.formatDate(new Date(), "%YY%MM%DD") + ".xls";
        let p = grid.getToolBarForm().getFormData();
        Prolog.exportFile(url, name, "", "get", p);
        PlgDialog.close(pload);

    }


    //添加
    function addworkAreaSet() {
        operType = 0;
        let str = "<div class=\"layui-col-lg12\" id=\"workAreaSet_grid_add_content\"></div>";
        $("#workAreaSet_grid_sub").html(str);
        workAreaSetFormInit(0, {});
        changePanel("workAreaSet_grid_01_edit");
    }
    //保存操作
    $("#btn_save_workAreaSet").click(function () {
        let fd = form1.getFormData();
        if (fd.remark.length > 30) {
            layer.msg("备注长度不能超过30");
            return;
        }

        if (fd.buyername1 == null || fd.buyername1 == "" || fd.buyername1 == "[]") {
            PlgDialog.msg("工号不能为空");
            return;
        }

        let b = form1.validate();
        if (!b) return;

        if (fd.businesstype == "2011" && fd.workarea == "") {
            PlgDialog.msg("作业区域不能为空");
            return;
        }

        if (operType === 0) {
            save_workAreaSet(grid, "/basic/workgrp/batch-create", "post", "application/json", JSON.stringify([fd]));
        }
        else if (operType === 1) {
            save_workAreaSet(grid, "/basic/workgrp/batch-update", "post", "application/json", JSON.stringify([fd]));
        }
    });
    //表单
    function workAreaSetFormInit(ntype, rdata) {
        let tit = "新增工作组";
        let rediv = "workAreaSet_grid_sub";
        $("#btn_save_workAreaSet").show();
        if (ntype === 1) {
            tit = "工作组 [" + rdata.workernumber + "] 信息修改";
        }
        else if (ntype === 2) {
            tit = "工作组 [" + rdata.workernumber + "] 信息查看";
            $("#btn_save_workAreaSet").hide();
        }
        $("#workAreaSet_span_title").html(tit);
        $("#" + rediv).html("");
        let formcfg = {
            renderer: rediv,
            items: [
                { type: "settings", inputWidth: 200, width: "*", labelWidth: 80, position: "label-left", labelAlign: "left" },
                {
                    type: "block", width: "*",
                    list: [
                        { type: "hidden", name: "workid", value: "" },
                        { type: "hidden", name: "personid", value: "" },
                        { type: "hidden", name: "workernumber", label: "工号:", placeholder: "请双击选择" },
                        {
                            width: 200,
                            type: "selectTable",
                            placeholder: "请选择人员",
                            readonly: false,
                            table: userTable,
                            className: "oper_div",
                            tableWidth: 500,
                            tableHeight: 400,
                            fieldText: "p_workernumber",
                            fieldValue: "p_workernumber",
                            name: "buyername1",
                            label: "工号:",
                            listener: function (Grid) {
                                setMethod(Grid, userTable, function (data) {
                                    var fromdata = form1.getFormData();
                                    data = fromdata.buyername1.length == 2 ? "" : data;
                                    form1.setFormData({ personid: data.p_id, workernumber: data.p_workernumber, nickname: data.p_nickname });
                                });
                            }
                        },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "nickname", editable: false, validate: "NotEmpty", required: true, label: "人员名称:" },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "remark", label: "备注:" }

                    ]
                },
                {
                    type: "block", width: "*",
                    list: [
                        {
                            type: "combo", readonly: true, width: 200, name: "businesstype", label: "业务类型:", validate: "NotEmpty", required: true, options: rsp_businesstype
                        },
                        { type: "newcolumn", offset: 40 },
                        {
                            type: "combo", readonly: true, width: 200, name: "worktype", label: "作业类型:", validate: "NotEmpty", required: true, options: rsp_worktype
                        },
                        { type: "newcolumn", offset: 40 },
                        {
                            type: "combo", readonly: true, width: 200, name: "workarea", label: "作业区域:", options: warehouse
                        }
                    ]
                },
                {
                    type: "block", width: "*",
                    list: [
                        { type: "input", name: "priority", label: "优先级:", validate: "ValidInteger", maxLength: 4 },
                        { type: "newcolumn", offset: 40 },
                        {
                            type: "combo", readonly: true, width: 200, name: "packcode", label: "包装方式:", options: rsp_packcode
                        },
                        { type: "newcolumn", offset: 40 },
                        { type: "password", width: 200, name: "areaattr5", label: "密码:", hidden: true }
                    ]
                }

            ]
        };
        form1 = new PlgForm(formcfg);
        form1.setFormData(rdata);
        if (ntype == 1) {
            form1.getDForm().setText("buyername1", rdata.workernumber == undefined ? "" : rdata.workernumber);
            form1.getDForm().setItemValue("buyername1", "[\"" + rdata.workernumber + "\"]");
        }
        form1.disableItem("nickname");
        if (ntype === 2) {
            form1.disableAllItem();
        }
        if (rdata.areaattr5) {
            form1.showItem("areaattr5");
        }
        form1.getCombo("businesstype").attachEvent("onChange", function (n) {
            if (n == "3011") {
                form1.showItem("areaattr5");
                if (rdata.areaattr5)
                    form1.setItemValue("areaattr5", rdata.areaattr5);
                else
                    form1.setItemValue("areaattr5", "");
            }
            else {
                form1.hideItem("areaattr5");
                form1.setItemValue("areaattr5", "");
            }
        });
        $("input[name=\"workernumber\"]").dblclick(function () {
            let opts = {
                //terrace显示全部，card分页显示
                skin: "card",
                //renderer:"grid",
                columns: [
                    { id: "p_id", name: "货位id", type: "ro", width: "130", hidden: true },
                    { id: "p_workernumber", name: "工号", type: "ro" },
                    { id: "p_nickname", name: "人员名称", type: "ro" }
                ],
                multiselect: false,
                toolbar: [
                    { type: "settings", position: "label-left", width: 300, labelWidth: 80 },
                    {
                        type: "block", id: "bk", blockOffset: 0, list: [
                            { type: "input", name: "search", label: "用户名称:", width: 190 },
                            { type: "newcolumn", offset: 30 },
                            { type: "button", name: "querycarr", value: "查询" }, { type: "newcolumn" },
                            { type: "button", name: "car_Reset", className: " normal", value: "重置" }, { type: "newcolumn" }]
                    }],
                imagePath: "/prologui/dist/images/PlgGrid",
                url: "/users/users/list",//数据接口
                type: "post",//数据提交方式，默认为get
                params: {},//查询提交参数，分页参数默认为pageNum,pageSize
                page: true, //是否启用分页
                totalCount: "totalCount" //总记录数字段，默认totalCount
            };
            getEject(opts, function (data) {
                form1.setFormData({ personid: data.p_id, workernumber: data.p_workernumber, nickname: data.p_nickname });
                layer.closeAll();
            });
        });
    }
    //保存
    function save_workAreaSet(grid, url, type, contentType, formData) {
        //加载等待
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        let rep = null;
        Prolog.ajax({
            url: url,
            type: type,
            contentType: contentType,
            data: formData,
            success: function (data) {
                PlgDialog.close(pload);
                rep = data;
                if (data.success) {
                    PlgDialog.msg(data.message);
                    setTimeout(function () { changePanel("workAreaSet_grid_01"); grid.reload(); }, 10);
                }
                else {
                    setTimeout(() => { PlgDialog.alert(data.message == null ? "接口调用失败" : data.message); }, 300);
                }
            },
            error: function () { PlgDialog.close(pload); PlgDialog.msg("接口调用失败"); }
        });
        return rep;
    }
    function bindRefdata(rsp, data, addNsN) {
        if (addNsN) {
            rsp.push({ text: "", value: "" });
        }
        for (var i = 0; i < data.length; i++) {
            rsp.push({ text: data[i].text, value: data[i].value });
        }
    }
    window.workAreaSet_deleteClick = function (rid) {
        let checkedIds = [];
        checkedIds.push({
            workid: rid
        });
        Prolog.delGridRowData(grid, "/basic/workgrp/delete", "post", "application/json", JSON.stringify(checkedIds), true);
    };
    //修改
    window.workAreaSet_editClick = function (rid, rdata) {
        grid.selectRowById(rid);
        operType = 1;
        workAreaSetFormInit(1, rdata);
        changePanel("workAreaSet_grid_01_edit");
    };
    //复制
    window.workAreaSet_copy = function (rid, rdata) {
        grid.selectRowById(rid);
        operType = 0;
        rdata.workernumber = "";
        rdata.nickname = "";
        workAreaSetFormInit(0, rdata);
        changePanel("workAreaSet_grid_01_edit");
    };
    window.workAreaSet_detailClick = function (rid, rdata) {
        grid.selectRowById(rid);
        operType = 2;
        changePanel("workAreaSet_grid_01_edit");
        $("#btn_save_workAreaSet").hide();
        $("#workAreaSet_span_title").html("工作组 [" + rdata.workernumber + "] 信息查看");
        $("#workAreaSet_grid_sub").removeClass();
        new PlgPanel({
            renderer: "workAreaSet_grid_sub",
            skin: 2,
            header: {
                isShow: true,
                title: "基本信息"
            },
            defaultBody: {
                layoutCol: 3,
                valueBj: true,
                cols: [
                    [
                        { value: rdata.workernumber, label: "工号" },
                        { value: rdata.nickname, label: "人员名称" },
                        { value: Prolog.getNameByID(rsp_businesstype, rdata.businesstype), label: "业务类型" },
                        { value: Prolog.getNameByID(rsp_worktype, rdata.worktype), label: "作业类型" },
                        { value: Prolog.getNameByID(warehouse, rdata.workarea), label: "作业区域" },
                        { value: Prolog.getNameByID(rsp_packcode, rdata.packcode), label: "包装方式" },
                        { value: rdata.priority, label: "优先级" },
                        { value: rdata.remark, label: "备注" }
                    ],
                    [
                        { value: rdata.createby, label: "创建人" },
                        { value: rdata.createdate, label: "创建时间" }
                    ]
                ]
            }
        });
    };
};