/**
 * zzx
 * 2022.01.20
 * 预警配置
 */
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE, SERVICE_PLATFORM_POWER_BASE, 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, edit_grid_opts, edit_grid;
  var userGJ = {
    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 carousel = layui.carousel;
  carousel.render({
    elem: "#earlyWarning",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%",
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#earlyWarning_main", "#earlyWarning_edit", "#earlyWarning_view"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $("#earlyWarning_edit_return").on("click", function () {
    changePanel("#earlyWarning_main");
  });
  $("#earlyWarning_view_return").on("click", function () {
    changePanel("#earlyWarning_main");
  });

  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "EARLY_WARNING_STATUS" },
    { "objectcode": "EARLY_WARNING_TYPE" },
    { "objectcode": "EARLY_WARNING_PUSH_METHOD" },
    { "objectcode": "EARLY_WARNING_UNIT" }
  ], function (data) {
    dataSelect = data.data;
  });
  let USER_TYPE = [
    { value: 'I', text: '内部员工(自有)' },
    { value: 'C', text: '客户' },
    { value: 'V', text: '供应商' },
    { value: 'H', text: '货主' },
    { value: 'S', text: '服务商(承运商)' },
    { value: 'D', text: '司机' },
    { value: 'M', text: '送货员' },
  ]

  // 客户弹窗
  var userTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "客户编码", type: "ro" },
      { id: "name", name: "客户名称", type: "ro" },
      { id: "shortName", name: "客户简称", type: "ro" },
      { id: "cargoOwnerName", name: "所属货主", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left" },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "customerCode", label: "客户编码:" },
          { type: "newcolumn" },
          { type: "input", name: "customerName", label: "客户名称:" },
          { type: "newcolumn" },
          { type: "input", name: "cargoOwnerName", label: "所属货主:" },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    multiselect: true,
    pagebar: { type: "simple" },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/queryCustomerPopup",
    type: "post",
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };
  // 工号弹窗
  let operator_Table = {
    columns: [
      { id: "id", name: "id", type: "ro", width: 100, hidden: true },
      { id: "nickname", name: "用户名称", type: "ro", width: 120 },
      { id: "username", name: "用户账号", type: "ro", width: "*" }
    ],
    toolbar: [
      { type: "settings", labelAlign: "left", labelWidth: 65 },
      { type: "input", name: "name", label: "查询条件:", offsetLeft: 5, placeholder: "请输入用户编码/名称", width: 300 },
      { type: "newcolumn" },
      { type: "button", name: "btn_search", value: "查询" },
      { type: "newcolumn" },
      { type: "button", name: "btn_reset", value: "重置" }
    ],
    multiselect: true,
    url: SERVICE_PLATFORM_POWER_BASE + '/userpower/getEnterpriseUsers',
    type: "get",
    params: {},
    contentType: "application/x-www-form-urlencoded",
    pagebar: { type: "simple" },
    page: true,
    totalCount: "totalCount"
  };
  // 推送方式弹窗
  var pushMethodTable = {
    columns: [
      { id: "code", name: "id", type: "ro", width: "130", hidden: true },
      { id: "name", name: "名称", type: "ro" }
    ],
    multiselect: true,
    pagebar: { type: "simple" },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/refdata/dtl/get-part",
    type: "post",
    contentType: "application/json",
    params: JSON.stringify({ objectcode: "EARLY_WARNING_PUSH_METHOD" }),
    page: false,
    totalCount: "totalCount"
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "earlyWarningId", name: "id", type: "ro", width: 120, hidden: true },
      { id: "earlyWarningName", name: "预警名称", type: "ro", width: 120 },
      { id: "earlyWarningTypeName", name: "预警类型", type: "ro", width: 120 },
      { id: "customerNames", name: "客户", type: "ro", width: 120 },
      { id: "", name: "开始预警偏差", type: "ro", width: 120, render: function (v, rd) { return rd.startTimeOffset + rd.startTimeOffsetUnit; } },
      { id: "", name: "结束预警偏差", type: "ro", width: 120, render: function (v, rd) { return rd.endTimeOffset + rd.endTimeOffsetUnit; } },
      { id: "pushMethodName", name: "推送方式", type: "ro", width: 120 },
      { id: "", name: "预警间隔", type: "ro", width: 120, render: function (v, rd) { return rd.intervalNumber + rd.intervalNumberUnit; } },
      { id: "describe", name: "预警消息", type: "ro", width: 120 },
      { id: "username", name: "通知人员", type: "ro", width: 120 },
      { id: "createperson", name: "创建用户", type: "ro", width: 120 },
      { id: "createtime", name: "创建时间", type: "ro", width: 120 },

      { id: "updateperson", name: "修改用户", type: "ro", width: 120 },
      { id: "updatetime", name: "修改时间", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function () {
          return "查看^earlyWarning_view,修改^earlyWarning_edit,删除^earlyWarning_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "search", label: "查询条件:", placeholder: "请输入预警名称/预警类型/客户/通知用户" },
          {
            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>新 增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_del", value: "删 除" }
            ]
          }
        ]
      }
    ],
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/alertConfiguration/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("earlyWarning_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        break;
      case "master_add":
        changePanel("#earlyWarning_edit");
        $("#earlyWarning_edit_form").html("");
        editFormCreated();
        $("#earlyWarning_edit_title").html("新增");
        break;
      case "master_del":
        var ids = master_grid.getCheckedIds();
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        var list = ids.split(",").map(id => {
          return { earlyWarningId: master_grid.getRowData(id).earlyWarningId };
        });
        alertConfiguration_delete(list);
        break;
    }
  });
  // 单个删除
  window.earlyWarning_del = function (rid) {
    alertConfiguration_delete([{ earlyWarningId: rid }]);
  };
  // 删除方法
  function alertConfiguration_delete(rowList) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/alertConfiguration/delete", type: "post", contentType: "application/json", data: JSON.stringify(rowList),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              master_grid.reload();
              return true;
            }
            setTimeout(() => { PlgDialog.alert(data.message || "接口调用失败"); }, 300);
            return false;

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

  // 查看
  window.earlyWarning_view = function (rid, rdata) {
    changePanel("#earlyWarning_view");
    new PlgPanel({
      renderer: "earlyWarning_view_form",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "预警名称", value: rdata.earlyWarningName },
            { label: "预警类型", value: rdata.earlyWarningTypeName },
            { label: "客户", value: rdata.companyname },
            { label: "开始预警偏差", value: rdata.startTimeOffset + rdata.startTimeOffsetUnit }
          ],
          [
            { label: "结束预警偏差", value: rdata.endTimeOffset + rdata.endTimeOffsetUnit },
            { label: "推送方式", value: rdata.pushMethodName },
            { label: "每隔", value: rdata.intervalNumber + rdata.intervalNumberUnit + "预警" }
          ],
          [
            { label: "预警消息", value: rdata.describe }
          ]
        ]
      }
    });

    let view_grid = new PlgGrid($.extend({}, edit_grid_opts, { toolbar: "", multiselect: false }));
    view_grid.renderTo("earlyWarning_view_grid");
    usersQuery(rdata.earlyWarningId, view_grid);
  };

  // 修改
  window.earlyWarning_edit = function (rid, rdata) {
    changePanel("#earlyWarning_edit");
    $("#earlyWarning_edit_form").html("");
    editFormCreated(rdata);
    $("#earlyWarning_edit_title").html("修改");
  };

  // 详情form
  edit_form_opts = {
    renderer: "earlyWarning_edit_form",
    items: [
      { type: "settings", labelAlign: "right", labelWidth: 100 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "earlyWarningName", label: "预警名称:", required: true },
          { type: "combo", className: "layui-col-md3", name: "earlyWarningTypeCode", label: "预警类型:", options: dataSelect.EARLY_WARNING_TYPE, readonly: true, required: true },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择",
            readonly: false,
            table: userTable,
            tableWidth: 700,
            tableHeight: 500,
            fieldText: "name",
            fieldValue: ["id", "code", "name"],
            name: "companyList",
            label: "客户:<span class='dhxform_item_required'>*</span>",
            listener: function (Grid) {
              setMethod(Grid, userTable, function () { });
            }
          },
          { type: "input", className: "layui-col-md2", name: "startTimeOffset", label: "开始预警偏差:", required: true },
          { type: "combo", className: "layui-col-md1", name: "startTimeOffsetUnit", options: dataSelect.EARLY_WARNING_UNIT, readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md2", name: "endTimeOffset", label: "结束预警偏差:", required: true },
          { type: "combo", className: "layui-col-md1", name: "endTimeOffsetUnit", options: dataSelect.EARLY_WARNING_UNIT, readonly: true },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择",
            readonly: false,
            table: pushMethodTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "name",
            fieldValue: "code",
            name: "pushMethodList",
            label: "推送方式:<span class='dhxform_item_required'>*</span>",
            listener: function (Grid) {
              setMethod(Grid, pushMethodTable, function () { });
            }
          },
          // { type: "combo", className: "layui-col-md3", name: "pushMethodCode", label: "推送方式:", comboType: "checkbox", options: dataSelect.EARLY_WARNING_PUSH_METHOD, readonly: true, required: true },
          { type: "input", className: "layui-col-md2", name: "intervalNumber", label: "每隔:" },
          { type: "combo", className: "layui-col-md1", name: "intervalNumberUnit", options: dataSelect.EARLY_WARNING_UNIT, readonly: true },
          { type: "label", className: "layui-col-md1", label: "预警" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md9", name: "describe", label: "预警消息:", rows: 3, required: true }
        ]
      }
    ]
  };
  // dataSelect.EARLY_WARNING_STATUS.forEach(item => {
  //   edit_form_opts.items[edit_form_opts.items.length - 1].list.push({ type: "label", className: "layui-col-md1", label: item.text });
  // });

  edit_grid_opts = {
    skin: "card",
    columns: [
      { id: "lineid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "username", name: "姓名", type: "ro" }, // 3
      { id: "userAccount", name: "帐号", type: "ro" },
      { id: "phone", name: "手机号", type: "ro" },
      { id: "departmentId", name: "", type: "ro", hidden: true },
      { id: "departmentName", name: "所属部门", type: "ro" },
      { id: "userTypeCode", name: "", type: "ro", hidden: true },
      { id: "userTypeName", name: "用户对象", type: "ro" }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-normal", name: "editGrid_add", value: "<i class='layui-icon layui-icon-add-1'></i>新 增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "editGrid_del", value: "删 除" }
            ]
          }
        ]
      }
    ],
    multiselect: true,
    page: false
  };
  // 创建form
  function editFormCreated(rdata) {
    edit_form = new PlgForm(edit_form_opts);

    edit_grid = new PlgGrid(edit_grid_opts);
    edit_grid.renderTo("earlyWarning_edit_grid");
    edit_grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "editGrid_add":
          userDialog();
          break;
        case "editGrid_del":
          var ids = edit_grid.getCheckedIds();
          if (!ids) {
            layer.msg("请选择数据");
            return false;
          }
          var editRowList = [];
          ids.split(",").forEach(row_id => {
            const ele = edit_grid.getRowData(row_id);
            if (ele.rowType === "add") {
              edit_grid.deleteRow(row_id);
            }
            else {
              editRowList.push(ele);
            }
          });
          if (editRowList.length) {
            editGrid_del(editRowList);
          }
          break;
      }
    });

    if (rdata) {
      let idList = rdata.customerIds.split(","), codeList = rdata.customerCodes.split(","), nameList = rdata.customerNames.split(",")
      let companyList = idList.map((item, index) => {
        return {
          id: item,
          code: codeList[index],
          name: nameList[index],
        }
      })
      rdata.companyList = idList.length ? JSON.stringify(companyList) : '[]';
      rdata.pushMethodList = JSON.stringify(rdata.pushMethodCode.split(","));
      edit_form.setText("companyList", rdata.customerNames);
      edit_form.setText("pushMethodList", rdata.pushMethodName);
      edit_form.setFormData(rdata);
      edit_form.disableItem("companyList");
      edit_form.disableItem("earlyWarningName");
      edit_form.disableItem("earlyWarningTypeCode");
      usersQuery(rdata.earlyWarningId, edit_grid);
    }
    else {
      edit_form.setFormData({ startTimeOffsetUnit: "小时", endTimeOffsetUnit: "小时", intervalNumberUnit: "小时" });
    }

    // 表单label点击
    $("#earlyWarning_edit_form .dhxform_txt_label2").on("click", function (data) {
      let text = data.currentTarget.innerText;
      let input = edit_form.getInput("describe");
      let cursurPosition = input.selectionStart;
      if (text !== "预警" && cursurPosition > -1) {
        input.value = input.value.substr(0, cursurPosition) + text + input.value.substr(cursurPosition);
      }
      // input.focus();
      // input.setSelectionRange(2, 3);
    });
  }

  // 保存
  $("#earlyWarning_edit_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return;
    let formData = edit_form.getFormData();

    formData.earlyWarningTypeName = edit_form.getCombo("earlyWarningTypeCode").getComboText();
    formData.companyList = formData.companyList ? JSON.parse(formData.companyList) : [];
    if (!formData.companyList.length) {
      layer.msg("请选择客户");
      return false;
    }
    let idList = [], codeList = [], nameList = []
    formData.companyList.forEach(item => {
      idList.push(item.id)
      codeList.push(item.code)
      nameList.push(item.name)
    })
    formData.customerIds = idList.join(',')
    formData.customerCodes = codeList.join(',')
    formData.customerNames = nameList.join(',')
    delete formData.companyList;

    let pushMethods = formData.pushMethodList ? JSON.parse(formData.pushMethodList) : [];
    if (!pushMethods.length) {
      layer.msg("请选择推送方式");
      return false;
    }
    formData.pushMethodCode = pushMethods.join(",");
    formData.pushMethodName = edit_form.getText("pushMethodList");
    delete formData.pushMethodList;

    // 获取已选择的用户
    let dataList = [];
    let indexNum = edit_grid.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let ele = edit_grid.getRowData(edit_grid.getRowId(i));
      if (ele.rowType === "add") dataList.push(ele);
    }
    formData.users = dataList;

    let url = $("#earlyWarning_edit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/alertConfiguration/save" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/alertConfiguration/update";
    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("#earlyWarning_main");
          master_grid.reload();
          return true;
        }
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });

  // 用户弹窗
  function userDialog() {
    // 获取已选择的用户
    let useridList = [];
    let indexNum = edit_grid.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let { userid } = edit_grid.getRowData(edit_grid.getRowId(i));
      useridList.push(userid);
    }

    let user_grid;
    PlgDialog.open({
      title: "选择用户",
      shadeClose: true,
      type: 1,
      area: ["600px", "500px"],
      content: "<div id =\"earlyWarning_dialog\"></div>",
      btn: ["确认", "取消"],
      yes: function () {
        let ids = user_grid.getCheckedIds();
        if (ids) {
          ids.split(",").forEach(id => {
            const ele = user_grid.getRowData(id);
            if (!useridList.includes(id)) {
              let rowdata = {
                lineid: "",
                userid: ele.id,
                username: ele.nickname,
                userAccount: ele.username,
                phone: ele.phoneNumber,
                departmentId: ele.p_organizationid,
                departmentName: ele.p_orgname,
                userTypeCode: ele.userCategory,
                userTypeName: Prolog.getNameByID(USER_TYPE, ele.userCategory),
                rowType: "add"
              };
              edit_grid.addRow(id, rowdata);
            }
          });
        }
        layer.closeAll();
      }
    });
    user_grid = new PlgGrid(operator_Table);
    user_grid.renderTo("earlyWarning_dialog");
    user_grid.loadData(null, function () {
      useridList.forEach(id => user_grid.setCellValue(id, 1, 1));
    });
    user_grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "btn_search":
          var { search } = user_grid.getToolBarForm().getFormData();
          user_grid.setParams({ search, "branchid": userGJ.p_companyid });
          user_grid.reload();
          break;
        case "btn_reset":
          user_grid.getToolBarForm().clear();
          break;
      }
    });
  }

  // 查询用户
  function usersQuery(earlyWarningId, Grid) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/alertConfiguration/usersQuery", type: "post", contentType: "application/json", data: JSON.stringify({ earlyWarningId }),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          Grid.loadData({ data: { list: res.data } });
          return true;
        }
        setTimeout(() => { PlgDialog.alert(res.message || "接口调用失败"); }, 300);
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
  // 编辑删除
  function editGrid_del(editRowList) {
    // 原有的调接口删除
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/alertConfiguration/usersDelete", type: "post", contentType: "application/json", data: JSON.stringify(editRowList),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          editRowList.forEach(item => edit_grid.deleteRow(item.lineid));
          return true;
        }
        setTimeout(() => { PlgDialog.alert(res.message || "接口调用失败"); }, 300);
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
};