/**
 * guoj
 * 2020.07.08
 * 配送中心
    */
    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 () => {  let formdataJson;
  let objid = "";
  //省
  var province;
  //查询省
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", "post", JSON.stringify({ "fatherid": "01" }), function (data) {
    province = data.data;
    for (let x in province) {
      province[x].text = province[x].keyvalue;
      province[x].value = province[x].zoneid;
    }
    province.unshift({ "text": "", "value": "" });
  }, "application/json");
  var ddfrom = null;
  var bench = { "pageSize": 10, "pageNum": 1 };
  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "100", hidden: true },
      { id: "companycode", name: "机构编号", type: "ro", width: 150 },
      { id: "companyname", name: "机构名称", type: "ro", width: 150 },
      { id: "areaid", name: "上级组织", type: "ro", width: 100 },
      { id: "provincename", name: "省", type: "ro", width: 100 },
      { id: "cityname", name: "市", type: "ro", width: 100 },
      { id: "areaname", name: "区", type: "ro", width: 100 },
      { id: "address", name: "详细地址", type: "ro", width: 100 },
      { id: "contactman", name: "联系人", type: "ro", width: 100 },
      { id: "longitude", name: "经度", type: "ro", width: 120 },
      { id: "latitude", name: "纬度", type: "ro", width: 100 },
      { id: "remark", name: "备注", type: "ro", width: 130 },
      {
        id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 200, render: function (v, rd) {
          if (rd.source === "WMS") {
            return "详情^organization_details";
          }
          return "删除^organization_deleteClick,修改^organization_updataClick,详情^organization_details";
        }
      }
    ],
    multiselect: true,
    fixedLast: true, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "button", className: "btn-normal", name: "querywork", value: "查 询" },
      { type: "newcolumn" },
      { type: "button", className: "", name: "btn_reset", value: "重 置" },
      { type: "newcolumn" },
      { type: "button", className: "btn-normal plg-toolbar-right", name: "addBtn", offsetLeft: 10, value: "<i class='layui-icon layui-icon-add-1'></i>新 增" }],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/page",//数据接口
    type: "post",//数据提交方式，默认为get
    pagebar: {
      buttons: [
        { text: "删除", className: "layui-btn-danger", name: "delete" }
      ]
    },
    contentType: "application/json",
    params: JSON.stringify(bench),//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  var grid = new PlgGrid(opts);
  grid.renderTo("organization_guojzhuans2A");
  $("#organization_guojzhuans2A").addClass("layui-form");
  grid.attachEvent("onDataReady", function () {
    setTimeout(function () {
      layui.form.render();
    }, 200);
  });
  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    if (name == "querywork") {
      /* if (objid == "") {
        layer.msg("请选择菜单节点");
        return;
      } */
      grid.reload();
    }
    if (name == "btn_reset") {
      objid = "";
      grid.setParams(JSON.stringify({ companyid: "" }));
      grid.reload();
      initTree();
    }
    if (name == "addBtn") {
      // if(objid == ""){
      //     layer.msg("请选择菜单节点");
      //     return;
      // }

      setViewName("#organization_div1");
      $("#organization_div4").html("");
      ddfrom = new PlgForm(formdataJson);
      ddfrom.setFormData({ areaid: objid });
      ddfrom.attachEvent("onChange", function (name, value, state) {
        if (name == "isAllowCrossDay") {
          if (state) {
            ddfrom.setRequired("crossDays", true);
          }
          else {
            ddfrom.setRequired("crossDays", false);
          }
        }
      });
      linkage(0, "");
      $("#organization_title").html("新增");
      //时间选择器
      plgDate.render({
        elem: "#org_stime",
         type: "time",
         btns: ["now", "confirm"],
         value: "00:00:00"
      });
      plgDate.render({
        elem: "#org_etime",
         type: "time",
         btns: ["now", "confirm"],
         value: "23:59:59"
      });
    }
  });

  //按钮添加方法
  grid.attachPageBarEvent(function (name) {
    //删除
    if (name == "delete") {
      let data = [];
      let datas = getDeleteAll(grid);
      datas.forEach(v => {
        data.push({ companyid: v });
      });
      data = JSON.stringify(data);
      utilDelete(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/delete", "post", data, function (data) {
        initTree();
        grid.reload();
      }, "application/json");
    }
  });
  //删除
  window.organization_deleteClick = function (rid) {
    grid.selectRowById(rid);
    let data = JSON.stringify([{ companyid: rid }]);
    utilDelete(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/delete", "post", data, function (data) {

      initTree();
      grid.reload();
    }, "application/json");
  };
  //修改
  window.organization_updataClick = function (rid, data) {
    grid.selectRowById(rid);
    $("#organization_div4").html("");
    formdataJson.items.forEach(t => {
      if (t.name == "crossDays") {
        if (data.isAllowCrossDay == "1") {
          t.required = true;
        }
        else {
          t.required = false;
        }
      }
    });
    ddfrom = new PlgForm(formdataJson);
    ddfrom.attachEvent("onChange", function (name, value, state) {
      if (name == "isAllowCrossDay") {
        if (state) {
          ddfrom.setRequired("crossDays", true);
        }
        else {
          ddfrom.setRequired("crossDays", false);
        }
      }
    });
    ddfrom.setFormData(data);
    linkage(1, data);
    setViewName("#organization_div1");
    $("#organization_title").html("编辑");
    //时间选择器
    plgDate.render({
      elem: "#org_stime",
       type: "time",
       btns: ["now", "confirm"],
       value: data.serviceStartTime || "00:00:00"
    });
    plgDate.render({
      elem: "#org_etime",
       type: "time",
       btns: ["now", "confirm"],
       value: data.serviceEndTime || "23:59:59"
    });
  };
  //详情
  window.organization_details = function (rid, rdata) {
    grid.selectRowById(rid);
    setViewName("#organization_div9");
    new PlgPanel({
      renderer: "organization_div422",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [{
            label: "机构编号",
            value: rdata.companycode
          },
          {
            label: "机构名称",
            value: rdata.companyname
          },
          {
            label: "上级组织",
            value: rdata.areaid
          },
          {
            label: "省",
            value: rdata.provincename
          }],
          [
            {
              label: "市",
              value: rdata.cityname
            },
            {
              label: "区",
              value: rdata.areaname
            },
            {
              label: "详细地址",
              value: rdata.address
            },
            {
              label: "联系人",
              value: rdata.contactman
            }
          ],
          [
            {
              label: "经度",
              value: rdata.longitude
            },
            {
              label: "纬度",
              value: rdata.latitude
            },
            {
              label: "备注",
              value: rdata.remark
            }
          ],
          [
            {
              label: "仓库开门时间",
              value: rdata.serviceStartTime
            },
            {
              label: "仓库关门时间",
              value: rdata.serviceEndTime
            },
            {
              label: "允许跨天",
              value: rdata.isAllowCrossDay == "1" ? "是" : "否"
            },
            {
              label: "跨天数",
              value: rdata.crossDays
            }
          ]
        ]
      }
    });
  };
  //跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#organization_div2",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  let dataView = ["#organization_div1", "#organization_div3", "#organization_div9"];
  function setViewName(name) {
    for (var i = 0; i < dataView.length; i++) {
      if (name == dataView[i]) {
        $(name).css("display", "block");
      }
      else {
        $(dataView[i]).css("display", "none");
      }
    }
  }
  formdataJson = {
    renderer: "organization_div4",
    items: [
      { type: "settings", position: "label-left", width: 300, labelWidth: 90, labelAlign: "left" },
      { type: "hidden", name: "companyid", label: "id:", width: 230 },
      { type: "newcolumn" },
      { type: "input", name: "companycode", label: "机构编号:", width: 230, editable: false, validate: "NotEmpty", required: true },
      { type: "newcolumn" },
      { type: "input", name: "companyname", label: "机构名称:", width: 230, validate: "NotEmpty", required: true },
      { type: "newcolumn" },
      {
        type: "input", name: "areaid", label: "上级组织:", width: 230, disabled: true
      },
      { type: "newcolumn" },
      { type: "combo", name: "province", label: "所在省:", width: 230, options: province },
      { type: "newcolumn" },
      { type: "combo", name: "city", label: "所在市:", width: 230 },
      { type: "newcolumn" },
      {
        type: "combo", name: "area", label: "所在区:", width: 230
      },
      { type: "newcolumn" },
      {
        type: "input", name: "address", label: "详细地址:", width: 887, required: true
      },
      { type: "newcolumn" },
      {
        type: "input", name: "contactman", label: "联系人:", width: 230
      },
      { type: "newcolumn" },
      { type: "input", name: "tel", label: "联系方式:", width: 230, maxLength: 11 },
      { type: "newcolumn" },
      { type: "input", name: "longitude", label: "经度:", width: 230 },
      { type: "newcolumn" },
      { type: "input", name: "latitude", label: "纬度:", width: 230 },
      { type: "newcolumn" },
      { type: "input", name: "remark", label: "备注:", width: 230 },
      { type: "newcolumn" },
      { type: "label", name: "serviceStartTime", label: "<div class='label'>仓库开门时间:</div><input class='dhxform_textarea plg-input' readonly style='width: 230px;' id='org_stime' />", width: 320, labelWidth: 320 },
      { type: "newcolumn" },
      { type: "label", name: "serviceEndTime", label: "<div class='label'>仓库关门时间:</div><input class='dhxform_textarea plg-input' readonly style='width: 230px;' id='org_etime' />", width: 320, labelWidth: 315 },
      { type: "newcolumn" },
      { type: "input", name: "crossDays", label: "跨天数:", width: 230, validate: "ValidInteger", maxLength: 4, value: "0", placeholder: "单位天", required: true },
      { type: "newcolumn" },
      { type: "checkbox", name: "isAllowCrossDay", label: "允许跨天:", width: 310, labelWidth: 90, checked: true },
      { type: "hidden", name: "coordinateSystem", value: "GCJ" }
    ]
  };
  //三级联动 type 0-新增 1-修改
  function linkage(type, data) {
    if (type == 1) {
      // 首先更新省市区下拉框数据
      getByPid(data.province, "city", data.city);
      getByPid(data.city, "area", data.area);
    }
    // 最后添加联动关系
    ddfrom.attachComboEvent("province", "onChange", function (id) {
      ddfrom.getCombo("city").clearAll();
      ddfrom.getCombo("city").setComboText("");
      if (id) {
        ddfrom.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" });
      }
    });
    ddfrom.attachComboEvent("city", "onChange", function (id) {
      ddfrom.getCombo("area").clearAll();
      ddfrom.getCombo("area").setComboText("");
      if (id) {
        ddfrom.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" });
      }
    });
  }
  // 获取省市区
  function getByPid(fatherid, comboName, value) {
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/zone/get-by-pid", type: "post", contentType: "application/json", data: JSON.stringify({ fatherid }),
      success: function (res) {
        if (res.success) {
          let list = res.data.map(item => {
            return {
              value: item.zoneid,
              text: item.keyvalue
            };
          });
          // 给combo赋下拉框数据
          ddfrom.getCombo(comboName).addOption(list);
          // 给combo赋值
          const nextData = {};
          nextData[comboName] = value;
          ddfrom.setFormData(nextData);
          return true;
        }
                return false;
      },
      error: function () { PlgDialog.close(pload); return false; }
    });
  }

  //返回
  $(document).on("click", "#organization_return", function () {
    setViewName("#organization_div3");
  });
  //保存
  document.querySelector("#organization_save").onclick = function () {
    //数据data
    var data = ddfrom.getFormData();
    var feik = ddfrom.validate();
    if (!feik) {
      return;
    }
    data.serviceStartTime = $("#org_stime").val();
    data.serviceEndTime = $("#org_etime").val();
    data.cityname = ddfrom.getCombo("city").getComboText();
    data.areaname = ddfrom.getCombo("area").getComboText();
    data.provincename = ddfrom.getCombo("province").getComboText();

    if (data.crossDays && parseInt(data.crossDays) < 0) {
      PlgDialog.msg("跨天数不能为负数");
      return;
    }

    //请求地址和类型
    var url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/update";
    var type = "post";
    var contentType = "application/json";
    //message新增为0，修改为1
    if (data.companyid == null || data.companyid == "") {
      url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/add";
    }
    //调用ajax方法
    utilAjaxGJ(url, type, JSON.stringify(data), function (data) {

      setViewName("#organization_div3");
      initTree();
      grid.reload();
    }, contentType);
  };


  initTree();
  function initTree() {
    var token = window.localStorage.getItem("authorization");
    $("#organization_guojzhuans2BAQB").html("");
    var confing2 = {
      isExpand: true, //是否初始化时展开第一个父节点的所有内容
      renderer: "organization_guojzhuans2BAQB",
      skin: "menu-tree",
      initAjax: {
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/query",
        type: "post",
        contentType: "application/json",
        data: JSON.stringify({ companyid: userGJ.p_enterpriseid })
      },
      setting: {
        async: {
          enable: true,
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/distributionCentre/query",
          type: "post",
          contentType: "application/json",
          autoParam: ["companyid"],
          dataFilter: function (reeId, parentNode, responseData) {

            responseData.data.forEach(function (item) {

              item.isParent = !item.p_leaf;

            });
            return responseData.data;
          },
          headers: {
            "Authorization": token
          }
        },
        check: {
          enable: false
        },
        data: {
          key: {
            name: "companyname",
            title: "companyname"
          },
          simpleData: {
            enable: true,
            idKey: "companyid",
            pIdKey: "areaid",
            rootPId: userGJ.p_enterpriseid,
            id: "companyid"
          }
        },
        callback: {
          //单击事件的回调
          onClick: function (event, treeId, treeNode) {
            objid = treeNode.companyid;
            grid.setParams(JSON.stringify({ companyid: objid }));
            grid.reload();
          }
        }
      }
    };
    tree2 = new PlgZtree(confing2);
  }
};
