/**
 * jiw
 * 2018.12.24
 * 货主
*/
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_province = [];
  Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": "01" }), async: false,
      success: function (data) {
          if (data.success) {
              rsp_province.push({ text: "", value: "" });
              for (var i = 0; i < data.data.length; i++) {
                  rsp_province.push({ text: data.data[i].keyvalue, value: data.data[i].zoneid });
              }
          }
      }, error: function () { PlgDialog.msg("接口调用失败"); }
  });

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


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

  //返回主页面
  $(document).on("click", "#mstOwnerinfo_btn_back", function () {
      $("#mstOwnerinfo_grid_01_edit").css("display", "none");
      $("#mstOwnerinfo_grid_01").css("display", "block");
      $("#mstOwnerinfo_Template").css("display", "none");
      return false;
  });

  gridInit();

  function gridInit() {
      var ownerInfoOpts = {
          skin: "terrace",
          rowId: "companyid",
          columns: [
              { id: "companyid", name: "id", type: "ro", width: 50, hidden: true },
              { id: "companycode", name: "货主编号", type: "ro", width: 100 },
              { id: "companyname", name: "货主名称", type: "ro", width: 150 },
              { id: "groupno1", name: "分组属性", type: "ro", width: 100 },
              { id: "provincename", name: "省", type: "ro", width: 100, hidden: true },
              { id: "cityname", name: "市", type: "ro", width: 100, hidden: true },
              { id: "areaname", name: "区", type: "ro", width: 100, hidden: true },
              { id: "address", name: "详细地址", type: "ro", width: 200 },
              { id: "contactman", name: "到货联系人", type: "ro", width: 100 },
              { id: "createdate", name: "创建时间", type: "ro", width: 100, hidden: true },
              { id: "createby", name: "创建人", type: "ro", width: 100, hidden: true },
              { id: "lastmodifydate", name: "最后修改时间", type: "ro", width: 150 },
              { id: "lastmodifyby", name: "最后修改人员", type: "ro", width: 100 },
              {
                  id: "op", name: "操作", type: "button", align: "center", width: 180, render: function () {
                      return "详情^mstOwnerinfo_detailClick,复制^mstOwnerinfo_copyClick,修改^mstOwnerinfo_editClick,删除^mstOwnerinfo_deleteClick";
                  }
              }
          ],
          multiselect: true,
          fixedLast: true,
          toolbar: [
              { type: "input", name: "consignname", label: "查询条件:", width: 300, placeholder: "货主编号/货主名称" }, { type: "newcolumn" },
              { type: "button", name: "searchBtn", value: "查询" }, { type: "newcolumn" },
              { type: "button", name: "refreshBtn", className: "normal", value: "重置" }, { type: "newcolumn" },
              { type: "button", name: "impandexpBtn", className: "plg-toolbar-right normal", value: "<i class='layui-icon layui-icon-download-circle'></i>导出" }, { type: "newcolumn" },
              { type: "button", name: "addBtn", className: "plg-toolbar-right", value: "<i class='layui-icon layui-icon-add-1'></i>新增" }, { type: "newcolumn" }
          ],
          formData: [],
          pagebar: {
              buttons: [
                  { text: "删除", className: "layui-btn-danger", name: "delete" }
              ]
          },
          imagePath: "/prologui/dist/images/PlgGrid",
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/consignors",//数据接口
          type: "post",//数据提交方式，默认为get
          params: JSON.stringify(param),//查询提交参数，分页参数默认为pageNum,pageSize
          contentType: "application/json",
          page: true, //是否启用分页
          totalCount: "totalCount" //总记录数字段，默认totalCount
      };
      //分页参数 pageSize pageNum
      grid = new PlgGrid(ownerInfoOpts);
      grid.renderTo("mstOwnerinfo_grid_01");
      grid.loadData();

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

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

      grid.attachToolBarEvent("onButtonClick", function (name) {
          if (name == "searchBtn") { // 查询
              let fdata = grid.getToolBarForm().getFormData();
              grid.setParams(JSON.stringify(fdata));
              grid.reload();
          }
          else if (name == "addBtn") { // 添加
              addmstOwnerinfo();

          }
          else if (name == "impandexpBtn") { // 导入
              //                $('#mstOwnerinfo_grid_01').css("display", 'none');
              //                $('#mstOwnerinfo_grid_01_edit').css("display", 'none');
              //                $('#mstOwnerinfo_Template').css("display", 'block');
              exportExcel();

          }
          else if (name == "download") { // 下载模板
              window.open("/download/单位资料导入模板.xlsx");

          }
          else if (name == "refreshBtn") { // 重置
              grid.getToolBarForm().clear();
              var fdata = grid.getToolBarForm().getFormData();
              fdata.consignname = "";
              grid.setParams(JSON.stringify(fdata));
              grid.reload();
          }
      });

      function exportExcel() {

          var fdata = grid.getToolBarForm().getFormData();
          var obj = JSON.parse(JSON.stringify(fdata));

          var url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/export-consignors?consignname=" + encodeURI(obj.consignname);

          var token = localStorage.getItem("authorization");

          if (token == null || token == "") {
              PlgDialog.msg("登录状态异常，请重新登录！");
              window.location.href = "/menu?path=login";
              return;
          }

          var xhh = new XMLHttpRequest();

          xhh.open("get", url);
          xhh.setRequestHeader("Authorization", token);
          xhh.responseType = "blob";
          xhh.onreadystatechange = function () {
              if (xhh.readyState === 4 && xhh.status === 200) {
                  var filename = "货主资料" + new Date().getTime() + ".xls";
                  var blob = new Blob([xhh.response], { type: "text/xls" });
                  var csvUrl = URL.createObjectURL(blob);
                  var link = document.createElement("a");
                  link.href = csvUrl;
                  link.download = filename;
                  link.click();
              }
          };
          xhh.send();

      }

      utilImportGJ2("mstOwnerinfo_Template1", "mstOwnerinfoImportId", "mstOwnerinfoExportId", "url", function () {
          $("#mstOwnerinfo_grid_01").css("display", "block");
          $("#mstOwnerinfo_grid_01_edit").css("display", "none");
          $("#mstOwnerinfo_Template").css("display", "none");
      });

      grid.attachPageBarEvent(function (name) {
          if (name === "delete") {
              var rowId = grid.getCheckedIds();
              if (!rowId) return;
              var rowIds = rowId.split(",");
              var checkedIds = [];
              rowIds.forEach(v => {
                  checkedIds.push(
                      { companyid: v }
                  );
              });
              Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/batch-delete", "post", "application/json", JSON.stringify(checkedIds), true);
          }
      });
  }

  //添加
  function addmstOwnerinfo() {
      operType = 0;
      var str = "<div class=\"layui-col-lg12\" id=\"mstOwnerinfo_grid_add_content\"></div>";
      $("#mstOwnerinfo_grid_sub").html(str);
      mstOwnerinfoFormInit(0, {});
      $("#mstOwnerinfo_grid_01_edit").css("display", "block");
      $("#mstOwnerinfo_grid_01").css("display", "none");
      $("#mstOwnerinfo_Template").css("display", "none");
  }

  //保存操作
  $("#btn_save_mstOwnerinfo").click(function () {
      var b = form1.validate();
      if (!b) return;
      var fd = form1.getFormData();
      fd.enterpriseid = userGJ.p_enterpriseid;
      if (operType === 0) {
          fd.companyid = fd.companycode;
          save_mstOwnerinfo(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/batch-create", "post", "application/json", JSON.stringify({list: [fd]}));
      }
      else if (operType === 1) {
          save_mstOwnerinfo(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/update-comany", "post", "application/json", JSON.stringify(fd));
      }
  });

  //表单
  function mstOwnerinfoFormInit(ntype, rdata) {
      var tit = "新增货主";
      var rediv = "mstOwnerinfo_grid_sub";
      $("#btn_save_mstOwnerinfo").show();
      if (ntype === 1) {
          tit = "货主 [" + rdata.companyname + "] 信息修改";
      }
      else if (ntype === 2) {
          tit = "货主 [" + rdata.companyname + "] 信息查看";
          $("#btn_save_mstOwnerinfo").hide();
      }
      $("#mstOwnerinfo_span_title").html(tit);
      $("#" + rediv).html("");
      var formcfg = {
          renderer: rediv,
          items: [
              { type: "settings", inputWidth: 200, width: "*", labelWidth: 80, position: "label-left", labelAlign: "left" },
              {
                  type: "block", width: "*",
                  list: [
                      { type: "hidden", name: "companyid", value: "" }, { type: "hidden", name: "companytype", value: "H" },
                      { type: "input", name: "companycode", required: true, labelAlign: "right", label: "货主编号:" },
                      { type: "newcolumn", offset: 40 },
                      { type: "input", name: "companyname", required: true, labelAlign: "right", label: "货主名称:" },
                      { type: "newcolumn", offset: 40 },
                      { type: "input", name: "groupno1", labelAlign: "right", label: "所在区域:" }
                  ]
              },
              {
                  type: "block", width: "*",
                  list: [
                      { type: "combo", readonly: true, name: "province", labelAlign: "right", label: "省:", width: 200, options: rsp_province },
                      { type: "hidden", name: "provincename" },
                      { type: "newcolumn", offset: 40 },
                      { type: "combo", readonly: true, name: "city", labelAlign: "right", label: "市:", width: 200, options: [] },
                      { type: "hidden", name: "cityname" },
                      { type: "newcolumn", offset: 40 },
                      { type: "combo", readonly: true, name: "area", labelAlign: "right", label: "区:", width: 200, options: [] },
                      { type: "hidden", name: "areaname" }
                  ]
              },
              {
                  type: "block", width: "*",
                  list: [
                      { type: "input", name: "contactman", labelAlign: "right", label: "到货联系人:" },
                      { type: "newcolumn", offset: 40 },
                      { type: "input", name: "address", labelAlign: "right", label: "详细地址:" }
                  ]
              }

          ]
      };
      form1 = new PlgForm(formcfg);
      form1.setFormData(rdata);

      if (ntype > 0) {
          form1.loadComboData("city", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", async: false, data: JSON.stringify({ "fatherid": rdata.province }), valueField: "zoneid", textField: "keyvalue" });
          //form1.getCombo("city").setComboText(rdata.cityname == "" ? rdata.city : rdata.cityname);
          form1.setItemValue("city", rdata.city);
          if (rdata.city != null) {
              form1.loadComboData("area", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", async: false, data: JSON.stringify({ "fatherid": rdata.city }), valueField: "zoneid", textField: "keyvalue" });
              //form1.getCombo("area").setComboText(rdata.areaname == "" ? rdata.area : rdata.areaname);
              form1.setItemValue("area", rdata.area);
          }
          form1.disableItem("companycode");
          form1.disableItem("companyname");
      }
      if (ntype === 2) {
          form1.disableAllItem();
      }

      form1.attachComboEvent("province", "onChange", function (id) {
          form1.getCombo("city").setComboText("");
          form1.getInput("provincename").value = form1.getCombo("province").getComboText();
          form1.loadComboData("city", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      });
      form1.attachComboEvent("city", "onChange", function (id) {
          form1.getCombo("area").setComboText("");
          form1.getInput("cityname").value = form1.getCombo("city").getComboText();
          form1.loadComboData("area", { url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ "fatherid": id }), valueField: "zoneid", textField: "keyvalue" });
      });
      form1.attachComboEvent("area", "onChange", function () {
          form1.getInput("areaname").value = form1.getCombo("area").getComboText();
      });

  }

  //保存
  function save_mstOwnerinfo(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,
          success: function (data) {
              PlgDialog.close(pload);
              rep = data;
              if (data.success) {
                  PlgDialog.msg(data.message);
                  setTimeout(function () {
                      $("#mstOwnerinfo_grid_01_edit").css("display", "none");
                      $("#mstOwnerinfo_grid_01").css("display", "block");
                      $("#mstOwnerinfo_Template").css("display", "none");
                      grid.reload();
                  }, 10);
              }
              else {
                  setTimeout(() => { PlgDialog.alert(data.message == null ? "接口调用失败" : data.message); }, 300);
              }
          },
          error: function () { PlgDialog.close(pload); PlgDialog.msg("接口调用失败"); }
      });
      return rep;
  }

  window.mstOwnerinfo_deleteClick = function (rid) {
      var checkedIds = [];
      checkedIds.push({
          companyid: rid
      });
      Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/batch-delete", "post", "application/json", JSON.stringify(checkedIds), false);
  };
  window.mstOwnerinfo_editClick = function (rid, rdata) {
      grid.selectRowById(rid);
      operType = 1;
      mstOwnerinfoFormInit(1, rdata);
      $("#mstOwnerinfo_grid_01_edit").css("display", "block");
      $("#mstOwnerinfo_grid_01").css("display", "none");
      $("#mstOwnerinfo_Template").css("display", "none");
  };
  window.mstOwnerinfo_copyClick = function (rid, rdata) {
      grid.selectRowById(rid);
      operType = 0;
      rdata.companyid = null;
      mstOwnerinfoFormInit(0, rdata);
      $("#mstOwnerinfo_grid_01_edit").css("display", "block");
      $("#mstOwnerinfo_grid_01").css("display", "none");
      $("#mstOwnerinfo_Template").css("display", "none");
  };
  window.mstOwnerinfo_detailClick = function (rid, rdata) {
      grid.selectRowById(rid);
      operType = 2;
      $("#mstOwnerinfo_grid_01_edit").css("display", "block");
      $("#mstOwnerinfo_grid_01").css("display", "none");
      $("#mstOwnerinfo_Template").css("display", "none");
      $("#mstOwnerinfo_span_title").html("货主 [" + rdata.companyname + "] 信息查看");
      $("#btn_save_mstOwnerinfo").hide();
      $("#mstOwnerinfo_grid_sub").removeClass();

      new PlgPanel({
          renderer: "mstOwnerinfo_grid_sub",
          skin: 2,
          header: {
              isShow: true,
              title: "基本信息"
          },
          defaultBody: {
              layoutCol: 3,
              valueBj: true,
              cols: [
                  [
                      { value: rdata.companycode, label: "货主编号" },
                      { value: rdata.companyname, label: "货主名称" },
                      { value: rdata.contactman, label: "到货联系人" },
                      { value: rdata.address, label: "详细地址" }
                  ],
                  [
                      { value: rdata.provincename, label: "省" },
                      { value: rdata.cityname, label: "市" },
                      { value: rdata.areaname, label: "区" },
                      { value: rdata.groupno1, label: "所在区域" }
                  ],
                  [
                      { label: "创建人", value: rdata.createby },
                      { label: "创建时间", value: rdata.createdate },
                      { label: "修改人", value: rdata.lastmodifyby },
                      { label: "修改时间", value: rdata.lastmodifydate }

                  ]
              ]
          }
      });
  };

};