/**
 * zzx
 * 2022.01.13
 * 扩展字段
 */
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 (self) => {
  var master_grid, edit_form_opts, edit_form;
  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#extendedField",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#extendedField_main", "#extendedField_edit", "#extendedField_view"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $("#extendedField_edit_return").on("click", function () {
    changePanel("#extendedField_main");
  });
  $("#extendedField_view_return").on("click", function () {
    changePanel("#extendedField_main");
  });

  // 获取下拉框
  var dataSelect;
  getSelectGJ([
    { "objectcode": "EXTENDED_OBJECT" },
    { "objectcode": "FIELD_TYPE", "groupcode1": "1" }
  ], function (data) {
    dataSelect = data.data;
    dataSelect.EXTENDED_OBJECT.unshift({ "value": "", "text": "" });
    dataSelect.FIELD_TYPE.unshift({ "value": "", "text": "" });
  });

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "lineid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "displayName", name: "扩展字段", type: "ro" },
      // { id: "fieldName", name: "字段名称", type: "ro" },
      { id: "extendedObjectName", name: "扩展对象", type: "ro" },
      { id: "fieldTypeName", name: "类型", type: "ro" },
      { id: "createperson", name: "创建人", type: "ro" },
      { id: "createtime", name: "创建时间", type: "ro" },
      { id: "updateperson", name: "修改人", type: "ro" },
      { id: "updatetime", name: "修改时间", type: "ro" },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 150, fixed: "right", render: function () {
          return "查看^extendedField_view,修改^extendedField_edit,删除^extendedField_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+"/extendedField/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("extendedField_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("#extendedField_edit");
        $("#extendedField_edit_form").html("");
        editFormCreated();
        $("#extendedField_edit_title").html("新增");
        break;
      case "master_del":
        var ids = master_grid.getCheckedIds();
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        var list = ids.split(",").map(item => {
          return { lineid: item };
        });
        extendedField_delete(list);
        break;
    }
  });
  // 单个删除
  window.extendedField_del = function (rid) {
    extendedField_delete([{ lineid: rid }]);
  };
  // 删除方法
  function extendedField_delete(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+"/extendedField/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.extendedField_view = function (rid, rdata) {
    changePanel("#extendedField_view");
    let cols = [
      [
        { label: "扩展字段", value: rdata.displayName },
        { label: "扩展对象", value: Prolog.getNameByID(dataSelect.EXTENDED_OBJECT, rdata.extendedObjectCode) },
        { label: "字段类型", value: Prolog.getNameByID(dataSelect.FIELD_TYPE, rdata.fieldType) },
        { label: "权限类型", value: rdata.status == "1" ? "启用" : "停用" }
      ]
    ];
    if (rdata.fieldType === "4") {
      cols.push(
        [
          { label: "枚举值", value: rdata.fieldChoiceValue }
        ]
      );
    }
    new PlgPanel({
      renderer: "extendedField_view_form",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols
      }
    });
  };

  // 修改
  window.extendedField_edit = function (rid, rdata) {
    changePanel("#extendedField_edit");
    $("#extendedField_edit_form").html("");
    editFormCreated(rdata);
    $("#extendedField_edit_title").html("修改");
  };

  // 详情form
  edit_form_opts = {
    renderer: "extendedField_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "displayName", label: "扩展字段:", required: true },
          { type: "combo", className: "layui-col-md3", name: "extendedObjectCode", label: "扩展对象:", options: dataSelect.EXTENDED_OBJECT, readonly: true, required: true },
          { type: "combo", className: "layui-col-md3", name: "fieldType", label: "字段类型:", options: dataSelect.FIELD_TYPE, readonly: true, required: true },
          { type: "combo", className: "layui-col-md3", name: "status", label: "状态:", options: [{ value: "1", text: "启用" }, { value: "0", text: "停用" }], readonly: true, required: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "fieldChoiceValue", label: "枚举值<span class='dhxform_item_required'>*</span>:", placeholder: "多个值用逗号隔开", rows: 3, hidden: true }
        ]
      }
    ]
  };
  // 创建form
  function editFormCreated(rdata) {
    edit_form = new PlgForm(edit_form_opts);
    edit_form.attachComboEvent("fieldType", "onChange", function (id) {
      if (id === "4") {
        edit_form.showItem("fieldChoiceValue");
      }
      else {
        edit_form.hideItem("fieldChoiceValue");
      }
    });

    if (rdata) {
      edit_form.setFormData(rdata);
      edit_form.disableItem("displayName");
      edit_form.disableItem("extendedObjectCode");
    }
    else {
      edit_form.enableItem("displayName");
      edit_form.enableItem("extendedObjectCode");
    }
  }

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

    if (formData.fieldType === "4" && !formData.fieldChoiceValue) {
      layer.msg("当字段类型位单选框时枚举值必填");
      return false;
    }

    formData.extendedObjectName = edit_form.getCombo("extendedObjectCode").getComboText();
    formData.fieldTypeName = edit_form.getCombo("fieldType").getComboText();

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