/**
 * zzx
 * 2022.01.14
 * 导入配置
 */
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';
// import {SeniorSearch} from './seniorSearch.js';



export default () => {
  var master_grid, edit_form_opts, edit_form, edit_grid_opts, edit_grid;

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

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

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "hid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "importObjName", name: "导入对象", type: "ro" },
      { id: "templeteName", name: "模板名称", type: "ro" },
      { id: "status", name: "是否启用", type: "ro", render: function (v) { return Prolog.getNameByID(dataSelect.ENABLE_STATUS, v); } },
      { 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 (v, rd) {
          let result = "^importConfiguration_enable,查看^importConfiguration_view,修改^importConfiguration_edit,删除^importConfiguration_del";
          if (rd.status === 1) {
            result = "停用" + result;
          }
          else {
            result = "启用" + result;
          }
          return result;
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "importObjName", 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: "newcolumn" },
              // { type: "button", className: "btn-normal", name: "master_seniorSearch", 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+"/sysimport/templet/listPage", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("importConfiguration_master");
  // master_grid.loadData();
//  var seniorSearch = new SeniorSearch("ImportQuery", master_grid);
  // seniorSearch.listAll();

  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_seniorSearch":
      //   seniorSearch.dialog();
      //   break;
      case "master_add":
        changePanel("#importConfiguration_edit");
        $("#importConfiguration_edit_form").html("");
        editFormCreated();
        $("#importConfiguration_edit_title").html("新增");
        break;
      case "master_del":
        var ids = master_grid.getCheckedIds();
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        templet_delete(ids);
        break;
    }
  });
  // 启用/停用
  window.importConfiguration_enable = function (rid, rdata) {
    let text = rdata.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+"/sysimport/templet/enable/" + rid + "/" + (rdata.status === 1 ? "0" : "1"), type: "get",
          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.importConfiguration_del = function (rid) {
    templet_delete(rid);
  };
  // 删除方法
  function templet_delete(ids) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysimport/templet/delete", type: "post", contentType: "application/x-www-form-urlencoded", data: { ids },
          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.importConfiguration_edit = function (rid, rdata) {
    changePanel("#importConfiguration_edit");
    $("#importConfiguration_edit_form").html("");
    editFormCreated(rdata);
    $("#importConfiguration_edit_title").html("修改");
  };

  // 查看
  window.importConfiguration_view = function (rid, rdata) {
    changePanel("#importConfiguration_view");
    new PlgPanel({
      renderer: "importConfiguration_view_form",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "导入对象", value: Prolog.getNameByID(dataSelect.IMPORT_OBJ_LIST, rdata.importObjNo) },
            { label: "模板名称", value: rdata.templeteName },
            { label: "是否启用", value: Prolog.getNameByID(dataSelect.ENABLE_STATUS, rdata.status) }
          ]
        ]
      }
    });
    let view_grid = new PlgGrid({
      skin: "card",
      columns: [
        { id: "stdColNo", name: "id", type: "ro", width: "130", hidden: true },
        { id: "stdColName", name: "标准版excel列名", type: "ro" },
        { id: "custColName", name: "自定义excel列名", type: "ro" }
      ],
      page: false
    });
    view_grid.renderTo("importConfiguration_view_grid");
    queryHd(rdata.hid, view_grid);
  };

  // 详情form
  edit_form_opts = {
    renderer: "importConfiguration_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [

          { type: "combo", className: "layui-col-md3", name: "importObjNo", label: "导入对象:", options: dataSelect.IMPORT_OBJ_LIST, readonly: true, required: true },
          { type: "input", className: "layui-col-md3", name: "templeteName", label: "模板名称:", required: true },
          { type: "combo", className: "layui-col-md3", name: "status", label: "是否启用:", options: dataSelect.ENABLE_STATUS, 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 }
        ]
      }
    ]
  };
  edit_grid_opts = {
    skin: "card",
    columns: [
      { id: "fieldid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "stdColName", name: "标准版excel列名", type: "ro" },
      { id: "custColName", name: "<span style='color:#096dd9;'>自定义excel列名</span>", type: "ed" }
    ],
    page: false
  };
  // 创建form
  function editFormCreated(rdata) {
    edit_form = new PlgForm(edit_form_opts);
    edit_grid = new PlgGrid(edit_grid_opts);
    edit_grid.renderTo("importConfiguration_edit_grid");
    edit_grid.getGrid().enableEditEvents(true, false, true);

    // 编辑离开校验
    edit_grid.attachEvent("onEditCell", function (stage, rId, cInd, nValue) {
      if (stage === 2) {
        edit_grid.setCellValue(rId, cInd, nValue);
      }
      return true;
    });

    if (rdata) {
      edit_form.setFormData(rdata);
      edit_form.disableItem("importObjNo");
      edit_form.disableItem("templeteName");
      queryHd(rdata.hid, edit_grid);
    }
    else {
      edit_form.enableItem("");
    }

    edit_form.attachComboEvent("importObjNo", "onChange", function (id) {
      queryImportTempletd(id);
    });
  }

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

      let dataList = [];
      let indexNum = edit_grid.getGrid().getRowsNum();
      for (let i = 0; i < indexNum; i++) {
        const element = edit_grid.getRowData(edit_grid.getRowId(i));
        if (!element.custColName) {
          layer.msg("自定义excel列名不能为空");
          return false;
        }
        dataList.push(element);
      }

      formData.importObjName = edit_form.getCombo("importObjNo").getComboText();
      formData.list = dataList;

      let url = $("#importConfiguration_edit_title").html() === "新增" ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysimport/templet/add" : UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysimport/templet/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("#importConfiguration_main");
            master_grid.reload();
            return true;
          }
                    return false;
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }, 200);
  });

  // 获取不同导入对象对应的明细列表
  function queryImportTempletd(importObjNo) {
    edit_grid.clearAll();
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysimport/stdfeild/list/" + importObjNo, type: "get",
      success: function (res) {
        if (res.success) {
          edit_grid.loadData({ data: { list: res.data } });
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }

  // 查询模板明细列表
  function queryHd(id, Grid) {
    Grid.clearAll();
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysimport/templet/queryHd/" + id, type: "get",
      success: function (res) {
        if (res.success) {
          Grid.loadData({ data: { list: res.data.list } });
          return true;
        }
                return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
};