/**
 * jiw
 * 2018.10.23
 * 号码管理器
 */
 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 rsp_codetype = [], rsp_codedatatype = [], rsp_issegsource = [];
  var req = [{ "objectcode": "codetype" }, { "objectcode": "codedatatype" }, { "objectcode": "YesOrNo" }];
  Prolog.ajax({
    url: "/sys/refdata/dtl/dd-list", type: "post", contentType: "application/json", data: JSON.stringify(req), async: false,
    success: function (data) {
      if (data.success) {
        bindRefdata(rsp_codetype, data.data.codetype, true);
        bindRefdata(rsp_codedatatype, data.data.codedatatype, true);
        bindRefdata(rsp_issegsource, data.data.YesOrNo, true);
      }
    }, error: function () { PlgDialog.msg("接口调用失败"); }
  });

  var grid = null;
  var param = { "pageNum": 1, "pageSize": 10 };
  var type = 0;


  //滑屏
  var carousel = layui.carousel;
  var car = carousel.render({
    elem: "#numbermanager_grid",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });

  function changePanel(name) {
    car.slide(name);
  }

  //返回主页面
  $("#numbermanager_btn_back").click(function () {
    changePanel("numbermanager_grid_01");
    return false;
  });

  gridInit();


  //主页面Grid
  function gridInit() {
    var numOpts = {
      skin: "terrace",
      rowId: "codeid",
      columns: [
        { id: "codeid", name: "资源ID", type: "ro", hidden: true },
        { id: "code", name: "资源码", type: "ro" },
        { id: "groupid", name: "分组", type: "ro", hidden: true },
        { id: "name", name: "名称", type: "ro" },
        {
          id: "codetype", name: "号码类型", align: "center", type: "ro", width: 80, render: function (v) {
            return Prolog.getNameByID(rsp_codetype, v);
          }
        },
        {
          id: "codedatatype", name: "数值类型", align: "center", width: 80, type: "ro", render: function (v) {
            return Prolog.getNameByID(rsp_codedatatype, v);
          }
        },
        { id: "length", name: "长度", align: "right", width: 80, type: "ro" },
        { id: "gap", name: "间隔", align: "right", width: 80, type: "ro" },
        { id: "codeflag", name: "号码代号", type: "ro", hidden: true },
        { id: "maxbillno", name: "最大资源码号", align: "right", width: 120, type: "ro" },
        { id: "billrule", name: "号码规则", type: "ro" },
        { id: "segcodesql", name: "段代码取法", type: "ro" },
        {
          id: "op", name: "操作", type: "button", align: "center", width: 150, render: function () {
            return "详情^res_NumberManager_showClick,修改^res_NumberManager_editClick,删除^res_NumberManager_delClick";
          }
        }
      ],
      multiselect: false,
      fixedLast: true,
      toolbar: [
        { type: "input", name: "search", label: "查询条件:", width: 300, placeholder: "请输入编号/名称" }, { type: "newcolumn" },
        { type: "button", name: "btn_search", value: "查询" },
        { type: "newcolumn" },
        { type: "button", name: "btn_reset", className: " normal", value: "重置" },
        { type: "newcolumn" },
        {
          type: "button",
          name: "btn_add",
          className: "plg-toolbar-right",
          value: "<i class='layui-icon layui-icon-add-1'></i>新增"
        }, { type: "newcolumn" }
      ],
      formData: [],
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/codes/query",//数据接口
      type: "POST",//数据提交方式，默认为get
      params: param,//查询提交参数，分页参数默认为pageNum,pageSize
      contentType: "application/x-www-form-urlencoded",
      page: true, //是否启用分页
      totalCount: "totalCount" //总记录数字段，默认totalCount
    };
    //分页参数 pageSize pageNum
    grid = new PlgGrid(numOpts);
    grid.renderTo("numbermanager_grid_01");
    grid.loadData();

    // 双击行编辑
    grid.on("onRowDblClicked", function () {
      show_numbermanagerinfo(grid.getSelectedRowId(), grid.getSelectedRowData());
    });

    //工具栏键盘事件
    grid.getToolBarForm().attachEvent("onKeyDown", function (inp, ev) {
      if (ev.key == "Enter") {
        grid.setParams(grid.getToolBarForm().getFormData());
        grid.reload();
      }
    });

    //工具栏按钮事件
    grid.attachToolBarEvent("onButtonClick", function (name) {
      // 查询
      if (name === "btn_search") {
        grid.setParams(grid.getToolBarForm().getFormData());
        grid.reload();
      }
      // 新增
      else if (name === "btn_add") {
        addnumbermanager();
      }
      else if (name == "btn_reset") {
        grid.getToolBarForm().clear();
      }
    });
  }

  //添加号码管理器
  function addnumbermanager() {
    type = 0;
    var str = "<div class=\"layui-col-lg12\" id=\"numbermanager_grid_add_content\"></div>";
    $("#numbermanager_grid_sub").html(str);
    $("#numbermanager_add_btn_next").show();
    changePanel("numbermanager_grid_01_edit");
    numbermanagerFormInit(0, {});

  }

  $("#btn_save_numbermanager").click(function () {
    var b = form1.validate();
    if (!b) return;
    var fd = form1.getFormData();
    if (type === 0) {
      save_numbermanagerinfo(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/codes/create", "post", "application/x-www-form-urlencoded", fd);
    }
    else if (type === 1) {
      save_numbermanagerinfo(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/codes/update", "put", "application/x-www-form-urlencoded", fd);
    }
  });

  //号码管理器表单
  function numbermanagerFormInit(ntype, rdata) {
    var tit = "新增号码管理器";
    var rediv = "numbermanager_grid_add_content";
    if (ntype === 1) {
      tit = "号码管理器 [" + rdata.name + "] 信息修改";
      rediv = "numbermanager_grid_sub";
    }
    $("#numbermanager_span_title").html(tit);
    $("#btn_save_numbermanager").show();
    $("#" + rediv).html("");
    var formcfg = {
      renderer: rediv,
      items: [
        { type: "settings", inputWidth: 200, width: "*", labelWidth: 100, position: "label-left", labelAlign: "left" },
        {
          type: "block", width: "*",
          list: [
            {
              type: "combo", readonly: true,
              name: "codetype",
              validate: "NotEmpty",
              required: true,
              editable: false,
              label: "号码类型:",
              width: 200,
              options: rsp_codetype
            },
            { type: "newcolumn", offset: 60 },
            {
              type: "combo", readonly: true,
              name: "codedatatype",
              validate: "NotEmpty",
              required: true,
              editable: false,
              label: "数值类型:",
              width: 200,
              options: rsp_codedatatype
            }]
        },
        {
          type: "block", width: "*",
          list: [
            { type: "input", name: "code", label: "资源码:", validate: "NotEmpty", required: true },
            { type: "newcolumn", offset: 60 },
            { type: "input", name: "name", label: "名称:", validate: "NotEmpty", required: true }]
        },
        {
          type: "block", width: "*",
          list: [
            { type: "input", name: "groupid", label: "分组:", editable: false, required: true, validate: "NotEmpty,ValidInteger", placeholder: "只能输入数字" },
            { type: "newcolumn", offset: 60 },
            {
              type: "input",
              name: "length",
              label: "长度:",
              validate: "NotEmpty,ValidInteger",
              required: true,
              placeholder: "只能输入数字"
            }]
        },
        {
          type: "block", width: "*",
          list: [
            {
              type: "input",
              name: "gap",
              label: "间隔:",
              editable: false,
              validate: "NotEmpty,ValidInteger",
              required: true,
              placeholder: "只能输入数字"
            },
            { type: "newcolumn", offset: 60 },
            { type: "input", name: "codeflag", label: "号码代号:", editable: false }]
        },
        {
          type: "block", width: "*",
          list: [
            { type: "input", name: "maxbillno", label: "最大资源码号:", editable: false },
            { type: "newcolumn", offset: 60 },
            { type: "input", name: "billrule", label: "号码规则:", editable: false }]
        },
        {
          type: "block", width: "*",
          list: [
            {
              type: "combo", readonly: true,
              name: "issegsource",
              editable: false,
              label: "段资源定义:",
              width: 200,
              options: rsp_issegsource
            },
            { type: "newcolumn", offset: 60 },
            { type: "input", name: "segcodesql", label: "段代码取法:", editable: false },
            { type: "hidden", name: "codeid", value: "", editable: false }]
        }
      ]
    };
    form1 = new PlgForm(formcfg);
    form1.setFormData(rdata);

    if (ntype === 1) {
      form1.getDForm().disableItem("codetype");
      form1.getDForm().disableItem("codedatatype");
      /* form1.getDForm().disableItem("groupid");
      form1.getDForm().disableItem("codeflag");
      form1.getDForm().disableItem("maxbillno");
      form1.getDForm().disableItem("billrule");
      form1.getDForm().disableItem("issegsource");
      form1.getDForm().disableItem("segcodesql");
      form1.getDForm().disableItem("codeid");
      form1.getDForm().disableItem("gap"); */
    }
  }


  //号码管理器信息保存
  function save_numbermanagerinfo(grid, url, type, contentType, formData) {
    //加载等待
    var pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    var rep = null;
    Prolog.ajax({
      url: url,
      type: type,
      contentType: contentType,
      data: formData,
      async: true,
      success: function (data) {
        PlgDialog.close(pload);
        rep = data;
        if (data.success) {
          PlgDialog.msg(data.message);
          setTimeout(function () { changePanel("numbermanager_grid_01"); grid.reload(); }, 10);
        }
        else {
          setTimeout(() => { PlgDialog.alert(data.message == null ? "接口调用失败" : data.message); }, 300);
          PlgDialog.close(pload);
        }
      },
      error: function () { PlgDialog.close(pload); PlgDialog.msg("接口调用失败"); }
    });
    return rep;
  }

  //查看号码管理器详细
  function show_numbermanagerinfo(rid, rdata) {
    $("#btn_save_numbermanager").hide();
    $("#numbermanager_span_title").html("号码管理器 [" + rdata.name + "] 信息查看");
    changePanel("numbermanager_grid_01_edit");
    $("#numbermanager_grid_sub").removeClass();

    new PlgPanel({
      renderer: "numbermanager_grid_sub",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [{
            label: "资源码",
            value: rdata.code
          },
          {
            label: "名称",
            value: rdata.name
          },
          {
            label: "修号码类型",
            value: Prolog.getNameByID(rsp_codetype, rdata.codetype)
          },
          {
            label: "数值类型",
            value: Prolog.getNameByID(rsp_codedatatype, rdata.codedatatype)
          },
          {
            label: "分组",
            value: rdata.groupid
          },
          {
            label: "长度",
            value: rdata.length
          },
          {
            label: "间隔",
            value: rdata.gap
          },
          {
            label: "号码代号",
            value: rdata.codeflag
          },
          {
            label: "最大资源码号",
            value: rdata.maxbillno
          },
          {
            label: "号码规则",
            value: rdata.billrule
          },
          {
            label: "段资源定义",
            value: rdata.issegsource
          },
          {
            label: "段代码取法",
            value: rdata.segcodesql
          }

          ]
        ]
      }
    });
  }
  function bindRefdata(rsp, data, addNsN) {
    if (addNsN) {
      rsp.push({ text: "", value: "" });
    }
    for (var i = 0; i < data.length; i++) {
      rsp.push({ text: data[i].text, value: data[i].value });
    }
  }

  window.res_NumberManager_editClick = function (rid, rdata) {
    grid.selectRowById(rid);
    type = 1;
    changePanel("numbermanager_grid_01_edit");
    numbermanagerFormInit(1, rdata);
    return false;
  };
  window.res_NumberManager_delClick = function (rid) {
    Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/codes/delete", "", "", { "codeid": rid }, false);
    return false;
  };
  window.res_NumberManager_showClick = function (rid, rdata) {
    grid.selectRowById(rid);
    show_numbermanagerinfo(rid, rdata);
    return false;
  };
};