/**
 * zzx
 * 2021.08.31
 * 系统参数管理
    */
    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 master_grid, edit_form_opts, edit_form;
  var selectDetails; // 修改数据的明细

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#systemParameter",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#systemParameter_main", "#systemParameter_edit"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $("#systemParameter_edit_return").on("click", function () {
    changePanel("#systemParameter_main");
  });

  // 获取下拉框
  var codeEnums = {
    SCHEDULING_MODE: { text: "运输调度模式", value: "SCHEDULING_MODE", memo: "运输调度模式，选择【预约调度】则系统走预约+运输业务流程；选择【运输调度】则系统没有预约功能，走运输调度业务流程。" },
    IS_EMPTY_LEAVE: { text: "是否允许空车放行", value: "IS_EMPTY_LEAVE", memo: "是否允许空车放行，选择允许则【叫号登记】界面可操作【空车放行】；选择不允许则【叫号登记】界面【空车放行】不可操作。" },
    FREE_PARKINGHOURS: { text: "免费停车时长", value: "FREE_PARKINGHOURS", memo: "免费停车时长，单位为分钟，例如：填120，则车辆进场120分钟后开始收费。" },
    IS_DRIVER_NUMBER: { text: "司机到场是否自动取号", value: "IS_DRIVER_NUMBER", memo: "司机到场是否自动取号，如设置自动取号，司机做到场登记时系统自动为司机做取号操作，如未设置，司机需在门岗手动扫码取号。" },
    OPERABLE_WAREHOUSE: { text: "场内移动端操作范围", value: "OPERABLE_WAREHOUSE", memo: "场内移动端操作范围，单位为公里，例如：填写数值1，司机移动端在离当前仓库1公里内才可操作到场登记。" },
    WHETHER_CALL: { text: "是否启用自动叫号", value: "WHETHER_CALL", memo: "是否启用自动叫号，如设置启用，月台空闲时自动根据优先策略叫号已取号车辆。" },
    WAITINGTIME_CALL: { text: "叫号等待时长", value: "WAITINGTIME_CALL", memo: "叫号等待时长，即叫号后等待的时间，单位为分钟，只能填写正整数，不可为0，填0时默认改为60，例如：填30，即为叫号后等待30分钟，未到则叫下一个号。" },
    IS_INTELLIGENT_SCHEDULING: { text: "是否智能调度", value: "IS_INTELLIGENT_SCHEDULING", memo: "是否智能调度，选择【人工调度】则系统不使用智能调度算法；选择【智能调度】则系统使用智能调度功能。" },
    WAYBILL_DISPATCH_CONFIRMATION: { text: "运单下发节点", value: "WAYBILL_DISPATCH_CONFIRMATION", memo: "运单下发节点，全不选则运单不下发，选择节点则在对应节点下发运单，适用于对接外部系统时管理运单下发节点。" },
    REFRESHTIME_BOARD: { text: "看板刷新时长", value: "REFRESHTIME_BOARD", memo: "看板刷新时长，单位为秒，例如：填60，即为每60秒刷新一次，刷新时长不要低于10秒。" },
    //CERTIFICATE_EXPIRATION_WARNING: { text: "证件过期预警天数", value: "CERTIFICATE_EXPIRATION_WARNING", memo: "证件过期预警天数，单位为天，例如：填写数值60，则在证件到期时间前60天进行提醒。" }
  };


  // 查询省
  var provinceEnums = [];
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", "post", JSON.stringify({ "fatherid": "01" }), function (data) {
    provinceEnums = data.data;
    for (let x in provinceEnums) {
      provinceEnums[x].text = provinceEnums[x].keyvalue;
      provinceEnums[x].value = provinceEnums[x].zoneid;
    }
    provinceEnums.unshift({ "value": "", "text": "" });
  }, "application/json");

  // 配送中心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 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "配送中心编号:", width: 150 },
          { 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
  };
  // 配送中心table多选
  var branchTableCombo = {
    // 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: true,
    toolbar: [
      { type: "settings", position: "label-left", width: 200 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "配送中心编号:", width: 150 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" },
          { type: "newcolumn" },
          { type: "button", className: "btn-normal", name: "btn_close", 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
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "branchCode", name: "配送中心编号", type: "ro", align: "center" },
      { id: "branchName", name: "配送中心名称", type: "ro", align: "center" },
      {
        id: "op", name: "操作", type: "button", align: "center", render: function () {
          return "修改^systemParameter_edit,复制^systemParameter_copy,删除^systemParameter_del,详情^systemParameter_view";
        }
      }
    ],
    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: "branchCodeList",
            label: "配送中心:",
            listener: function (Grid) {
              setMethod(Grid, branchTable, function () { });
            }
          },
          {
            type: "block", className: "layui-col-md6 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-md3 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: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysParameter/query", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("systemParameter_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.branchCode = request.branchCodeList ? JSON.parse(request.branchCodeList)[0] : "";
        delete request.branchCodeList;
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setText("branchCodeList", "");
        break;
      case "master_add":
        changePanel("#systemParameter_edit");
        $("#systemParameter_edit_form").html("");
        editFormCreated();
        $("#systemParameter_edit_title").html("新增");
        $("#systemParameter_edit_save").show();
        break;
    }
  });
  // 单个删除
  window.systemParameter_del = function (rid) {
    auditNodeDelete({ branchCode: rid });
  };
  // 删除方法
  function auditNodeDelete(idList) {
    layer.open({
      title: "删除",
      content: "是否删除当前配送中心参数？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysParameter/delete", 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.systemParameter_edit = function (rid, rdata) {
    changePanel("#systemParameter_edit");
    $("#systemParameter_edit_form").html("");
    editFormCreated(rdata, "edit");
    $("#systemParameter_edit_title").html("修改");
    $("#systemParameter_edit_save").show();
  };

  // 复制
  window.systemParameter_copy = function (rid, rdata) {
    changePanel("#systemParameter_edit");
    $("#systemParameter_edit_form").html("");
    editFormCreated(rdata, "copy");
    $("#systemParameter_edit_title").html("复制");
    $("#systemParameter_edit_save").show();
  };

  // 详情
  window.systemParameter_view = function (rid, rdata) {
    changePanel("#systemParameter_edit");
    $("#systemParameter_edit_form").html("");
    editFormCreated(rdata, "view");
    $("#systemParameter_edit_title").html("详情");
    $("#systemParameter_edit_save").hide();
  };

  // 详情form
  edit_form_opts = {
    renderer: "systemParameter_edit_form",
    items: [
      { type: "settings", PoSingle: "label-left", labelWidth: 180 },
    //   {
        // type: "fieldset", name: "name1", label: "", list: [
            {
                type: "label",
                name: "labtext",
                className: "div_blockquote",
                labelWidth: "*",
                label: "<blockquote class='site-text layui-elem-quote'>配送中心</blockquote>"
            },
          {
            type: "block",
            list: [


              {
                type: "selectTable",
                width: 400,
                labelWidth: 80,
                placeholder: "请选择配送中心",
                readonly: false,
                table: branchTableCombo,
                tableWidth: 600,
                tableHeight: 500,
                fieldText: "companyname",
                fieldValue: ["companyid", "companyname"],
                name: "branchList",
                label: "配送中心:<span class='dhxform_item_required'>*</span>",
                listener: {
                  "init": function (Grid) {
                    // 注册按钮事件
                    Grid.attachToolBarEvent("onButtonClick", function (name) {
                      switch (name) {
                        case "querycarr":
                          var request = Grid.getToolBarForm().getFormData();
                          Grid.setParams(JSON.stringify(request));
                          Grid.reload();
                          break;
                        case "car_Reset":
                          Grid.getToolBarForm().clear();
                          break;
                        case "btn_close":
                          PlgDialog.closeAll();
                          break;
                      }
                    });
                  }
                }
              }
            ]
          },
        // ]
    //   },
    //   {
        // type: "fieldset", name: "name2", label: "预约调度设置", list: [
            {
                type: "label",
                name: "labtext",
                className: "div_blockquote",
                labelWidth: "*",
                label: "<blockquote class='site-text layui-elem-quote'>预约调度设置</blockquote>"
            },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "运输调度模式<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='SCHEDULING_MODE' title='" + codeEnums["SCHEDULING_MODE"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "radio", name: "SCHEDULING_MODE", value: "1", label: "预约调度:", labelAlign: "right" },
              { type: "newcolumn", offset: 30 },
              { type: "radio", name: "SCHEDULING_MODE", value: "2", label: "运输调度:", labelAlign: "right", checked: true }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "是否允许空车放行<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='IS_EMPTY_LEAVE' title='" + codeEnums["IS_EMPTY_LEAVE"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "radio", name: "IS_EMPTY_LEAVE", value: "1", label: "允许:", labelAlign: "right", checked: true },
              { type: "newcolumn", offset: 30 },
              { type: "radio", name: "IS_EMPTY_LEAVE", value: "0", label: "不允许:", labelAlign: "right" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "免费停车时长<i class='layui-icon layui-icon-about' nameid='FREE_PARKINGHOURS' title='" + codeEnums["FREE_PARKINGHOURS"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "input", name: "FREE_PARKINGHOURS", label: " ", width: 200, labelWidth: 100, validate: "NotNegativeNume" },
              { type: "newcolumn" },
              { type: "label", name: "", label: "（分钟）" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "司机到场是否自动取号<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='IS_DRIVER_NUMBER' title='" + codeEnums["IS_DRIVER_NUMBER"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "radio", name: "IS_DRIVER_NUMBER", value: "0", label: "不自动取号:", labelAlign: "right", checked: true },
              { type: "newcolumn", offset: 30 },
              { type: "radio", name: "IS_DRIVER_NUMBER", value: "1", label: "自动取号:", labelAlign: "right" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "场内移动端操作范围<i class='layui-icon layui-icon-about' nameid='OPERABLE_WAREHOUSE' title='" + codeEnums["OPERABLE_WAREHOUSE"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "input", name: "OPERABLE_WAREHOUSE", label: " ", width: 200, labelWidth: 100, validate: "NotNegativeNume" },
              { type: "newcolumn" },
              { type: "label", name: "", label: "（公里）" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "是否启用自动叫号<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='WHETHER_CALL' title='" + codeEnums["WHETHER_CALL"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "radio", name: "WHETHER_CALL", value: "1", label: "启用:", labelAlign: "right" },
              { type: "newcolumn", offset: 30 },
              { type: "radio", name: "WHETHER_CALL", value: "0", label: "不启用:", labelAlign: "right", checked: true }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "叫号等待时长<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='WAITINGTIME_CALL' title='" + codeEnums["WAITINGTIME_CALL"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "input", name: "WAITINGTIME_CALL", label: " ", width: 200, labelWidth: 100, validate: "NotNegativeNume,NotEmpty" },
              { type: "newcolumn" },
              { type: "label", name: "", label: "（分钟）" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "是否智能调度<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='IS_INTELLIGENT_SCHEDULING' title='" + codeEnums["IS_INTELLIGENT_SCHEDULING"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "radio", name: "IS_INTELLIGENT_SCHEDULING", value: "2", label: "人工调度:", labelAlign: "right", checked: true },
              { type: "newcolumn", offset: 30 },
              { type: "radio", name: "IS_INTELLIGENT_SCHEDULING", value: "1", label: "智能调度:", labelAlign: "right" }
            ]
          },
        // ]
    //   },
    //   {
        // type: "fieldset", name: "name3", label: "对接策略设置", list: [
            {
                type: "label",
                name: "labtext",
                className: "div_blockquote",
                labelWidth: "*",
                label: "<blockquote class='site-text layui-elem-quote'>对接策略设置</blockquote>"
            },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "运单下发节点<i class='layui-icon layui-icon-about' nameid='WAYBILL_DISPATCH_CONFIRMATION' title='" + codeEnums["WAYBILL_DISPATCH_CONFIRMATION"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "checkbox", name: "WAYBILL_DISPATCH_CONFIRMATION", value: "1", label: "派车确认:", labelAlign: "right" }
            ]
          },
        // ]
    //   },
    //   {
        // type: "fieldset", name: "name4", label: "系统时效设置", list: [
            {
                type: "label",
                name: "labtext",
                className: "div_blockquote",
                labelWidth: "*",
                label: "<blockquote class='site-text layui-elem-quote'>系统时效设置</blockquote>"
            },
          {
            type: "block",
            list: [
              { type: "label", name: "", label: "看板刷新时长<span class='dhxform_item_required'>*</span><i class='layui-icon layui-icon-about' nameid='REFRESHTIME_BOARD' title='" + codeEnums["REFRESHTIME_BOARD"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "input", name: "REFRESHTIME_BOARD", label: " ", width: 200, labelWidth: 100, validate: "NotNegativeNume,NotEmpty" },
              { type: "newcolumn" },
              { type: "label", name: "", label: "（秒）" }
            ]
          },
          /* {
            type: "block",
            list: [
              { type: "label", name: "", label: "证件过期预警天数<i class='layui-icon layui-icon-about' nameid='CERTIFICATE_EXPIRATION_WARNING' title='" + codeEnums["CERTIFICATE_EXPIRATION_WARNING"].memo + "'></i>" }
            ]
          },
          {
            type: "block",
            list: [
              { type: "input", name: "CERTIFICATE_EXPIRATION_WARNING", label: " ", width: 200, labelWidth: 100, validate: "NotNegativeNume" },
              { type: "newcolumn" },
              { type: "label", name: "", label: "（天）" }
            ]
          } */
        // ]
    //   }
    ]
  };
  // 创建form
  function editFormCreated(rdata, type) {
    edit_form = new PlgForm(edit_form_opts);

    if (rdata) {
      // 查询明细
      let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      Prolog.ajax({
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysParameter/queryByBranchCode", type: "post", contentType: "application/json", data: JSON.stringify({ branchCode: rdata.branchCode }),
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            let formData = {};
            selectDetails = res.data;
            res.data.forEach(item => {
              formData[item.parameterCode] = item.parameterValue;
            });
            if (type === "edit") { // 修改
              formData.branchList = JSON.stringify({ companyid: rdata.branchCode, companyname: rdata.branchName });
              edit_form.setText("branchList", rdata.branchName);
              edit_form.disableItem("branchList");
            }
            else if (type === "copy") { // 复制
              edit_form.enableItem("branchList");
            }
            else if (type === "view") { // 详情
              formData.branchList = JSON.stringify({ companyid: rdata.branchCode, companyname: rdata.branchName });
              edit_form.setText("branchList", rdata.branchName);
              // edit_form.disableItem("branchList");
              edit_form.disableAllItem();
            }
            edit_form.setFormData(formData);
            return true;
          }
                    return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });

    }
    else { // 新增
      edit_form.enableItem("branchList");
    }

    // 描述点击
    $(".layui-icon.layui-icon-about").on("click", function () {
      const nameid = $(this).attr("nameid");
      layer.alert(codeEnums[nameid].memo);
    });
  }

  // 保存
  $("#systemParameter_edit_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return;
    let formData = edit_form.getFormData();
    formData.branchList = formData.branchList ? JSON.parse(formData.branchList) : [];
    if (formData.branchList.length === 0) {
      layer.msg("请选择配送中心");
      return false;
    }

    let url, request;
    if ($("#systemParameter_edit_title").html() === "修改") {
      url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysParameter/update";
      selectDetails.forEach(item => {
        item.parameterValue = formData[item.parameterCode] || "0";
      });
      request = {
        details: selectDetails
      };
    }
    else {
      url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysParameter/save";
      let details = [];
      for (const key in codeEnums) {
        const element = codeEnums[key];
        details.push({
          parameterCode: element.value,
          parameterName: element.text,
          parameterValue: formData[element.value] || "0",
          memo: element.memo
        });
      }

      request = {
        branchCodes: formData.branchList.map(item => {
          return {
            branchCode: item.companyid,
            branchName: item.companyname
          };
        }),
        details
      };
    }

    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type: "post", contentType: "application/json", data: JSON.stringify(request),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          changePanel("#systemParameter_main");
          master_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};