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

  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "PROCEDURE_TYPE" },
    { "objectcode": "PROCEDURE_NAME" },
    { "objectcode": "SERVICE_FLOW_STATUS" },
    { "objectcode": "AUDIT_FLOW_STATUS" },
    { "objectcode": "PUB_PROCESS_CONFIGURATION_IS_LOCK" }
  ], function (data) {
    dataSelect = data.data;
    dataSelect.PROCEDURE_TYPE.unshift({ "value": "", "text": "" });
  });

  // 查询省
  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 auditRoleTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "p_id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "p_name", name: "角色名称", type: "ro" },
      { id: "p_orgname", name: "所属组织", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "name", label: "查询条件:", width: 150, placeholder: "请输入角色名称" },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: "/users/role/list",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: {}, // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/x-www-form-urlencoded",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 审核人table
  var auditPersonTable = {
    // 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: 200 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "search", label: "查询条件:", width: 150, placeholder: "请输入用户名称" },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: "/users/role/users",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: { type: 1 }, // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/x-www-form-urlencoded",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "procedureTypeName", name: "流程类型", type: "ro", width: 120 },
      { id: "procedureCode", name: "流程编号", type: "ro", width: 120 },
      { id: "procedureName", name: "流程名称", type: "ro", width: 120 },
      { id: "currentStatusName", name: "当前状态", type: "ro", width: 120 },
      { id: "nextStatusName", name: "下一状态", type: "ro", width: 120 },
      { id: "branchname", name: "配送中心", type: "ro", width: 120 },
      { id: "auditRoleName", name: "审核角色", type: "ro", width: 120 },
      { id: "auditPersonName", name: "审核人", type: "ro", width: 120 },
      { id: "isLockName", name: "是否锁定", type: "ro", width: 120 },
      { id: "remarks", name: "备注", type: "ro", width: 120 },
      // {
      //   id: "containerType", name: "容器类型", type: "ro", render: function (v) {
      //     return getSelectValue(dataSelect.CONTAINER_TYPE, v);
      //   }
      // },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function () {
          return "修改^auditAuthorityManage_edit,删除^auditAuthorityManage_del";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", readonly: true, name: "procedureType", label: "流程类型:", options: dataSelect.PROCEDURE_TYPE },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "procedureCode", label: "流程名称:", options: [{ "value": "", "text": "" }].concat(dataSelect.PROCEDURE_NAME) },
          {
            type: "block", className: "layui-col-md3 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: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubProcessConfiguration/query/v1.0", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("auditAuthorityManage_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("#auditAuthorityManage_edit");
        $("#auditAuthorityManage_edit_form").html("");
        editFormCreated();
        $("#auditAuthorityManage_edit_title").html("新增");
        break;
    }
  });
  // 单个删除
  window.auditAuthorityManage_del = function (rid) {
    auditNodeDelete([{ procedureCode: rid }]);
  };
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    let list = ids.split(",").map(item => {
      return { procedureCode: item };
    });
    auditNodeDelete(list);
  });
  // 删除方法
  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+"/pubProcessConfiguration/delete/v1.0", 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.auditAuthorityManage_edit = function (rid, rdata) {
    changePanel("#auditAuthorityManage_edit");
    $("#auditAuthorityManage_edit_form").html("");
    editFormCreated(rdata);
    $("#auditAuthorityManage_edit_title").html("修改");
  };

  // 详情form
  edit_form_opts = {
    renderer: "auditAuthorityManage_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "combo", className: "layui-col-md3", name: "procedureType", label: "流程类型:", options: dataSelect.PROCEDURE_TYPE, readonly: true, required: true },
          { type: "combo", className: "layui-col-md3", name: "procedureCode", label: "流程名称:", options: dataSelect.PROCEDURE_NAME, readonly: true, required: true },
          { type: "combo", className: "layui-col-md3", name: "currentStatus", label: "当前状态:", options: [], readonly: true, required: true },
          { type: "combo", className: "layui-col-md3", name: "nextStatus", label: "下一状态:", options: [], readonly: true, required: true },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择配送中心",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "branchidList",
            label: "配送中心:",
            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;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  branchid: isSelected ? sdata.companyid : "",
                  branchcode: isSelected ? sdata.companycode : "",
                  branchname: isSelected ? sdata.companyname : ""
                });
              }
            }
          },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择审核角色",
            readonly: false,
            table: auditRoleTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "p_name",
            fieldValue: "p_id",
            name: "auditRoleList",
            label: "审核角色:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var request = Grid.getToolBarForm().getFormData();
                      Grid.setParams(request);
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  auditRoleId: isSelected ? sdata.p_id : "",
                  auditRoleName: isSelected ? sdata.p_name : "",
                  auditPersonId: "",
                  auditPersonName: "",
                  auditPersonList: "[]"
                });
                edit_form.setText("auditPersonList", "");
                if (isSelected) {
                  auditPersonTable.params = { type: 1, roleid: isSelected ? sdata.p_id : "" };
                  edit_form.getDForm().setTableConfig("auditPersonList", auditPersonTable);
                  edit_form.enableItem("auditPersonList");
                }
                else {
                  edit_form.disableItem("auditPersonList");
                }
              }
            }
          },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择审核人",
            readonly: false,
            table: auditPersonTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "p_nickname",
            fieldValue: "p_id",
            name: "auditPersonList",
            label: "审核人:",
            listener: {
              "init": function (Grid) {
                // 注册按钮事件
                Grid.attachToolBarEvent("onButtonClick", function (name) {
                  switch (name) {
                    case "querycarr":
                      var request = Grid.getToolBarForm().getFormData();
                      request.type = 1;
                      Grid.setParams(request);
                      Grid.reload();
                      break;
                    case "car_Reset":
                      Grid.getToolBarForm().clear();
                      break;
                  }
                });
              },
              "afterSelect": function (isSelected, selectId, sgrid) {
                let sdata = sgrid.getRowData(selectId);
                edit_form.setFormData({
                  auditPersonId: isSelected ? sdata.p_id : "",
                  auditPersonName: isSelected ? sdata.p_nickname : ""
                });
              }
            }
          },
          { type: "combo", className: "layui-col-md3", name: "isLock", label: "是否锁定:", options: dataSelect.PUB_PROCESS_CONFIGURATION_IS_LOCK, readonly: true, required: true },
          { type: "input", className: "layui-col-md6", name: "remarks", label: "备注:", rows: 3 }
        ]
      }
    ]
  };
  // 创建form
  function editFormCreated(rdata) {
    edit_form = new PlgForm(edit_form_opts);

    // 状态根据流程类型变化 0-业务流 1-审核流
    edit_form.attachComboEvent("procedureType", "onChange", function (id) {
      edit_form.getCombo("currentStatus").setComboText("");
      edit_form.getCombo("nextStatus").setComboText("");
      edit_form.getCombo("currentStatus").clearAll();
      edit_form.getCombo("nextStatus").clearAll();
      if (id === "01") {
        edit_form.getCombo("currentStatus").addOption(dataSelect.SERVICE_FLOW_STATUS);
        edit_form.getCombo("nextStatus").addOption(dataSelect.SERVICE_FLOW_STATUS);
      }
      else if (id === "02") {
        edit_form.getCombo("currentStatus").addOption(dataSelect.AUDIT_FLOW_STATUS);
        edit_form.getCombo("nextStatus").addOption(dataSelect.AUDIT_FLOW_STATUS);
      }
    });
    if (rdata) {
      rdata.branchidList = rdata.branchid ? JSON.stringify([rdata.branchid]) : "[]";
      rdata.auditRoleList = rdata.auditRoleId ? JSON.stringify([rdata.auditRoleId]) : "[]";
      rdata.auditPersonList = rdata.auditPersonId ? JSON.stringify([rdata.auditPersonId]) : "[]";
      edit_form.setFormData(rdata);
      edit_form.setText("branchidList", rdata.branchname || "");
      edit_form.setText("branchidList", rdata.branchcode || "");
      edit_form.setText("auditRoleList", rdata.auditRoleName || "");
      edit_form.setText("auditPersonList", rdata.auditPersonName || "");
      if (rdata.auditRoleId) {
        edit_form.enableItem("auditPersonList");
      }
      else {
        edit_form.disableItem("auditPersonList");
      }
      edit_form.disableItem("procedureType");
      edit_form.disableItem("procedureCode");
    }
    else {
      edit_form.disableItem("auditPersonList");
    }
  }

  // 保存
  $("#auditAuthorityManage_edit_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return;
    let formData = edit_form.getFormData();
    formData.procedureName = edit_form.getCombo("procedureCode").getComboText();
    if (!formData.branchid) {
      layer.msg("请选择配送中心");
      return false;
    }
    delete formData.branchidList;
    delete formData.auditRoleList;
    delete formData.auditPersonList;
    let url = $("#auditAuthorityManage_edit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubProcessConfiguration/add/v1.0" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubProcessConfiguration/update/v1.0";
    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("#auditAuthorityManage_main");
          master_grid.reload();
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};