/**
 * jiw
 * 2018.12.24
 * 门店
*/
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 rsp_brancid = [];
    var param = { locname: "", pageNum: 1, pageSize: 10 };
    var grid = null, operType = 0;

    utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/branch/dd-list", "get", {}, function (data) {
        rsp_brancid = data.data;
        for (var i = 0; i < rsp_brancid.length; i++) {
            rsp_brancid[i].text = rsp_brancid[i].locname;
            rsp_brancid[i].value = rsp_brancid[i].companyid;
        }
    });

    //滑屏
    var carousel = layui.carousel;
    carousel.render({
        elem: "#shop_grid",
        autoplay: false,
        index: 0,
        arrow: "none",
        indicator: "none",
        anim: "fade",
        width: "100%", //设置容器宽度
        height: "100%"
    });

    //返回主页面
    $(document).on("click", "#shop_btn_back", function () {
        $("#shop_grid_01_edit").css("display", "none");
        $("#shop_Template").css("display", "none");
        $("#shop_grid_01").css("display", "block");
        return false;
    });

    gridInit();

    function gridInit() {
        var shopOpts = {
            skin: "terrace",
            rowId: "itemid",
            columns: [
                { id: "companyid", name: "店id", type: "ro", hidden: true }, // 主键，必须是唯一，放在第一行
                { id: "companycode", name: "店编号", type: "ro" },
                { id: "locname", name: "店名称", type: "ro" },
                {
                    id: "areaid", name: "关联仓", type: "ro", render: function (v) { return Prolog.getNameByID(rsp_brancid, v); }
                },
                { id: "charger", name: "负责人", type: "ro" },
                {
                    id: "wxno", name: "优先级", type: "ro"
                },
                {
                    id: "status", name: "状态", type: "ro", render: function (v) {
                        if (v == "0") return Prolog.getCircle("yellow") + "锁定";
                        if (v == "1") return Prolog.getCircle("green") + "启用";
                    }
                },
                { id: "address", name: "地址", type: "ro" },
                { id: "contactman", name: "联系人", type: "ro" },
                { id: "tel", name: "联系电话", type: "ro" },
                { id: "extattr8", name: "最后修改人", type: "ro" },
                { id: "lastmodifydate", name: "最后修改时间", type: "ro" },
                {
                    id: "op", name: "操作", type: "button", align: "center", width: 180, render: function () {
                        return "详情^shop_detailClick,复制^shop_copyClick,修改^shop_editClick,删除^shop_deleteClick";
                    }
                }
            ],
            multiselect: true,
            fixedLast: true,
            toolbar: [
                { type: "input", name: "locname", label: "查询条件:", width: 300, placeholder: "店编号/店名称" }, { type: "newcolumn" },
                { type: "button", name: "searchBtn", value: "查询" }, { type: "newcolumn" },
                { type: "button", name: "refreshBtn", className: "normal", value: "重置" }, { type: "newcolumn" },
                { type: "button", name: "impandexpBtn", className: "plg-toolbar-right normal", value: "<i class='layui-icon layui-icon-download-circle'></i>导出" }, { type: "newcolumn" },
                // { type: "button", name: "download", className: "plg-toolbar-right normal", value: "<i class='layui-icon layui-icon-file-b'></i>下载模板" }, { type: "newcolumn" },
                { type: "button", name: "addBtn", className: "plg-toolbar-right", value: "<i class='layui-icon layui-icon-add-1'></i>新增" }, { type: "newcolumn" }
            ],
            formData: [],
            pagebar: {
                buttons: [
                    { text: "锁定", className: "layui-btn-normal", name: "lock" },
                    { text: "启用", className: "layui-btn-normal", name: "unlock" },
                    { text: "删除", className: "layui-btn-danger", name: "delete" }
                ]
            },
            imagePath: "/prologui/dist/images/PlgGrid",
            url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/getStore",//数据接口
            type: "post",//数据提交方式，默认为get
            params: JSON.stringify(param),//查询提交参数，分页参数默认为pageNum,pageSize
            contentType: "application/json",
            page: true, //是否启用分页
            totalCount: "totalCount" //总记录数字段，默认totalCount
        };
        //分页参数 pageSize pageNum
        grid = new PlgGrid(shopOpts);
        grid.renderTo("shop_grid_01");
        grid.loadData();

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

        //工具栏键盘事件
        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") { // 添加
                addshop({});
            }
            else if (name == "impandexpBtn") { // 导入
                //                $('#shop_grid_01').css("display", 'none');
                //                $('#shop_grid_01_edit').css("display", 'none');
                //                $('#shop_Template').css("display", 'block');
                exportEXcel();
            }
            else if (name == "download") { // 下载模板
                window.open("/download/工作台模板.xlsx");
            }
            else if (name == "refreshBtn") { // 重置
                grid.getToolBarForm().clear();
                let fdata = grid.getToolBarForm().getFormData();
                fdata.consignname = "";
                grid.setParams(JSON.stringify(fdata));
                grid.reload();
            }
        });

        utilImportGJ2("shop_Template1", "shopImportId", "shopExportId", "url", function () {
            $("#shop_grid_01").css("display", "block");
            $("#shop_grid_01_edit").css("display", "none");
            $("#shop_Template").css("display", "none");
        });
        grid.attachPageBarEvent(function (name) {
            if (name === "delete") {
                let rowId = grid.getCheckedIds();
                if (!rowId) return;
                let rowIds = rowId.split(",");
                let checkedIds = [];
                rowIds.forEach(v => {
                    checkedIds.push(
                        { companyid: v }
                    );
                });
                Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/batch-delete", "post", "application/json", JSON.stringify(checkedIds), true);
            }
            else if (name === "unlock" || name === "lock") {
                let rowId = grid.getCheckedIds();
                if (!rowId) return;
                let rowIds = rowId.split(",");
                let checkedIds = [];
                rowIds.forEach(v => {
                    checkedIds.push(
                        {
                            companyid: v,
                            status: name === "lock" ? "0" : "1"
                        }
                    );
                });
                Prolog.ajax({
                    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/storeStateChanges",
                    type: "post",
                    contentType: "application/json",
                    data: JSON.stringify(checkedIds),
                    success: function (data) {
                        if (data.success) {
                            grid.reload();
                        }
                    },
                    error: function () { PlgDialog.msg("接口调用失败"); }
                });
            }
        });
    }

    function exportEXcel() {

        let fdata = grid.getToolBarForm().getFormData();
        let obj = JSON.parse(JSON.stringify(fdata));
        let url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/exportStore/v1.0?locname=" + encodeURI(obj.locname);
        let token = localStorage.getItem("authorization");

        if (token == null || token == "") {
            PlgDialog.msg("登录状态异常，请重新登录！");
            window.location.href = "/menu?path=login";
            return;
        }

        let xhh = new XMLHttpRequest();
        xhh.open("get", url);
        xhh.setRequestHeader("Authorization", token);
        xhh.responseType = "blob";
        xhh.onreadystatechange = function () {
            if (xhh.readyState === 4 && xhh.status === 200) {
                var filename = "门店资料" + new Date().getTime() + ".xls";
                var blob = new Blob([xhh.response], { type: "text/xls" });
                var csvUrl = URL.createObjectURL(blob);
                var link = document.createElement("a");
                link.href = csvUrl;
                link.download = filename;
                link.click();
            }
        };
        xhh.send();

    }

    //添加
    function addshop(rdata) {
        operType = 0;
        let str = "<div class=\"layui-col-lg12\" id=\"shop_grid_add_content\"></div>";
        $("#shop_grid_sub").html(str);
        shopFormInit(0, rdata);
        $("#shop_grid_01_edit").css("display", "block");
        $("#shop_Template").css("display", "none");
        $("#shop_grid_01").css("display", "none");
    }

    //保存操作
    $("#btn_save_shop").click(function () {
        let b = form1.validate();
        if (!b) return;
        let fd = form1.getFormData();
        if (operType === 0) {
            save_shop(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/batch-create", "post", "application/json", JSON.stringify([fd]));
        }
        else if (operType === 1) {
            save_shop(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/updateStore", "post", "application/json", JSON.stringify(fd));
        }
    });

    //保存
    function save_shop(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 () {
                        $("#shop_grid_01_edit").css("display", "none");
                        $("#shop_Template").css("display", "none");
                        $("#shop_grid_01").css("display", "block");
                        grid.reload();
                    }, 10);
                }
                else {
                    setTimeout(() => { PlgDialog.alert(data.message == null ? "接口调用失败" : data.message); }, 300);
                }
            },
            error: function () { PlgDialog.close(pload); PlgDialog.msg("接口调用失败"); }
        });
        return rep;
    }

    //表单
    function shopFormInit(ntype, rdata) {
        var tit = "新增门店";
        var rediv = "shop_grid_sub";
        $("#btn_save_shop").show();
        if (ntype === 1) {
            tit = "门店 [" + rdata.locname + "] 信息修改";
        }
        else if (ntype === 2) {
            tit = "门店 [" + rdata.locname + "] 信息信息查看";
            $("#btn_save_shop").hide();
        }
        $("#shop_span_title").html(tit);
        $("#" + rediv).html("");
        var formcfg = {
            renderer: rediv,
            items: [
                { type: "settings", inputWidth: 200, width: "*", labelWidth: 80, position: "label-left", labelAlign: "left" },
                {
                    type: "block", width: "*",
                    list: [
                        { type: "hidden", name: "companyid", value: "" },
                        { type: "hidden", name: "companytype", value: "D" },
                        { type: "input", name: "companycode", label: "店编号:" },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "locname", label: "店名称:" },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "contactman", label: "联系人:" }

                    ]
                },
                {
                    type: "block", width: "*",
                    list: [
                        { type: "combo", readonly: true, name: "areaid", value: "", width: 200, label: "关联仓", options: rsp_brancid },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "charger", value: "", label: "负责人" },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "tel", label: "联系电话:" }
                    ]
                },
                {
                    type: "block", width: "*",
                    list: [
                        { type: "input", name: "wxno", value: "", label: "优先级" },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "address", label: "地址:" }
                    ]
                },
                {
                    type: "block", width: "*", hidden: ntype === 2 ? false : true,
                    list: [
                        { type: "input", name: "createby", value: "", label: "创建人" },
                        { type: "newcolumn", offset: 40 },
                        { type: "input", name: "lastmodifydate", value: "", label: "修改时间" }
                    ]
                }
            ]
        };
        form1 = new PlgForm(formcfg);
        form1.setFormData(rdata);
        if (ntype === 2) {
            form1.disableAllItem();
        }
    }

    window.shop_deleteClick = function (rid) {
        var checkedIds = [];
        checkedIds.push({
            companyid: rid
        });
        Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/batch-delete", "post", "application/json", JSON.stringify(checkedIds), false);
    };

    //编辑
    window.shop_editClick = function (rid, rdata) {
        grid.selectRowById(rid);
        operType = 1;
        shopFormInit(1, rdata);
        $("#shop_grid_01_edit").css("display", "block");
        $("#shop_Template").css("display", "none");
        $("#shop_grid_01").css("display", "none");
    };
    //复制
    window.shop_copyClick = function (rid, rdata) {
        grid.selectRowById(rid);
        rdata.companyid = null;
        addshop(rdata);
    };
    //详情
    window.shop_detailClick = function (rid, rdata) {
        grid.selectRowById(rid);
        operType = 2;
        $("#shop_grid_01_edit").css("display", "block");
        $("#shop_Template").css("display", "none");
        $("#shop_grid_01").css("display", "none");
        $("#btn_save_shop").hide();
        $("#shop_span_title").html("门店 [" + rdata.locname + "] 信息信息查看");
        $("#shop_grid_sub").removeClass();

        new PlgPanel({
            renderer: "shop_grid_sub",
            skin: 2,
            header: {
                isShow: true,
                title: "基本信息"
            },
            defaultBody: {
                layoutCol: 3,
                valueBj: true,
                cols: [
                    [
                        { value: rdata.companycode, label: "店编号" },
                        { value: rdata.locname, label: "店名称" },
                        { value: rdata.charger, label: "负责人" },
                        { value: Prolog.getNameByID(rsp_brancid, rdata.areaid), label: "关联仓" },
                        { value: rdata.status == "1" ? "启用" : "停用", label: "状态" },
                        { value: rdata.wxno, label: "优先级" },
                        { value: rdata.address, label: "地址" },
                        { value: rdata.contactman, label: "联系人" }

                    ],
                    [
                        { value: rdata.tel, label: "联系电话" },
                        { value: rdata.createby, label: "创建人" },
                        { value: rdata.extattr8, label: "最后修改人" },
                        { value: rdata.lastmodifydate, label: "修改时间" }

                    ]
                ]
            }
        });
    };
};