/**
 * zzx
 * 2020.05.25
 * 容器管理
    */
    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 carousel = layui.carousel;
  carousel.render({
    elem: "#transportContainerManage",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#transportContainerManage_main", "#transportContainerManage_edit"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $(document).on("click", "#transportContainerManage_edit_return", function () {
    changePanel("#transportContainerManage_main");
  });

  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "CONTAINER_TYPE" },
    { "objectcode": "MAINDATA_STATUS" }], function (data) {
      dataSelect = data.data;
    });

  var master_grid, edit_form_opts, edit_form;

  // 配送中心/站点table
  var branchTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "配送中心/站点编号", type: "ro" },
      { id: "companyname", name: "配送中心/站点名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "配送中心/站点编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyBranch",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // gps设备table
  var bindSmartDeviceGpsTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "smartDeviceId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "smartDeviceCode", name: "智能设备编号", type: "ro" },
      { id: "smartDeviceName", name: "智能设备名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "smartDeviceCode", label: "智能设备编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseSmartDevice/queryTBaseSmartDevice",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ status: "01", smartDeviceType: "01" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 冷链设备table
  var bindSmartDeviceColdTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "smartDeviceId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "smartDeviceCode", name: "智能设备编号", type: "ro" },
      { id: "smartDeviceName", name: "智能设备名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "smartDeviceCode", label: "智能设备编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseSmartDevice/queryTBaseSmartDevice",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ status: "01", smartDeviceType: "02" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "containerId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchName", name: "配送中心/站点地址", type: "ro" },
      { id: "containerCode", name: "容器编号", type: "ro" },
      { id: "containerName", name: "容器名称", type: "ro" },
      {
        id: "containerType", name: "容器类型", type: "ro", render: function (v) {
          return getSelectValue(dataSelect.CONTAINER_TYPE, v);
        }
      },
      { id: "bindSmartDeviceGps", name: "关联GPS设备", type: "ro" },
      { id: "bindSmartDeviceCold", name: "关联冷链设备", type: "ro" },
      {
        id: "status", name: "状态", type: "ro", render: function (v) {
          return getSelectValue(dataSelect.MAINDATA_STATUS, v);
        }
      },
      { id: "memo", name: "备注", type: "ro" },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function () {
          let result = "修改^transportContainerManage_edit,";
          if (rd.status == "1") {
            result += "停用^transportContainerManage_del";
          }
          else {
            result += "启用^transportContainerManage_del";
          }
          return result;
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          // {
          //   type: "selectTable",
          //   className: "layui-col-md3",
          //   placeholder: "请选择配送中心/站点",
          //   readonly: false,
          //   table: branchTable,
          //   tableWidth: 600,
          //   tableHeight: 500,
          //   fieldText: "companyname",
          //   fieldValue: "companyid",
          //   name: "branchidList",
          //   label: "配送中心/站点:",
          //   listener: function (Grid) {
          //     setMethod(Grid, branchTable, function () { });
          //   }
          // },
          { type: "input", className: "layui-col-md3", name: "branchId", label: "配送中心/站:" },
          { type: "input", className: "layui-col-md3", name: "containerCode", label: "容器编号:" },
          { type: "input", className: "layui-col-md3", name: "containerName", label: "容器名称:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "containerType", label: "容器类型:", options: [{ "value": "", "text": "" }].concat(dataSelect.CONTAINER_TYPE) },
          {
            type: "block", className: "layui-col-md2 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md1 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" }
            ]
          }
        ]
      }

    ],
    pagebar: {
      buttons: [
        { text: "<i class='layui-icon layui-icon-delete'></i>删除", className: "plg-btn-normal", name: "page_del" }
      ]
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseTransportContainer/queryTBaseTransportContainer", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("transportContainerManage_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        // request.branchId = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setText("branchidList", "");
        break;
      case "master_add":
        changePanel("#transportContainerManage_edit");
        $("#transportContainerManage_edit_form").html("");
        edit_form = new PlgForm(edit_form_opts);
        edit_form.enableItem("branchList");
        edit_form.enableItem("containerCode");
        edit_form.setFormData({ status: "1" });
        $("#transportContainerManage_edit_title").html("新增");
        break;
    }
  });
  // 单个删除
  window.transportContainerManage_del = function (rid, rdata) {
    let status = rdata.status == "1" ? "0" : "1";
    deleteTBaseTransportContainer([{ containerId: rid }], status);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { containerId: item };
    });
    deleteTBaseTransportContainer(list);
  });
  // 删除方法
  function deleteTBaseTransportContainer(idList, status) {
    let text = status == "1" ? "启用" : "停用";
    layer.open({
      title: text,
      content: "是否" + text + "？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseTransportContainer/deleteTBaseTransportContainer", type: "post", contentType: "application/json", data: JSON.stringify(idList),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              master_grid.reload();
              return true;
            }
            return false;

          }, error: function () { PlgDialog.close(pload); return false; }
        });
      }
    });
  }

  // 修改
  window.transportContainerManage_edit = function (rid, rdata) {
    changePanel("#transportContainerManage_edit");
    $("#transportContainerManage_edit_form").html("");
    edit_form = new PlgForm(edit_form_opts);
    edit_form.disableItem("branchList");
    rdata.branchList = JSON.stringify([rdata.branchId]);
    rdata.bindSmartDeviceGpsList = rdata.bindSmartDeviceGps ? JSON.stringify([rdata.bindSmartDeviceGps]) : "[]";
    rdata.bindSmartDeviceColdList = rdata.bindSmartDeviceCold ? JSON.stringify([rdata.bindSmartDeviceCold]) : "[]";
    edit_form.setFormData(rdata);
    edit_form.setText("branchList", rdata.branchName || "");
    edit_form.setText("bindSmartDeviceGpsList", rdata.bindSmartDeviceGps || "");
    edit_form.setText("bindSmartDeviceColdList", rdata.bindSmartDeviceCold || "");
    edit_form.disableItem("containerCode");
    $("#transportContainerManage_edit_title").html("修改");
  };

  // 详情form
  edit_form_opts = {
    renderer: "transportContainerManage_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择配送中心/站点",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "branchList",
            label: "配送中心/站点:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { companycode } = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify({ companycode, companytype: "S" }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  branchId: isSelected ? sdata.companyid : "",
                  branchName: isSelected ? sdata.companyname : ""
                });
              }
            }
          },
          { type: "hidden", name: "branchId", label: "配送中心/站点id:" },
          { type: "hidden", name: "branchName", label: "配送中心/站点名称:" },
          { type: "input", className: "layui-col-md3", name: "containerCode", label: "容器编号:", required: true },
          { type: "input", className: "layui-col-md3", name: "containerName", label: "容器名称:", required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", name: "containerType", label: "容器类型:", options: dataSelect.CONTAINER_TYPE, readonly: true, required: true },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择关联GPS设备",
            readonly: false,
            table: bindSmartDeviceGpsTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "smartDeviceCode",
            fieldValue: "smartDeviceCode",
            name: "bindSmartDeviceGpsList",
            label: "关联GPS设备:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { smartDeviceCode } = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify({ smartDeviceCode, status: "01", smartDeviceType: "01" }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  bindSmartDeviceGps: isSelected ? sdata.smartDeviceCode : ""
                });
              }
            }
          },
          { type: "hidden", name: "bindSmartDeviceGps", label: "关联GPS设备code:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择关联冷链设备",
            readonly: false,
            table: bindSmartDeviceColdTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "smartDeviceCode",
            fieldValue: "smartDeviceCode",
            name: "bindSmartDeviceColdList",
            label: "关联冷链设备:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var { smartDeviceCode } = Grid.getToolBarForm().getFormData();
                      Grid.setParams(JSON.stringify({ smartDeviceCode, status: "01", smartDeviceType: "02" }));
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  bindSmartDeviceCold: isSelected ? sdata.smartDeviceCode : ""
                });
              }
            }
          },
          { type: "hidden", name: "bindSmartDeviceCold", label: "关联冷链设备code:" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", name: "status", label: "状态:", options: dataSelect.MAINDATA_STATUS, readonly: true, required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "memo", label: "备注:", rows: 3 },
          { type: "hidden", name: "containerId", label: "容器id:" }
        ]
      }
    ]
  };

  // 保存
  $(document).on("click", "#transportContainerManage_edit_save", function () {
    let feik = edit_form.validate();
    if (!feik) return;
    let formData = edit_form.getFormData();
    if (!formData.branchId) {
      layer.msg("请选择配送中心/站点");
      return false;
    }
    delete formData.branchList;
    delete formData.bindSmartDeviceGpsList;
    delete formData.bindSmartDeviceColdList;
    let url = $("#transportContainerManage_edit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseTransportContainer/addTBaseTransportContainer" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseTransportContainer/updateTBaseTransportContainer";
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type: "post", contentType: "application/json", data: JSON.stringify(formData),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          changePanel("#transportContainerManage_main");
          master_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};