
/**
 * guoj
 * 2020.05.25
 * 线路管理
    */
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE, UPCLOUD_RDC_TMS_BUSINESS_SERVICE, UPCLOUD_RDC_TMS_INTERFACE_SERVICE } from '@/config/serviceSettings.js';
import { getSelectGJ, querySysPicture, departmentDialog } from '@/utils/prolog.ajax.js';
import { SeniorSearch } from '../auth/seniorSearch.js';


export default () => {
  // 获取扩展字段
  let gird_opts_list = [], form_opts_list = [], date_list = [];
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/extendedField/list", "post", JSON.stringify({ "extendedObjectCode": "9" }), function (res) {
    extendedFieldList({ list: res.data, className: "layui-col-md6" }, function (res) {
      gird_opts_list = res.gird_opts_list;
      form_opts_list = res.form_opts_list;
      date_list = res.date_list;
    });
  }, "application/json");

  var mapDataList = [];
  var gridTableList = [];
  var map;
  var driving;
  var infowindow;
  var marker;
  var indexs = 0;
  let fromDataJson;
  var grid1, grid2;
  var checkForm1, checkForm2, checkForm3, checkForm4;
  var gridNei1, gridNei2, gridNei3, gridNei4;
  var gridAdjust;
  var tabs;
  var jumpType = true;
  let tree, checkList = [], dialogForm;

  //起点终点仓table
  var userTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "100", hidden: true },
      { id: "code", name: "仓库编号", type: "ro" },
      { id: "name", name: "仓库名称", type: "ro", width: "180" },
      { id: "longitude", name: "经度", type: "ro" },
      { id: "latitude", name: "纬度", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 100 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "name", label: "仓库名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    pagebar: { type: "simple" },

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseBranch/queryBranch", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //线路table
  var lineByMap_Table = {
    columns: [
      { id: "lineId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "lineCode", name: "线路编号", type: "ro" },
      { id: "lineName", name: "线路名称", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left", width: 200 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "lineCode", label: "线路编号:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "lineName", label: "线路名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    multiselect: false,
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/selectLineByMap", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    pagebar: { type: "simple" },
    params: JSON.stringify({}), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount", //总记录数字段，默认totalCount
    beforeLoad: function (table) {
      let dataList = [];
      let indexNum = gridAdjust.getGrid().getRowsNum();
      for (let i = 0; i < indexNum; i++) {
        const element = gridAdjust.getRowData(gridAdjust.getRowId(i));
        dataList.push(element.lineId);
      }
      table.params = JSON.stringify(dataList);
    }
  };
  //车牌号table
  var vahicleTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "车辆编码", type: "ro" },
      { id: "plateNumber", name: "车牌号", type: "ro" }
      // { id: "vehicleSpecs", name: "规格编号", type: "ro" },
      // { id: "vehicleSpecsName", name: "规格名称", type: "ro" }
    ],
    toolbar: [
      { type: "settings", position: "label-left", width: 200 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "code", label: "车辆编码:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "plateNumber", label: "车牌号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    multiselect: false,
    beforeLoad: function (table) {
      let rdata = gridNei4.getSelectedRowData();
      table.params = JSON.stringify({ driverId: rdata.carrierId });
    },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/vehicle/popup", //数据接口
    type: "post", //数据提交方式，默认为get
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 司机table
  var driverTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "司机编号", type: "ro" },
      { id: "name", name: "司机名称", type: "ro" },
      { id: "phoneNumber", name: "手机号", type: "ro" },
      { id: "typeName", name: "归属", type: "ro" },
      { id: "affiliationName", name: "隶属机构", type: "ro" }
    ],
    multiselect: true,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 60 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "code", label: "司机编号:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "name", label: "司机名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/driver/popup", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    pagebar: { type: "simple" },
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 承运商table
  var carrierTable = {
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "承运商编号", type: "ro" },
      { id: "name", name: "承运商名称", type: "ro" }
    ],
    multiselect: true,
    toolbar: [
      { type: "settings", position: "label-left" },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "carrierCode", label: "承运商编码:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "carrierName", label: "承运商名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/carrier/page", //数据接口
    type: "post", //数据提交方式，默认为get
    pagebar: { type: "simple" },
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  // 客户table
  var clientTable01 = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "客户编码", type: "ro" },
      { id: "name", name: "客户名称", type: "ro" }
    ],
    multiselect: true,
    toolbar: [
      { type: "settings", position: "label-left", width: 200 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "customerCode", label: "客户编码:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "customerName", label: "客户名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/queryCustomerAndReceiver",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  var ddfrom = null;
  let dataSelete;
  //获取下拉框
  getSelectGJ([
    { "objectcode": "TRANSPORT_TYPE" },
    { "objectcode": "LINE_TYPE" },
    { "objectcode": "PLANTYPE" },
    { "objectcode": "LINE_CARRIER_TYPE" },
    { "objectcode": "LINE_BASIS" },
    { "objectcode": "DISTINGUISH_TYPE" },
    { "objectcode": "LINE_START_TYPE" },
  ], function (data) {
    data.data.TRANSPORT_TYPE.unshift({ "text": "", "value": "" });
    data.data.PLANTYPE.unshift({ "text": "", "value": "" });
    data.data.LINE_CARRIER_TYPE.unshift({ "text": "", "value": "" });
    data.data.LINE_BASIS.unshift({ "text": "", "value": "" });
    dataSelete = data.data;
  });
  // 查询省
  var provinceEnums = []
  utilSyncAjaxGJ(
    UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/zone/get-by-pid',
    'post',
    JSON.stringify({ fatherid: '01' }),
    function (data) {
      provinceEnums = data.data
      for (let x in provinceEnums) {
        provinceEnums[x].text = provinceEnums[x].keyvalue
        provinceEnums[x].value = provinceEnums[x].zoneid
      }
      provinceEnums.unshift({ value: '', text: '' })
    },
    'application/json'
  )

  let gird_opts_columns = [
    { id: "lineId", name: "id", type: "ro", width: "100", hidden: true },
    { id: "lineCode", name: "线路编码", type: "ro", width: 150 },
    { id: "lineName", name: "线路名称", type: "ro", width: 100 },
    { id: "departmentName", name: "部门", type: "ro", width: 120 },
    // { id: "organizationName", name: "所属组织", type: "ro", width: 120 },
    { id: "departmentName", name: "所属部门", type: "ro", width: 120 },
    { id: "startLineName", name: "线路起点", type: "ro", width: 100 },
    { id: "endLineName", name: "线路终点", type: "ro", width: 100 },
    { id: "carrierTypeName", name: "承运方类型", type: "ro", width: 100 },
    {
      id: "limit", name: "是否承运商限额限制", type: "ro", width: 150,
      render: (v, rd) => {
        return rd.limit == "1" ? "是" : "否";
      }
    },
    { id: "basisName", name: "限制依据", type: "ro", width: 100 },
    { id: "totalMileage", name: "总里程数", type: "ro", width: 100 },
    { id: "memo", name: "备注", type: "ro", width: 100 },
    {
      id: "status", name: "状态", type: "ro", width: 100,
      render: (v, rd) => {
        return rd.status == "10" ? "启用" : "禁用";
      }
    }
  ];
  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: gird_opts_columns.concat(gird_opts_list, [
      { id: "createperson", name: "创建人", type: "ro", width: 100 },
      { id: "createtime", name: "创建时间", type: "ro", width: 150 },
      { id: "updateperson", name: "修改人", type: "ro", width: 100 },
      { id: "updatetime", name: "修改时间", type: "ro", width: 150 },
      {
        id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 200, render: function (v, rd) {
          //
          let result = "^lineInformation_enable,查看^lineInformation_details,修改^lineInformation_updataClick,删除^lineInformation_deleteClick";
          if (rd.status == "10") {
            result = "停用" + result;
          }
          else {
            result = "启用" + result;
          }
          return result;
        }
      }]
    ),
    multiselect: true,
    fixedLast: true, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md2", name: "lineCode", label: "线路编码:", placeholder: "请输入线路编码" },
          { type: "input", className: "layui-col-md2", name: "lineName", label: "线路名称:", placeholder: "请输入线路名称" },

          {
            type: "block", className: "layui-col-md3 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "querywork", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "work_Reset", value: "重 置" },
              // { type: "newcolumn" },
              // { type: "button", className: "btn-normal", name: "master_seniorSearch", value: "高级查询" }
            ]
          },
          {
            type: "block", className: "layui-col-md5 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_calculated_mileage", value: "计算里程" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_jump_map", value: "地图" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "addBtn", value: "新 增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_Import", value: "导入" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_del", value: "删除" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_enable", value: "启用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_deactivate", value: "停用" }
            ]
          }
        ]
      }
    ],



    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/query",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: "{}",//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  let grid = new PlgGrid(opts);
  grid.renderTo("lineInformation_guojzhuans2");
  $("#lineInformation_guojzhuans2").addClass("layui-form");
  grid.attachEvent("onDataReady", function () {
    setTimeout(function () {
      layui.form.render();
    }, 200);
  });
  grid.loadData();
  // let seniorSearch = new SeniorSearch("ImportQuery", grid);
  // seniorSearch.listAll();

  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    if (name == "querywork") {
      var fdata = grid.getToolBarForm().getFormData();
      grid.setParams(JSON.stringify(fdata));
      grid.reload();
    }
    if (name == "addBtn") {
      setView("#lineInformation_div1");
      $("#lineInformation_div4").html("");
      ddfrom = new PlgForm(fromDataJson);
      provinceCityDistrict({})

      // 部门弹窗
      departmentDialog("#lineInformation_div4", ddfrom)

      setMethodCombo();
      ddfrom.setFormData({ carrierType: "1" })
      $("#lineInformation_title").html("新增");

      gridNei1.getToolBarForm().clear();
      gridNei1.getToolBarForm().getDForm().setText("clientTable01List", "");
      gridNei1.getGrid().clearAll();
      gridNei2.getGrid().clearAll();

      $("#lineInformation_save").show();
      ddfrom.enableItem();
      gridNei1.getToolBarForm().enableAllItem();
      gridNei2.getToolBarForm().enableAllItem();
      gridNei2.getToolBarForm().disableItem("master_jump_map");
      gridNei3.getToolBarForm().enableAllItem();
      gridNei4.getToolBarForm().enableAllItem();

      jumpType = true;

      checkList = []
      treeInit(false)
    }
    if (name == "work_Reset") {
      grid.getToolBarForm().clear();
      grid1.getGrid().clearAll();
      grid2.getGrid().clearAll();
      checkForm1.clear();
      checkForm2.clear();
      checkForm3.clear();
      checkForm4.clear();
      tabs.changeTabs("lineInformation_div3_bottomTab1");

    }
    // 高级搜索
    // if (name == "master_seniorSearch") {
    //   seniorSearch.dialog();
    // }
    // 计算里程
    if (name == "master_calculated_mileage") {

      let ids = grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let idsArr = ids.split(",");

      let par = [];
      idsArr.forEach(v => {
        let rd = grid.getRowData(v);

        let arr = [];
        rd.coordinates.forEach((item, index) => {
          arr.push(new AMap.LngLat(item.longitude, item.latitude));
        });

        let distance = Math.round(AMap.GeometryUtil.distanceOfLine(arr));


        par.push(
          { lineId: v, distance: distance }
        );
      });

      master_calculated_mileage_function(par, "1");


    }
    // 地图
    if (name == "master_jump_map") {
      let ids = grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let idsArr = ids.split(",");


      let par = [];
      idsArr.forEach(v => {
        par.push(
          { lineId: v }
        );
      });
      getMapPageData(par);


    }
    // 导入
    if (name == "master_Import") {
      importDialog();
    }
    // 删除
    if (name == "master_del") {
      let ids = grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let idsArr = ids.split(",");
      let checkedIds = [];
      idsArr.forEach(v => {
        checkedIds.push(
          { lineId: v }
        );
      });

      utilDelete(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/neverDelete", "post", JSON.stringify(checkedIds), function (data) {
        grid.reload();
      }, "application/json");
    }
    // 启用
    if (name == "master_enable") {
      let ids = grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let idsArr = ids.split(",");
      let checkedIds = [];
      idsArr.forEach(v => {
        let rd = grid.getRowData(v);
        checkedIds.push(
          { lineId: v, status: rd.status }
        );
      });
      layer.open({
        title: "启用",
        content: "是否启用？",
        btn: ["确认", "取消"],
        yes: function () {
          enable(checkedIds);
        }
      });
    }
    // 停用
    if (name == "master_deactivate") {
      let ids = grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let idsArr = ids.split(",");
      let checkedIds = [];
      idsArr.forEach(v => {
        let rd = grid.getRowData(v);
        checkedIds.push(
          { lineId: v, status: rd.status }
        );
      });

      layer.open({
        title: "停用",
        content: "是否停用？",
        btn: ["确认", "取消"],
        yes: function () {
          enable(checkedIds);
        }
      });


    }
  });


  grid.on("onRowSelect", function (id, index) {
    if (indexs == 0) {
      grid1.setParams(JSON.stringify({
        lineId: id
      }));
      grid1.reload();
      // 注册grid1方法
      gridRender();
    }
    else if (indexs == 1) {
      grid2.setParams(JSON.stringify({
        lineId: id
      }));
      grid2.reload();
    }
    else if (indexs == 2) {
      //请求地址和类型
      var url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/dateQuery";
      var type = "post";
      var contentType = "application/json";
      //message新增为0，修改为1
      //调用ajax方法
      utilAjaxGJ(url, type, JSON.stringify({ lineId: id }), function (res) {
        checkForm1.setFormData({
          lineId: res.data.lineId
        });
        checkForm2.setFormData(res.data.weeks);
        checkForm4.setFormData(res.data.days);

      }, contentType);
    }
  });

  // 启用停用公用方法
  function enable(par) {
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/remove",
      type: "post",
      contentType: "application/json",
      data: JSON.stringify(par),
      success: function (data) {
        PlgDialog.close(pload);
        if (data.success) {
          layer.closeAll();
          PlgDialog.msg(data.message);
          grid.reload();
          return true;
        }
        return false;

      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
  // 启用/停用单行点击
  window.lineInformation_enable = function (rid, rdata) {
    let text = rdata.status === 10 ? "停用" : "启用";
    layer.open({
      title: text,
      content: "是否" + text + "？",
      btn: ["确认", "取消"],
      yes: function () {
        enable([
          {
            lineId: rid, status: rdata.status
          }
        ]);
      }
    });


  };


  // 计算里程公用方法
  function master_calculated_mileage_function(par, type) {
    let str = "";

    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/calculate",
      type: "post",
      contentType: "application/json",
      async: false,
      data: JSON.stringify(par),
      success: function (data) {

        if (data.success) {
          // 列表
          if (type == "1") {
            grid.reload();
          }
          // 查看地图回显
          else if (type == "2") {
            str = data.data;
          }
        }
      }
    });
    if (type == "2") {
      return str;
    }


  }


  //删除
  window.lineInformation_deleteClick = function (rid, rdata) {
    grid.selectRowById(rid);
    rdata = JSON.stringify([{ lineId: rid }]);
    utilDelete(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/neverDelete", "post", rdata, function (data) {
      grid.reload();
    }, "application/json");
  };
  //修改
  window.lineInformation_updataClick = function (rid) {

    grid.selectRowById(rid);

    // 查看接口
    utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/view", "post", JSON.stringify({
      lineId: rid
    }), function (res) {
      let data = res.data;
      data.buyername1 = data.startLineCode ? JSON.stringify([data.startLineCode]) : ''
      data.buyername3 = data.endLineCode ? JSON.stringify([data.endLineCode]) : ''
      $("#lineInformation_div4").html("");
      ddfrom = new PlgForm(fromDataJson);


      // 部门弹窗
      departmentDialog("#lineInformation_div4", ddfrom)

      // ddfrom.disableItem("lineCode");
      setMethodCombo();

      ddfrom.setFormData(data);
      provinceCityDistrict(data)

      ddfrom.getDForm().setText("buyername1", data.startLineName || "");
      ddfrom.getDForm().setText("buyername3", data.endLineName || "");

      gridNei1.getToolBarForm().clear();
      gridNei1.getToolBarForm().getDForm().setText("clientTable01List", "");
      gridNei1.getGrid().clearAll();

      gridNei2.getGrid().clearAll();
      if (data.tmsArriverDTOs.length) {
        gridNei2.loadData({
          data: {
            list: data.tmsArriverDTOs
          }
        });
      }

      if (data.tmsCarrierDTOs.length) {
        if (data.carrierType == "1") {
          gridNei3.loadData({
            data: {
              list: data.tmsCarrierDTOs
            }
          });
        }
        else if (data.carrierType == "2") {
          gridNei4.loadData({
            data: {
              list: data.tmsCarrierDTOs
            }
          });
          for (let i = 0; i < data.tmsCarrierDTOs.length; i++) {
            gridNei4.setCellValue(data.tmsCarrierDTOs[i].carrierId, 6, { "text": data.tmsCarrierDTOs[i].vehiclePlateNumber, "value": data.tmsCarrierDTOs[i].vehiclePlateNumber });
          }
        }
      }
      else {
        if (data.carrierType == "1") {
          gridNei3.getGrid().clearAll();
        }
        else if (data.carrierType == "2") {
          gridNei4.getGrid().clearAll();
        }
        else {
          gridNei3.getGrid().clearAll();
          gridNei4.getGrid().clearAll();
        }
      }

      $("#lineInformation_save").show();
      ddfrom.enableItem();
      gridNei1.getToolBarForm().enableAllItem();
      gridNei2.getToolBarForm().enableAllItem();
      gridNei3.getToolBarForm().enableAllItem();
      gridNei4.getToolBarForm().enableAllItem();


      setView("#lineInformation_div1");
      $("#lineInformation_title").html("编辑");

      jumpType = true;

      checkList = data.administrativeAreas || []
      treeInit(false)
    }, "application/json");


  };
  //查看
  window.lineInformation_details = function (rid, rdata) {


    grid.selectRowById(rid);

    // 查看接口
    utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/view", "post", JSON.stringify({
      lineId: rid
    }), function (res) {
      let data = res.data;
      $("#lineInformation_div4").html("");
      ddfrom = new PlgForm(fromDataJson);
      // ddfrom.disableItem("lineCode");
      setMethodCombo();

      ddfrom.setFormData(data);
      provinceCityDistrict(data)

      gridNei2.getGrid().clearAll();
      if (data.tmsArriverDTOs.length) {
        gridNei2.loadData({
          data: {
            list: data.tmsArriverDTOs
          }
        });
      }

      if (data.tmsCarrierDTOs.length) {
        if (data.carrierType == "1") {
          gridNei3.loadData({
            data: {
              list: data.tmsCarrierDTOs
            }
          });
        }
        else if (data.carrierType == "2") {
          gridNei4.loadData({
            data: {
              list: data.tmsCarrierDTOs
            }
          });
          for (let i = 0; i < data.tmsCarrierDTOs.length; i++) {
            gridNei4.setCellValue(data.tmsCarrierDTOs[i].carrierId, 6, { "text": data.tmsCarrierDTOs[i].vehiclePlateNumber, "value": data.tmsCarrierDTOs[i].vehiclePlateNumber });
          }
        }
      }
      else {
        if (data.carrierType == "1") {
          gridNei3.getGrid().clearAll();
        }
        else if (data.carrierType == "2") {
          gridNei4.getGrid().clearAll();
        }
        else {
          gridNei3.getGrid().clearAll();
          gridNei4.getGrid().clearAll();
        }
      }

      $("#lineInformation_save").hide();
      ddfrom.disableAllItem();
      gridNei1.getToolBarForm().disableAllItem();
      gridNei2.getToolBarForm().disableAllItem();
      gridNei3.getToolBarForm().disableAllItem();
      gridNei4.getToolBarForm().disableAllItem();

      setView("#lineInformation_div1");
      $("#lineInformation_title").html("查看");

      jumpType = false;

      checkList = data.administrativeAreas || []
      treeInit(true)
    }, "application/json");


    // grid.selectRowById(rid);
    // setView("#lineInformation_div9");
    // new PlgPanel({
    //     renderer: "lineInformation_div422",
    //     skin: 2,
    //     header: {
    //         isShow: true,
    //         title: "基本信息"
    //     },
    //     defaultBody: {
    //         layoutCol: 3,
    //         valueBj: true,
    //         cols: [
    //             [{
    //                 label: "配送中心/站点",
    //                 value: rdata.branchName
    //             },
    //             {
    //                 label: "线路编号",
    //                 value: rdata.lineCode
    //             },
    //             {
    //                 label: "线路名称",
    //                 value: rdata.lineName
    //             },
    //             {
    //                 label: "线路类型",
    //                 value: rdata.lineTypename
    //             }],
    //             [
    //                 {
    //                     label: "规划类型",
    //                     value: getSelectValue(dataSelete.PLANTYPE, rdata.planType)
    //                 },
    //                 {
    //                     label: "单位名称",
    //                     value: rdata.companyName
    //                 },
    //                 {
    //                     label: "区划层级",
    //                     value: rdata.regionLevels
    //                 },
    //                 {
    //                     label: "区划编号",
    //                     value: rdata.regionCode
    //                 }
    //             ],
    //             [
    //                 {
    //                     label: "区划名称",
    //                     value: rdata.regionName
    //                 },
    //                 {
    //                     label: "目的站点",
    //                     value: rdata.nextBranchName
    //                 },
    //                 {
    //                     label: "运输类型",
    //                     value: getSelectValue(dataSelete.TRANSPORT_TYPE, rdata.goodtype)
    //                 },
    //                 {
    //                     label: "备注",
    //                     value: rdata.memo
    //                 }
    //             ],
    //             [
    //                 {
    //                     label: "首选承运商",
    //                     value: rdata.carrierName
    //                 },
    //                 {
    //                     label: "首选司机",
    //                     value: rdata.driverName
    //                 },
    //                 {
    //                     label: "首选车辆",
    //                     value: rdata.vehiclePlateNumber
    //                 }
    //             ]
    //         ]
    //     }
    // });
  };


  var tabcfg = {
    renderer: "lineInformation_div3_bottomTab",
    indexActive: 0,
    content: [
      {
        title: "收货方信息",
        id: "lineInformation_div3_bottomTab1",
        template: "<div id=\"lineInformation_div3_bottomTab1_01\" style=\"height:100%;padding: 0px;\"></div>"
      },
      {
        title: "承运方信息",
        id: "lineInformation_div3_bottomTab2",
        template: "<div id=\"lineInformation_div3_bottomTab1_02\" style=\"height:100%;padding: 0px;\"></div>"
      },
      {
        title: "线路可用日期",
        id: "lineInformation_div3_bottomTab3",
        template: "<div id=\"lineInformation_div3_bottomTab1_03\" style=\"height:100%;padding: 0px;\">" +
          "<div id=\"lineInformation_div3_bottomTab1_03_form1\"></div>" +
          "<div id=\"lineInformation_div3_bottomTab1_03_form2\"></div>" +
          "<div id=\"lineInformation_div3_bottomTab1_03_form3\"></div>" +
          "<div id=\"lineInformation_div3_bottomTab1_03_form4\"></div>" +
          "</div>"
      }
    ]
  };
  tabs = new PlgTabs(tabcfg);


  let gridopt0 = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "consigneeId", name: "id", type: "ro", width: "100", hidden: true },
      { id: "customerCode", name: "客户编码", type: "ro", width: 100 },
      { id: "customerName", name: "客户名称", type: "ro", width: 150 },
      { id: "consigneeCode", name: "收货方编码", type: "ro", width: 150 },
      { id: "consigneeName", name: "收货方名称", type: "ro", width: 100 },
      { id: "consigneeContact", name: "联系人", type: "ro", width: 100 },
      { id: "consigneePhoneNumber", name: "联系方式", type: "ro", width: 150 },
      { id: "consigneeAddress", name: "收货方地址", type: "ro", width: 150 },
      { id: "consigneeMemo", name: "收货方备注", type: "ro", width: 150 },
      { id: "deliveryOrder", name: "配送顺序", type: "ro", width: 150 },


      { id: "lineId", name: "线路ID", type: "ro", width: 150, hidden: true },
      { id: "customerId", name: "客户ID(隐藏)", type: "ro", width: 150, hidden: true },

      {
        id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 200, render: function () {
          return "删除^lineInformation_div3_bottomTab1_01_del";
        }
      }
    ],
    multiselect: true,
    fixedLast: true, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-danger", name: "lineInformation_div3_bottomTab1_01_del_all", value: "删除" }
            ]
          }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/tmsArriverPage",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: "{}",//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid1 = new PlgGrid(gridopt0);
  grid1.renderTo("lineInformation_div3_bottomTab1_01");
  $("#lineInformation_div3_bottomTab1_01").addClass("layui-form");
  grid1.attachEvent("onDataReady", function () {
    setTimeout(function () {
      layui.form.render();
    }, 200);
  });


  tabs.on(function (ele) {
    //设置table是哪页
    indexs = ele.index;
    if (indexs == 0) {


      let rid = grid.getCheckedIds();

      let rowId = grid.getSelectedRowId();
      if (!rowId) {
        // layer.msg("请单击行选择一条线路");
        return;
      }

      // let ids = rid.split(",");
      // if (ids.length > 1) {
      //     layer.msg("只允许单击行选择一条线路");
      //     grid1.getGrid().clearAll();
      //     return;
      // }

      // if (grid == null) {


      grid1.setParams(JSON.stringify({
        lineId: rowId
      }));
      grid1.reload();
      // 注册grid1方法
      gridRender();


      // }
    }
    if (indexs == 1) {


      let rid = grid.getCheckedIds();

      let rowId = grid.getSelectedRowId();
      if (!rowId) {
        // layer.msg("请单击行选择一条线路");
        return;
      }

      // let ids = rid.split(",");
      // if (ids.length > 1) {
      //     layer.msg("只允许勾选一条线路");
      //     return;
      // }


      // if (grid2 == null) {
      let gridopt1 = {
        skin: "card",
        rowId: "carrierCode",
        columns: [
          { id: "carrierCode", name: "行id", type: "ro", width: "100", hidden: true },
          { id: "carrierCode", name: "承运商编码", type: "ro", width: "150" },
          { id: "carrierName", name: "承运商名称", type: "ro", width: "150" },
          { id: "phoneNumber", name: "手机号", type: "ro", width: "150" },
          { id: "vehiclePlateNumber", name: "车牌号", type: "ro", width: "150" },
          { id: "shares", name: "份额", type: "ed", width: "150" },
          { id: "lineId", name: "线路ID", type: "ro", width: "150", hidden: true },

          {
            id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 200, render: function () {
              return "删除^lineInformation_div3_bottomTab1_02_del";
            }
          }
        ],
        multiselect: true,
        fixedLast: true, //开启固定列，固定最后一行，倒数第二列不能隐藏
        toolbar: [
          { type: "settings", labelWidth: 90, labelAlign: "right" },
          {
            type: "row",
            list: [
              {
                type: "block", className: "layui-col-md12 right",
                list: [
                  { type: "button", className: "btn-normal", name: "lineInformation_div3_bottomTab1_02_save", value: "保存" },
                  { type: "newcolumn" },
                  { type: "button", className: "btn-danger", name: "lineInformation_div3_bottomTab1_02_del_all", value: "删除" }
                ]
              }
            ]
          }
        ],
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/tmsCarrierPage",//数据接口
        type: "post",//数据提交方式，默认为get
        contentType: "application/json",
        params: "{}",//查询提交参数，分页参数默认为pageNum,pageSize
        page: true, //是否启用分页
        totalCount: "totalCount"
      };
      grid2 = new PlgGrid(gridopt1);
      grid2.renderTo("lineInformation_div3_bottomTab1_02");

      grid2.setParams(JSON.stringify({
        lineId: rowId
      }));
      grid2.reload();

      grid2.getGrid().enableEditEvents(true, false, true);

      grid2.attachToolBarEvent("onButtonClick", function (name) {
        if (name == "lineInformation_div3_bottomTab1_02_del_all") {
          var ids = grid2.getCheckedIds();
          if (!ids) {
            layer.msg("请选择数据");
            return false;
          }

          layer.open({
            title: _t("删除"),
            content: _t("还未保存，是否删除?"),
            btn: [_t("确认"), _t("取消")],
            yes: function () {
              ids.split(",").forEach(id => {
                grid2.deleteRow(id);
              });
              layer.closeAll();
            }
          });
        }
        if (name == "lineInformation_div3_bottomTab1_02_save") {

          let dataList = [];
          let indexNum = grid2.getGrid().getRowsNum();
          for (let i = 0; i < indexNum; i++) {
            const element = grid2.getRowData(grid2.getRowId(i));
            dataList.push(element);
          }

          let num = 0;
          dataList.forEach((item, index) => {
            num += Number(item.shares);
          });
          if (num != 100) {
            PlgDialog.msg("份额总和必须为100!");
            return;
          }
          // 调用保存接口
          utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/tmsCarrierSave", "post", JSON.stringify(dataList), function (data) {
            if (data.success) {
              grid2.reload();
            }
          }, "application/json");
        }
      });

      //离开事件
      grid2.attachEvent("onEditCell", function (stage, rId, cInd, nValue) {
        let rd = grid2.getRowData(rId);
        if (cInd == 7 && stage == 2) {
          nValue = isNaN(nValue * 1) ? 0 : nValue;
          if (cInd == 7 && !/^\d+$/.test(nValue)) {
            layer.msg("请输入非负整数");
            return;
          }
          grid2.setCellValue(rId, cInd, nValue);
        }
        else if (stage == 2) {
          grid2.setCellValue(rId, cInd, nValue);
        }
        return true;
      });

    }
    if (indexs == 2) {

      let rid = grid.getCheckedIds();

      let rowId = grid.getSelectedRowId();
      if (!rowId) {
        // layer.msg("请单击行选择一条线路");
        return;
      }

      var checkForm1OPT = {
        renderer: "lineInformation_div3_bottomTab1_03_form1",
        items: [
          { type: "settings", labelAlign: "right", labelWidth: 80 },

          {
            type: "row",
            list: [
              { type: "checkbox", label: "全选:", name: "checkTopAll" },
              { type: "hidden", name: "lineId" }
            ]
          }

        ]
      };
      checkForm1 = new PlgForm(checkForm1OPT);

      var checkForm2OPT = {
        renderer: "lineInformation_div3_bottomTab1_03_form2",
        items: [
          { type: "settings", labelAlign: "right", labelWidth: 80 },

          {
            type: "row",
            list: [
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "星期一:", name: "week_1" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "星期二:", name: "week_2" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "星期三:", name: "week_3" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "星期四:", name: "week_4" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "星期五:", name: "week_5" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "星期六:", name: "week_6" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "星期日:", name: "week_7" }
                ]
              }
            ]
          }
        ]
      };
      checkForm2 = new PlgForm(checkForm2OPT);

      var checkForm3OPT = {
        renderer: "lineInformation_div3_bottomTab1_03_form3",
        items: [
          { type: "settings", labelAlign: "right", labelWidth: 80 },

          {
            type: "row",
            list: [
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "全选:", name: "checkbotAll" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "单号:", name: "checkbotS" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "双号:", name: "checkbotE" }
                ]
              }
            ]
          }


        ]
      };
      checkForm3 = new PlgForm(checkForm3OPT);

      var checkForm4OPT = {
        renderer: "lineInformation_div3_bottomTab1_03_form4",
        items: [
          { type: "settings", labelAlign: "right", labelWidth: 80 },
          {
            type: "row",
            list: [
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "1:", name: "day_1" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "2:", name: "day_2" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "3:", name: "day_3" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "4:", name: "day_4" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "5:", name: "day_5" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "6:", name: "day_6" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "7:", name: "day_7" }
                ]
              },
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "8:", name: "day_8" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "9:", name: "day_9" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "10:", name: "day_10" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "11:", name: "day_11" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "12:", name: "day_12" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "13:", name: "day_13" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "14:", name: "day_14" }
                ]
              },
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "15:", name: "day_15" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "16:", name: "day_16" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "17:", name: "day_17" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "18:", name: "day_18" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "19:", name: "day_19" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "20:", name: "day_20" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "21:", name: "day_21" }
                ]
              },
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "22:", name: "day_22" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "23:", name: "day_23" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "24:", name: "day_24" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "25:", name: "day_25" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "26:", name: "day_26" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "27:", name: "day_27" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "28:", name: "day_28" }
                ]
              },
              {
                type: "block", className: "layui-col-md12 pl-0",
                list: [
                  { type: "checkbox", label: "29:", name: "day_29" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "30:", name: "day_30" },
                  { type: "newcolumn" },
                  { type: "checkbox", label: "31:", name: "day_31" }
                ]
              }
            ]
          },
          {
            type: "row",
            list: [
              {
                type: "block", className: "layui-col-md12 pl-0 center",
                list: [
                  { type: "button", className: "btn-normal", name: "lineInformation_div3_bottomTab1_03_form4_save", value: "保存" }
                ]
              }
            ]
          }


        ]
      };
      checkForm4 = new PlgForm(checkForm4OPT);


      //请求地址和类型
      var url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/dateQuery";
      var type = "post";
      var contentType = "application/json";
      //message新增为0，修改为1
      //调用ajax方法
      utilAjaxGJ(url, type, JSON.stringify({ lineId: rowId }), function (res) {
        checkForm1.setFormData({
          lineId: res.data.lineId
        });
        checkForm2.setFormData(res.data.weeks);
        checkForm4.setFormData(res.data.days);

      }, contentType);


      checkForm1.attachEvent("onChange", function (name, value, boolean, state) {
        //state 单选/复选时使用
        let waitObj2 = {};
        waitObj2 = checkForm2.getFormData();
        let waitObj4 = {};
        waitObj4 = checkForm4.getFormData();

        let flag4 = false;
        for (var item in waitObj4) {
          if (waitObj4[item] == "1") {
            flag4 = true;
            break;
          }
        }

        if (flag4) {
          layer.msg("已按日选择");

          for (var item4 in waitObj2) {
            waitObj2[item4] = "0";
          }
          checkForm2.setFormData(waitObj2);
          checkForm1.setFormData({
            checkTopAll: "0"
          });

          return;
        }

        if (name == "checkTopAll") {
          if (boolean == true) {
            for (var item1 in waitObj2) {
              waitObj2[item1] = "1";
            }
            checkForm2.setFormData(waitObj2);
          }
          else {
            for (var item2 in waitObj2) {
              waitObj2[item2] = "0";
            }
            checkForm2.setFormData(waitObj2);
          }
        }
      });

      checkForm2.attachEvent("onChange", function (name, value, boolean, state) {
        //state 单选/复选时使用

        let waitObj2 = {};
        waitObj2 = checkForm2.getFormData();
        let waitObj4 = {};
        waitObj4 = checkForm4.getFormData();

        let flag4 = false;
        for (var item in waitObj4) {
          if (waitObj4[item] == "1") {
            flag4 = true;
            break;
          }
        }

        if (flag4) {
          layer.msg("已按日选择");

          for (var item2 in waitObj2) {
            waitObj2[item2] = "0";
          }
          checkForm2.setFormData(waitObj2);

          return;
        }


        checkForm1.setFormData({
          checkTopAll: "0"
        });


      });

      checkForm3.attachEvent("onChange", function (name, value, boolean, state) {
        //state 单选/复选时使用
        let waitObj2 = {};
        waitObj2 = checkForm2.getFormData();
        let waitObj3 = {};
        waitObj3 = checkForm3.getFormData();
        let waitObj4 = {};
        waitObj4 = checkForm4.getFormData();

        let flag2 = false;
        for (var item2 in waitObj2) {
          if (waitObj2[item2] == "1") {
            flag2 = true;
            break;
          }
        }

        if (flag2) {
          layer.msg("已按周选择");

          for (var item3 in waitObj3) {
            waitObj3[item3] = "0";
          }
          checkForm3.setFormData(waitObj3);

          for (var item4 in waitObj4) {
            waitObj4[item4] = "0";
          }
          checkForm3.setFormData(waitObj3);
          checkForm4.setFormData(waitObj4);

          return;
        }


        // 全选
        if (name == "checkbotAll") {
          checkForm3.setFormData({
            checkbotS: "0",
            checkbotE: "0"
          });
          if (boolean == true) {
            for (var item5 in waitObj4) {
              waitObj4[item5] = "1";
            }
            checkForm4.setFormData(waitObj4);
          }
          else {
            for (var item6 in waitObj4) {
              waitObj4[item6] = "0";
            }
            checkForm4.setFormData(waitObj4);
          }
        }
        // 单号
        if (name == "checkbotS") {
          checkForm3.setFormData({
            checkbotAll: "0",
            checkbotE: "0"
          });
          for (let item4 in waitObj4) {
            waitObj4[item4] = "0";
          }
          checkForm4.setFormData(waitObj4);
          if (boolean == true) {
            for (var item7 in waitObj4) {

              let str = "";
              let index = item7.lastIndexOf("_");
              str = item7.substring(index + 1, item7.length);

              if (Number(str) % 2 != 0) {
                waitObj4[item7] = "1";
              }
            }
            checkForm4.setFormData(waitObj4);
          }
          else {
            for (var item8 in waitObj4) {
              waitObj4[item8] = "0";
            }
            checkForm4.setFormData(waitObj4);
          }
        }
        // 双号
        if (name == "checkbotE") {
          checkForm3.setFormData({
            checkbotAll: "0",
            checkbotS: "0"
          });
          for (let item4 in waitObj4) {
            waitObj4[item4] = "0";
          }
          checkForm4.setFormData(waitObj4);
          if (boolean == true) {
            for (var item9 in waitObj4) {

              let str = "";
              let index9 = item9.lastIndexOf("_");
              str = item9.substring(index9 + 1, item9.length);

              if (Number(str) % 2 == 0) {
                waitObj4[item9] = "1";
              }
            }
            checkForm4.setFormData(waitObj4);
          }
          else {
            for (var item10 in waitObj4) {
              waitObj4[item10] = "0";
            }
            checkForm4.setFormData(waitObj4);
          }
        }
      });

      checkForm4.attachEvent("onChange", function (name, value, boolean, state) {
        //state 单选/复选时使用
        let waitObj2 = {};
        waitObj2 = checkForm2.getFormData();
        let waitObj4 = {};
        waitObj4 = checkForm4.getFormData();

        let flag2 = false;
        for (let item2 in waitObj2) {
          if (waitObj2[item2] == "1") {
            flag2 = true;
            break;
          }
        }

        if (flag2) {
          layer.msg("已按周选择");

          for (var item4 in waitObj4) {
            waitObj4[item4] = "0";
          }
          checkForm4.setFormData(waitObj4);

          return;
        }

        checkForm3.setFormData({
          checkbotAll: "0",
          checkbotS: "0",
          checkbotE: "0"
        });
      });


      checkForm4.attachEvent("onButtonClick", function (name) {
        if (name == "lineInformation_div3_bottomTab1_03_form4_save") {

          let par = {
            lineId: checkForm1.getFormData().lineId,
            weeks: checkForm2.getFormData(),
            days: checkForm4.getFormData()
          };
          //请求地址和类型
          var url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/dateSave";
          var type = "post";
          var contentType = "application/json";
          //调用ajax方法
          utilAjaxGJ(url, type, JSON.stringify(par), function (res) {
            checkForm1.clear();
            checkForm2.clear();
            checkForm3.clear();
            checkForm4.clear();

          }, contentType);

        }
      });
    }
  });
  // tabs.changeTabs("lineInformation_div3_bottomTab1");

  function gridRender() {
    grid1.attachToolBarEvent("onButtonClick", function (name) {
      if (name == "lineInformation_div3_bottomTab1_01_del_all") {
        let ids = grid1.getCheckedIds();
        if (!ids) {
          layer.msg("请选择数据");
          return false;
        }
        let idsArr = ids.split(",");
        let checkedIds = [];
        idsArr.forEach(v => {
          let rdata = grid1.getRowData(v);
          checkedIds.push(
            {
              consigneeId: rdata.consigneeId,
              lineId: rdata.lineId,
              customerId: rdata.customerId
            }
          );
        });
        templet_delete(checkedIds);
      }
    });
  }

  // TAB1单个删除
  window.lineInformation_div3_bottomTab1_01_del = function (rid, rdata) {
    let arr = [
      {
        consigneeId: rdata.consigneeId,
        lineId: rdata.lineId,
        customerId: rdata.customerId
      }
    ];
    templet_delete(arr);
  };
  // TAB1删除方法
  function templet_delete(ids) {
    // return;
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/tmsArriverRemove",
          type: "post",
          contentType: "application/json",
          data: JSON.stringify(ids),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              grid1.reload();
              return true;
            }
            return false;

          }, error: function () { PlgDialog.close(pload); return false; }
        });
      }
    });
  }

  // TAB2单个删除
  window.lineInformation_div3_bottomTab1_02_del = function (rid) {
    layer.open({
      title: _t("删除"),
      content: _t("还未保存，是否删除?"),
      btn: [_t("确认"), _t("取消")],
      yes: function () {
        grid2.deleteRow(rid);
        layer.closeAll();
      }
    });
  };


  //跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#lineInformation_div2",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  let viewList = ["#lineInformation_div1", "#lineInformation_div3", "#lineInformation_div9", "#lineInformation_div_map"];
  function setView(name) {
    for (let i = 0; i < viewList.length; i++) {
      if (name == viewList[i]) {
        $(name).css("display", "block");
      }
      else {
        $(viewList[i]).css("display", "none");
      }
    }
  }
  fromDataJson = {
    renderer: "lineInformation_div4",
    items: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", name: "lineCode", label: "线路编号:", className: "layui-col-md6", required: true },
          { type: "input", name: "lineName", label: "线路名称:", className: "layui-col-md6", required: true },
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md6", name: "departmentName", label: "部门:", placeholder: "请选择部门", readonly: true, required: true },
          { type: "hidden", name: "departmentId" },
          { type: "hidden", name: "departmentCode" },
          { type: "combo", name: "lineStartType", label: "划分类型:", className: "layui-col-md6", options: dataSelete.LINE_START_TYPE, readonly: true },
        ]
      },
      {
        type: "row",
        list: [
          { type: 'combo', className: 'layui-col-md4', name: 'province', label: '省:', options: provinceEnums, readonly: true, hidden: true },
          { type: 'combo', className: 'layui-col-md4', name: 'city', label: '市:', readonly: true, hidden: true },
          { type: 'combo', className: 'layui-col-md4', name: 'district', label: '区:', readonly: true, hidden: true },
        ]
      },
      {
        type: "row",
        list: [
          {
            className: "layui-col-md6",
            type: "selectTable",
            placeholder: "请选择仓库",
            readonly: false,
            table: userTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "name",
            fieldValue: "code",
            name: "buyername1",
            label: "线路起点:",
            listener: function (consignorGrid) {
              setMethod(consignorGrid, userTable, function (data) {
                var fromdata = ddfrom.getFormData();
                data = fromdata.buyername1.length == 2 ? "" : data;
                var datad = {};
                datad.startLineId = data.id ? data.id : "";
                datad.startLineCode = data.code ? data.code : "";
                datad.startLineName = data.name ? data.name : "";

                datad.startLineLongitude = data.longitude ? data.longitude : "";
                datad.startLineLatitude = data.latitude ? data.latitude : "";

                ddfrom.setFormData(datad);
              });
            }
          },
          {
            className: "layui-col-md6",
            type: "selectTable",
            placeholder: "请选择仓库",
            readonly: false,
            table: userTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "name",
            fieldValue: "code",
            name: "buyername3",
            label: "线路终点:",
            listener: function (consignorGrid) {
              setMethod(consignorGrid, userTable, function (data) {
                var fromdata = ddfrom.getFormData();
                data = fromdata.buyername3.length == 2 ? "" : data;
                var datad = {};
                datad.endLineId = data.id ? data.id : "";
                datad.endLineCode = data.code ? data.code : "";
                datad.endLineName = data.name ? data.name : "";

                datad.endLineLongitude = data.longitude ? data.longitude : "";
                datad.endLineLatitude = data.latitude ? data.latitude : "";

                ddfrom.setFormData(datad);
              });
            }
          },
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", name: "carrierType", label: "承运方类型:", className: "layui-col-md6", options: dataSelete.LINE_CARRIER_TYPE, readonly: true },
          { type: "checkbox", name: "limit", label: "是否承运商份额限制:", labelWidth: "145", className: "layui-col-md6" },
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", name: "basis", label: "限制依据:", className: "layui-col-md6", options: dataSelete.LINE_BASIS, readonly: true },
          { type: "input", name: "totalMileage", label: "总里程数:", className: "layui-col-md6" },
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", name: "memo", label: "备注:", className: "layui-col-md12" },
        ]
      },
      {
        type: "row",
        list: [
          { type: "combo", name: "lineType", label: "线路类型:", className: "layui-col-md6", options: dataSelete.LINE_TYPE, readonly: true, required: true },
          { type: "combo", name: "distinguishType", label: "划分类型:", className: "layui-col-md6", options: dataSelete.DISTINGUISH_TYPE, readonly: true, required: true },
        ]
      },
      { type: "hidden", name: "lineId" },
      { type: "hidden", name: "startLineId" },
      { type: "hidden", name: "startLineCode" },
      { type: "hidden", name: "startLineName" },
      { type: "hidden", name: "endLineId" },
      { type: "hidden", name: "endLineCode" },
      { type: "hidden", name: "endLineName" },
      { type: "hidden", name: "startLineLongitude" },
      { type: "hidden", name: "startLineLatitude" },
      { type: "hidden", name: "endLineLongitude" },
      { type: "hidden", name: "endLineLatitude" }
    ]
  };
  fromDataJson.items.push({
    type: "row",
    list: form_opts_list
  });
  // 注册详情表单后的方法
  function setMethodCombo() {

    ddfrom.attachEvent("onChange", function (name, value, boolean, state) {
      //state 单选/复选时使用
      if (name == "limit") {
        if (!boolean) {
          for (let i = 0; i < gridNei3.getGrid().getRowsNum(); i++) {
            gridNei3.setCellValue(gridNei3.getRowId(i), 5, "0");
          }
          for (let i = 0; i < gridNei4.getGrid().getRowsNum(); i++) {
            gridNei4.setCellValue(gridNei4.getRowId(i), 8, "0");
          }
        }
      }
    });

    ddfrom.getCombo("carrierType").attachEvent("onChange", function (n) {
      gridNei3.getGrid().clearAll();
      gridNei4.getGrid().clearAll();
      //承运商
      if (n == "1") {
        $("#carrierType_title").html("承运方信息")
        $("#lineInformation_div7").show();
        $("#lineInformation_div8").hide();
      }
      //司机
      else if (n == "2") {
        $("#carrierType_title").html("司机信息")
        $("#lineInformation_div7").hide();
        $("#lineInformation_div8").show();
      }
    });

    ddfrom.getCombo("distinguishType").attachEvent("onChange", function (n) {
      //收货方
      if (n == "1") {
        $("#lineInformation_distinguishType_1").show();
        $("#lineInformation_distinguishType_2").hide();
      }
      //行政区域
      else if (n == "2") {
        $("#lineInformation_distinguishType_1").hide();
        $("#lineInformation_distinguishType_2").show();
      }
    });
  }
  //返回1
  $(document).on("click", "#lineInformation_return", function () {
    setView("#lineInformation_div3");
  });
  // 返回2;
  $(document).on("click", "#lineInformation_return2", function () {
    layer.open({
      title: "返回列表",
      content: "是否已计算里程?",
      btn: ["确认", "取消"],
      yes: function () {
        setView("#lineInformation_div3");
        layer.closeAll();
      }
    });
  });
  //返回3
  $(document).on("click", "#lineInformation_return3", function () {
    setView("#lineInformation_div_map");
  });

  //保存
  document.querySelector("#lineInformation_save").onclick = function () {
    //数据data
    var data = ddfrom.getFormData();
    var feik = ddfrom.validate();
    if (!feik) {
      return;
    }
    date_list.forEach(item => {
      data[item] = FormatDateTime(data[item]);
    });

    // 行政区域
    if (data.lineStartType == '2') {
      data.startLineLongitude = ''
      data.startLineLatitude = ''
      if (data.province) {
        data.startLineId = data.province
        data.startLineCode = data.province
        data.startLineName = ddfrom.getCombo("province").getComboText()
      }
      if (data.city) {
        data.startLineId = data.city
        data.startLineCode = data.city
        data.startLineName += (',' + ddfrom.getCombo("city").getComboText())
      }
      if (data.district) {
        data.startLineId = data.district
        data.startLineCode = data.district
        data.startLineName += (',' + ddfrom.getCombo("district").getComboText())
      }
    }
    delete data.province
    delete data.city
    delete data.district
    delete data.buyername1
    delete data.buyername3

    // 收货方
    data.tmsArriverVOS = [], data.administrativeAreas = [];
    if (data.distinguishType === '1') {
      let arr1 = [];
      let indexNum = gridNei2.getGrid().getRowsNum();
      let flag = false;
      for (let i = 0; i < indexNum; i++) {
        let rd = gridNei2.getRowData(gridNei2.getRowId(i));
        if (!rd.deliveryOrder) {
          flag = true;
          break;
        }
        else {
          arr1.push(rd);
        }

      }
      if (flag) {
        PlgDialog.msg("请填写配送顺序");
        return;
      }
      if (arr1.length) {
        data.tmsArriverVOS = [...arr1];
      }
    }
    // 行政区域
    else if (data.distinguishType === '2') {
      data.administrativeAreas = tree.treeObj.getCheckedNodes().map(item => {
        return item.zoneid
      })
    }

    //承运商
    data.tmsCarrierVOS = []
    if (data.carrierType == "1") {
      let indexNum = gridNei3.getGrid().getRowsNum();
      let num = 0;
      for (let i = 0; i < indexNum; i++) {
        let rd = gridNei3.getRowData(gridNei3.getRowId(i));
        data.tmsCarrierVOS.push(rd);
        num += Number(rd.shares);
      }
      if (data.limit == "1" && num != 100) {
        PlgDialog.msg("承运商份额总和必须为100!");
        return;
      }
    }
    //司机
    else if (data.carrierType == "2") {
      let indexNum = gridNei4.getGrid().getRowsNum();
      let num = 0;
      for (let i = 0; i < indexNum; i++) {
        let rd = gridNei4.getRowData(gridNei4.getRowId(i));
        data.tmsCarrierVOS.push(rd);
        num += Number(rd.shares);
      }
      if (data.limit == "1" && num != 100) {
        PlgDialog.msg("司机份额总和必须为100!");
        return;
      }
    }

    // data.organizationId = "";
    // data.organizationCode = "";
    // data.organizationName = "";
    // data.departmentId = "";
    // data.departmentCode = "";
    // data.departmentName = "";

    //请求地址和类型
    var url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/update";
    var type = "post";
    var contentType = "application/json";
    //message新增为0，修改为1
    if (data.lineId == null || data.lineId == "") {
      url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/save";
      type = "post";
    }

    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type, contentType, data: JSON.stringify(data),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          setView("#lineInformation_div3");
          grid.reload();
          grid1 && grid1.clearAll();
          grid2 && grid2.clearAll();
          checkForm1 && checkForm1.clear();
          checkForm2 && checkForm2.clear();
          checkForm3 && checkForm3.clear();
          checkForm4 && checkForm4.clear();
          tabs.changeTabs("lineInformation_div3_bottomTab1");
          return true;
        }
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  };

  var gridNei1_opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "id", name: "id", type: "ro", width: "100", hidden: true },
      // { id: "branchName", name: "配送中心/站点", type: "ro", width: 150 },
      { id: "code", name: "收货方编码", type: "ro", width: 150 },
      { id: "name", name: "收货方名称", type: "ro", width: 100 },
      { id: "contact", name: "联系人", type: "ro", width: 100 },
      {
        id: "phoneNumber", name: "联系方式", type: "ro", width: 150, render: function (v, rd) {
          return rd.phoneNumber ? rd.phoneNumber : rd.tel;
        }
      },
      { id: "address", name: "详细地址", type: "ro", width: 250 },
      { id: "consigneeMemo", name: "收货方备注", type: "ro", width: 100, hidden: true },
      { id: "customerId", name: "客户ID", type: "ro", width: 100, hidden: true },
      { id: "customerCode", name: "客户编码", type: "ro", width: 100, hidden: true },
      { id: "customerName", name: "客户名称", type: "ro", width: 100, hidden: true },
      { id: "longitude", name: "经度", type: "ro", width: 100, hidden: true },
      { id: "latitude", name: "纬度", type: "ro", width: 100, hidden: true }
    ],
    multiselect: true,
    fixedLast: false, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            className: "layui-col-md6",
            type: "selectTable",
            placeholder: "请选择客户",
            readonly: false,
            table: clientTable01,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "code",
            fieldValue: "id",
            name: "clientTable01List",
            label: "客户编码:",
            listener: {
              "afterClose": function (text, value, sgrid) {
                if (value == "" || value == null || value == "[]") return;
                let arr = JSON.parse(value);

                // 获取已选择的客户
                let gridNei1_waitList = [];
                let indexNum = gridNei1.getGrid().getRowsNum();
                for (let i = 0; i < indexNum; i++) {
                  let { id } = gridNei1.getRowData(gridNei1.getRowId(i));
                  gridNei1_waitList.push(id);
                }

                let datad = {};
                let arr1 = [];
                let arr2 = [];
                let arr3 = [];
                arr.forEach(index => {
                  // debugger;
                  let firstArr = sgrid.getRowData(index);
                  firstArr.tmsBaseCustomerReceiverDTOs.forEach((item2, index2) => {

                    if (!gridNei1_waitList.includes(item2.id)) {
                      let rowdata = item2;
                      rowdata.rowType = "add";
                      rowdata.customerId = item2.customerId;
                      rowdata.customerCode = item2.customerCode;
                      rowdata.customerName = item2.customerName;
                      gridNei1.addRow(item2.id, rowdata);
                    }
                    // ID CODE 客户名称
                    arr1.push(item2.customerId);
                    arr2.push(item2.customerCode);
                    arr3.push(item2.customerName);

                  });

                });
                datad.customerId = !arr1.length ? "" : arr1.join(",");
                datad.customerCode = !arr2.length ? "" : arr2.join(",");
                datad.customerName = !arr3.length ? "" : arr3.join(",");
                gridNei1.getToolBarForm().setFormData(datad);


              },
              "init": function (sgrid) {
                sgrid.attachToolBarEvent("onButtonClick", function (name) {
                  if (name === "querycarr") {
                    var p = sgrid.getToolBarForm().getFormData();
                    sgrid.setParams(JSON.stringify(p));
                    sgrid.reload();
                  }
                  if (name === "car_Reset") {
                    sgrid.getToolBarForm().clear();
                  }
                });
              }
            }

          },
          { type: "hidden", name: "customerId", label: "客户ID:", className: "layui-col-md6" },
          { type: "hidden", name: "customerCode", label: "客户编码:", className: "layui-col-md6" },
          { type: "input", name: "customerName", label: "客户名称:", className: "layui-col-md6", disabled: true }
        ]
      }
    ],



    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseCustomer/queryCustomerReceiver",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/x-www-form-urlencoded",
    params: {},//查询提交参数，分页参数默认为pageNum,pageSize
    page: false, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  gridNei1 = new PlgGrid(gridNei1_opts);
  gridNei1.renderTo("lineInformation_div6");
  // $("#lineInformation_div6").addClass("layui-form");
  // gridNei1.attachEvent("onDataReady", function () {
  //     setTimeout(function () {
  //         layui.form.render();
  //     }, 200);
  // });
  // gridNei1.loadData();


  var gridNei2_opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "consigneeId", name: "唯一行号收货方ID", type: "ro", width: "100", hidden: true },
      {
        id: "deliveryOrder", name: "<span style='color:#096dd9;'>配送顺序</span>", type: "ed", width: 80
      },
      { id: "customerCode", name: "客户编码", type: "ro", width: 150 },
      {
        id: "customerName", name: "客户名称", type: "ro", width: 100
      },

      {
        id: "consigneeCode", name: "收货方编码", type: "ro", width: 100
      },
      {
        id: "consigneeName", name: "收货方名称", type: "ro", width: 100
      },
      {
        id: "consigneeContact", name: "联系人", type: "ro", width: 150
      },
      {
        id: "consigneePhoneNumber", name: "联系方式", type: "ro", width: 250
      },
      {
        id: "consigneeAddress", name: "收货方地址", type: "ro", width: 250
      },
      {
        id: "consigneeMemo", name: "收货方备注", type: "ro", width: 250
      },

      {
        id: "customerId", name: "客户ID", type: "ro", width: 100, hidden: true
      },
      {
        id: "longitude", name: "经度", type: "ro", width: 100, hidden: true
      },
      {
        id: "latitude", name: "纬度", type: "ro", width: 100, hidden: true
      }

    ],
    multiselect: true,
    fixedLast: false, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_jump_map", value: "地图" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_calculated_mileage", value: "计算里程" }
            ]
          }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tBaseTransline/queryTBaseTransline",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: "{}",//查询提交参数，分页参数默认为pageNum,pageSize
    page: false, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  gridNei2 = new PlgGrid(gridNei2_opts);
  gridNei2.renderTo("lineInformation_div5");
  gridNei2.getGrid().enableEditEvents(true, false, true);
  //按钮添加方法
  gridNei2.attachToolBarEvent("onButtonClick", function (name) {

    // 计算里程
    if (name == "master_calculated_mileage") {

      let ids = gridNei2.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let idsArr = ids.split(",");


      let checkedIds = [];
      idsArr.forEach(v => {
        let rdata = gridNei2.getRowData(v);
        checkedIds.push(
          {
            longitude: rdata.longitude,
            latitude: rdata.latitude
            // index: rdata.deliveryOrder
          }
        );
      });

      // let par = {};

      let ddfromData = ddfrom.getFormData();

      if (ddfromData.startLineLongitude) {
        checkedIds.unshift({
          longitude: ddfromData.startLineLongitude,
          latitude: ddfromData.startLineLatitude
        });
        // par.startLineLongitude = ddfromData.startLineLongitude;
        // par.startLineLatitude = ddfromData.startLineLatitude;
      }
      if (ddfromData.endLineLongitude) {
        checkedIds.push({
          longitude: ddfromData.endLineLongitude,
          latitude: ddfromData.endLineLatitude
        });
        // par.endLineLongitude = ddfromData.endLineLongitude;
        // par.endLineLatitude = ddfromData.endLineLatitude;
      }


      // par.addressDTOList = checkedIds;

      // utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/line/calculate", "post", JSON.stringify(par), function (data) {
      //
      //     ddfrom.setFormData({
      //         totalMileage: data.data
      //     });
      // }, "application/json");
      let arr = [];
      checkedIds.forEach((item, index) => {
        arr.push(new AMap.LngLat(item.longitude, item.latitude));
      });

      let distance = Math.round(AMap.GeometryUtil.distanceOfLine(arr));

      // 米转千并且四舍五入
      let backDistance = Math.round(Number(distance) / 1000 * 100) / 100;

      //回显
      ddfrom.setFormData({
        totalMileage: backDistance
      });

      // 修改状态调接口保存给后端
      if (!jumpType) {
        let par = [
          {
            lineId: ddfrom.getFormData().lineId,
            distance: distance
          }
        ];
        master_calculated_mileage_function(par);
      }


    }
    // 地图
    if (name == "master_jump_map") {
      let par = [
        {
          lineId: ddfrom.getFormData().lineId
        }
      ];
      getMapPageData(par);


    }
  });
  //离开事件
  gridNei2.attachEvent("onEditCell", function (stage, rId, cInd, nValue) {
    let rd = gridNei2.getRowData(rId);
    if (cInd == 3 && stage == 2) {
      // nValue = isNaN(nValue * 1) ? 0 : nValue;
      if (cInd == 3 && !/^[1-9]\d*$/.test(nValue)) {
        layer.msg("请输入正整数");
        return;
      }
      gridNei2.setCellValue(rId, cInd, nValue);
    }
    else if (stage == 2) {
      gridNei2.setCellValue(rId, cInd, nValue);
    }
    return true;
  });

  // 左往右移动
  document.querySelector("#gridMoveRight").onclick = function () {

    if (!jumpType) return;

    let ids = gridNei1.getCheckedIds();
    if (!ids) {
      layer.msg("请选择数据");
      return false;
    }
    let obj = gridNei1.getToolBarForm().getFormData();
    if (!obj.customerCode) {
      layer.msg("请选择客户");
      return false;
    }

    let rightList = [];
    let indexNum = gridNei2.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let { consigneeId } = gridNei2.getRowData(gridNei2.getRowId(i));
      rightList.push(consigneeId);
    }


    if (ids) {
      ids.split(",").forEach(id => {
        let leftRdata = gridNei1.getRowData(id);
        if (!rightList.includes(id)) {
          let rowdata = {
            consigneeId: leftRdata.id,

            customerCode: leftRdata.customerCode,
            customerName: leftRdata.customerName,
            customerId: leftRdata.customerId,

            consigneeCode: leftRdata.code,
            consigneeName: leftRdata.name,
            consigneeContact: leftRdata.contact,
            consigneePhoneNumber: leftRdata.phoneNumber,
            consigneeAddress: leftRdata.address,
            consigneeMemo: leftRdata.memo,

            longitude: leftRdata.longitude,
            latitude: leftRdata.latitude,

            rowType: "add"
          };
          gridNei2.addRow(id, rowdata);
          gridNei1.deleteRow(id);
        }
      });
    }

  };

  // 右往左移
  document.querySelector("#gridMoveleft").onclick = function () {

    if (!jumpType) return;

    let ids = gridNei2.getCheckedIds();
    if (!ids) {
      layer.msg("请选择数据");
      return false;
    }

    let leftList = [];
    let indexNum = gridNei1.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let { id } = gridNei1.getRowData(gridNei1.getRowId(i));
      leftList.push(id);
    }


    if (ids) {
      ids.split(",").forEach(id => {
        let rightRdata = gridNei2.getRowData(id);
        if (!leftList.includes(id)) {
          let rowdata = {
            id: rightRdata.consigneeId,

            customerCode: rightRdata.customerCode,
            customerName: rightRdata.customerName,
            customerId: rightRdata.customerId,

            code: rightRdata.consigneeCode,
            name: rightRdata.consigneeName,
            contact: rightRdata.consigneeContact,
            phoneNumber: rightRdata.consigneePhoneNumber,
            address: rightRdata.consigneeAddress,
            memo: rightRdata.consigneeMemo,

            longitude: rightRdata.longitude,
            latitude: rightRdata.latitude,


            rowType: "add"
          };
          gridNei1.addRow(id, rowdata);
          gridNei2.deleteRow(id);
        }
      });
    }

  };

  let gridNei3_opts = {
    skin: "card",
    rowId: "carrierId",
    columns: [
      { id: "carrierId", name: "承运商ID", type: "ro", width: "100", hidden: true },
      { id: "carrierCode", name: "承运商编码", type: "ro", width: "150" },
      { id: "carrierName", name: "承运商名称", type: "ro", width: "150" },
      { id: "shares", name: "<span style='color:#096dd9;'>份额</span>", type: "ed", width: "150" }
    ],
    multiselect: true,
    fixedLast: false, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-normal", name: "gridNei3_add", value: "新增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "gridNei3_del_all", value: "删除" }
            ]
          }
        ]
      }
    ],
    url: "",//数据接口
    type: "post",//数据提交方式，默认为get
    // contentType: "application/x-www-form-urlencoded",
    params: {},//查询提交参数，分页参数默认为pageNum,pageSize
    page: false, //是否启用分页
    totalCount: "totalCount"
  };
  gridNei3 = new PlgGrid(gridNei3_opts);
  gridNei3.renderTo("lineInformation_div7");
  gridNei3.getGrid().enableEditEvents(true, false, true);
  gridNei3.attachToolBarEvent("onButtonClick", function (name) {
    if (name == "gridNei3_del_all") {
      var ids = gridNei3.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }

      layer.open({
        title: _t("删除"),
        content: _t("还未保存，是否删除?"),
        btn: [_t("确认"), _t("取消")],
        yes: function () {
          ids.split(",").forEach(id => {
            gridNei3.deleteRow(id);
          });
          layer.closeAll();
        }
      });
    }
    if (name == "gridNei3_add") {
      openDialog();

    }
  });
  //离开事件
  gridNei3.attachEvent("onEditCell", function (stage, rId, cInd, nValue) {
    if (cInd === 5) {
      if (stage == 0) {
        if (ddfrom.getFormData().limit != "1") {
          return false;
        }
        // 查看状态不允许编辑
        else if (!jumpType) {
          return false;
        }
      }
      if (stage == 2) {
        nValue = isNaN(nValue * 1) ? 0 : nValue;
        if (!/^\d+$/.test(nValue)) {
          layer.msg("请输入非负整数");
          return;
        }
        gridNei3.setCellValue(rId, cInd, nValue);
      }
      else if (stage == 2) {
        gridNei3.setCellValue(rId, cInd, nValue);
      }
    }

    return true;
  });

  // 承运商弹窗
  function openDialog() {
    // 获取已选择的用户
    let waitList = [];
    let indexNum = gridNei3.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let { carrierCode } = gridNei3.getRowData(gridNei3.getRowId(i));
      waitList.push(carrierCode);
    }

    let carrier_grid;
    PlgDialog.open({
      title: "选择承运商",
      shadeClose: true,
      type: 1,
      area: ["700px", "500px"],
      content: "<div id =\"openDialog11\"></div>",
      btn: ["确认", "取消"],
      yes: function () {
        let ids = carrier_grid.getCheckedIds();
        if (ids) {
          ids.split(",").forEach(id => {
            const carrierRdata = carrier_grid.getRowData(id);
            if (!waitList.includes(carrierRdata.code)) {
              let rowdata = {
                carrierCode: carrierRdata.code,
                carrierName: carrierRdata.name,
                carrierId: carrierRdata.id,
                rowType: "add"
              };
              gridNei3.addRow(id, rowdata);
            }
          });
        }
        layer.closeAll();
      }
    });
    carrier_grid = new PlgGrid(carrierTable);
    carrier_grid.renderTo("openDialog11");
    carrier_grid.loadData(
      //     null, function () {
      //     waitList.forEach(id => user_grid.setCellValue(id, 1, 1));
      // }
    );
    carrier_grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "querycarr":
          var request = carrier_grid.getToolBarForm().getFormData();
          carrier_grid.setParams(JSON.stringify(request));
          carrier_grid.reload();
          break;
        case "car_Reset":
          carrier_grid.getToolBarForm().clear();
          break;
      }
    });
  }


  let gridNei4_opts = {
    skin: "card",
    rowId: "carrierId",
    columns: [
      { id: "carrierId", name: "司机id", type: "ro", width: "100", hidden: true },
      { id: "carrierCode", name: "司机编码", type: "ro", width: "150" },
      { id: "carrierName", name: "司机姓名", type: "ro", width: "150" },
      { id: "phoneNumber", name: "手机号", type: "ro", width: "150" },
      {
        id: "vehicleNo2",
        width: 130,
        type: "selectTable",
        readonly: false,
        table: vahicleTable,
        tableWidth: 600,
        tableHeight: 500,
        fieldText: "plateNumber",
        fieldValue: "plateNumber",
        name: "<span style='color:#096dd9;'>车牌号</span>",
        listener: {
          "afterSelect": function (state, selectId, consignorGrid) {
            if (state) {
              var data = consignorGrid.getRowData(selectId);
              var id = gridNei4.getSelectedRowId();
              // gridNei4.setCellValue(id, 6, data.itemname);
              gridNei4.setCellValue(id, 7, data.plateNumber);

              gridNei4.setCellValue(id, 9, data.id);
              gridNei4.setCellValue(id, 10, data.code);
            }
          },
          "init": function (grid) {
            setMethod(grid, vahicleTable, function () { });
          }
        }
      }, // 6
      { id: "vehiclePlateNumber", name: "车牌号编码", type: "ro", width: "120", hidden: true }, // 7
      { id: "shares", name: "<span style='color:#096dd9;'>份额</span>", type: "ed", width: "150" }, // 8
      { id: "vehicleId", name: "车辆ID", type: "ro", width: "150", hidden: true }, // 9
      { id: "vehicleCode", name: "车辆code", type: "ro", width: "150", hidden: true } // 10

    ],
    multiselect: true,
    fixedLast: false, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-normal", name: "gridNei4_add", value: "新增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "gridNei4_del_all", value: "删除" }
            ]
          }
        ]
      }
    ],
    url: "",//数据接口
    type: "post",//数据提交方式，默认为get
    // contentType: "application/x-www-form-urlencoded",
    params: {},//查询提交参数，分页参数默认为pageNum,pageSize
    page: false, //是否启用分页
    totalCount: "totalCount"
  };
  gridNei4 = new PlgGrid(gridNei4_opts);
  gridNei4.renderTo("lineInformation_div8");
  gridNei4.getGrid().enableEditEvents(true, false, true);
  gridNei4.attachToolBarEvent("onButtonClick", function (name) {
    if (name == "gridNei4_del_all") {
      var ids = gridNei4.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }

      layer.open({
        title: _t("删除"),
        content: _t("还未保存，是否删除?"),
        btn: [_t("确认"), _t("取消")],
        yes: function () {
          ids.split(",").forEach(id => {
            gridNei4.deleteRow(id);
          });
          layer.closeAll();
        }
      });
    }
    if (name == "gridNei4_add") {
      openDialog22();

    }
  });
  //离开事件
  gridNei4.attachEvent("onEditCell", function (stage, rId, cInd, nValue) {
    let rd = gridNei4.getRowData(rId);
    if (cInd == 7 && stage == 0) {
      // 查看状态不允许编辑
      if (!jumpType) {
        return false;
      }
    }
    if (cInd == 8 && stage == 0) {
      if (ddfrom.getFormData().limit != "1") {
        return false;
      }
      // 查看状态不允许编辑
      else if (!jumpType) {
        return false;
      }
    }
    if (cInd == 8 && stage == 2) {
      nValue = isNaN(nValue * 1) ? 0 : nValue;
      if (cInd == 8 && !/^\d+$/.test(nValue)) {
        layer.msg("请输入非负整数");
        return;
      }
      gridNei4.setCellValue(rId, cInd, nValue);
    }
    else if (stage == 2) {
      gridNei4.setCellValue(rId, cInd, nValue);
    }
    return true;
  });

  // 司机弹窗
  function openDialog22() {
    // 获取已选择的用户
    let waitList = [];
    let indexNum = gridNei4.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let { carrierCode } = gridNei4.getRowData(gridNei4.getRowId(i));
      waitList.push(carrierCode);
    }

    let driver_grid;
    PlgDialog.open({
      title: "选择司机",
      shadeClose: true,
      type: 1,
      area: ["600px", "500px"],
      content: "<div id =\"openDialog22\"></div>",
      btn: ["确认", "取消"],
      yes: function () {
        let ids = driver_grid.getCheckedIds();
        if (ids) {
          ids.split(",").forEach(id => {
            const driverRdata = driver_grid.getRowData(id);
            if (!waitList.includes(driverRdata.userId)) {
              let rowdata = {
                carrierCode: driverRdata.code,
                carrierName: driverRdata.name,
                phoneNumber: driverRdata.phoneNumber,
                carrierId: driverRdata.id,
                vehicleId: driverRdata.vehicleId || "",
                vehicleCode: driverRdata.vehicleCode || "",
                vehiclePlateNumber: driverRdata.vehiclePlateNumber || "",
                rowType: "add"
              };
              gridNei4.addRow(id, rowdata);
              if (driverRdata.vehiclePlateNumber) {
                gridNei4.setCellValue(id, 6, { text: driverRdata.vehiclePlateNumber, value: JSON.stringify([driverRdata.vehiclePlateNumber]) });
              }
            }
          });
        }
        layer.closeAll();
      }
    });
    driver_grid = new PlgGrid(driverTable);
    driver_grid.renderTo("openDialog22");
    driver_grid.loadData(
      //     null, function () {
      //     waitList.forEach(id => driver_grid.setCellValue(id, 1, 1));
      // }
    );
    driver_grid.attachToolBarEvent("onButtonClick", function (name) {
      switch (name) {
        case "querycarr":
          var rdata = driver_grid.getToolBarForm().getFormData();
          driver_grid.setParams(JSON.stringify(rdata));
          driver_grid.reload();
          break;
        case "car_Reset":
          driver_grid.getToolBarForm().clear();
          break;
      }
    });
  }

  // 基本table组件
  let waitObj = {
    url: "", // 数据接口
    type: "", // 数据提交方式，默认为get
    params: {}, // 查询提交参数，分页参数默认为pageNum,pageSize
    page: false, // 是否启用分页
    totalCount: "totalCount", // 总记录数字段，默认totalCount
    // skin: "card",
    multiselect: false, // 是否支持多选
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    columns: [
      { id: "consigneeId", name: "consigneeId", width: 150, hidden: true },
      { id: "deliveryOrder", name: "配送顺序", width: 60, type: "ro", align: "center" },
      { id: "customerName", name: "客户名称", width: 150, type: "ro" },
      { id: "consigneeName", name: "收货方名称", width: 150, type: "ro" },
      { id: "consigneeContact", name: "联系人", width: 150, type: "ro" },
      { id: "consigneePhoneNumber", name: "联系方式", width: 150, type: "ro" },
      { id: "consigneeAddress", name: "收货方地址", width: 150, type: "ro" }
    ],
    toolbar: [

      { type: "settings", labelWidth: 40, labelAlign: "right", disabled: true },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md12", name: "lineName", label: "", disabled: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md4", name: "startLineName", label: "起点:", disabled: true },
          { type: "input", className: "layui-col-md4", name: "endLineName", label: "终点:", disabled: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md4", name: "terminalNumber", label: "总站数:", disabled: true },
          { type: "input", className: "layui-col-md4", name: "totalMileage", label: "里程数:", disabled: true },
          { type: "button", className: "layui-col-md4", name: "master_calculated_mileage", value: "计算里程" }

        ]
      }


    ]
  };

  setTimeout(() => {
    //基本地图加载
    map = new AMap.Map("lineInformation_div_map_leftMain", {
      resizeEnable: true,
      center: [116.397428, 39.90923],//地图中心点
      zoom: 13 //地图显示的缩放级别
    });
  }, 1000);

  // 拿地图页面数据并跳转
  function getMapPageData(par) {
    utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/selectMap", "post", JSON.stringify(par), function (res) {
      if (res.success) {
        setView("#lineInformation_div_map");
        // 清空地图
        if (driving) {
          driving.clear();
          if (driving.render) {
            driving.render.clear();
          }
        }
        if (infowindow) {
          map.clearMap();
        }


        // 清空右侧路线
        $("#lineInformation_div_map_rightMain").html("");

        // 清空待调整页面需要的数据
        mapDataList = [];


        if (res.data.length) {
          let arr1 = JSON.parse(JSON.stringify(res.data));

          mapDataList = arr1;


          // 构建右侧线路表格
          renderRightTableList(arr1);

          // 循环构建线路
          res.data.forEach((item, index) => {
            if (item.tmsArriverByMapDTOs.length > 1) {
              // 构建线路
              renderMap(item.tmsArriverByMapDTOs, index, item);
            }
          });
        }
      }
    }, "application/json");
  }

  // 构建右侧表格循环
  function renderRightTableList(tableList) {

    gridTableList = [];

    for (let i = 0; i < tableList.length; i++) {
      let _html = "            <div class=\"info_list\" id=\"table_" + tableList[i].lineId + "\" style=\"min-height:300px;\">";
      _html += "            </div>";
      $("#lineInformation_div_map_rightMain").append(_html);

      setTimeout(() => {
        let gridTable;
        gridTable = "gridTable+" + tableList[i].lineId;
        gridTable = new PlgGrid(waitObj);
        gridTable.renderTo("table_" + tableList[i].lineId);
        gridTable.loadData({
          data: {
            list: tableList[i].tmsArriverByMapDTOs
          }
        });
        gridTable.getToolBarForm().setFormData(tableList[i]);
        gridTable.getToolBarForm().attachEvent("onButtonClick", function (name) {
          if (name == "master_calculated_mileage") {

            // 如果有起点就要塞到数组第一个 如果有重点塞到数组最后一个
            let distanceArr = JSON.parse(JSON.stringify(tableList[i].tmsArriverByMapDTOs));
            if (tableList[i].startLineLongitude) {
              let obj = {
                longitude: tableList[i].startLineLongitude,
                latitude: tableList[i].startLineLatitude
              };
              distanceArr.unshift(obj);
            }
            if (tableList[i].endLineLongitude) {
              let obj = {
                longitude: tableList[i].endLineLongitude,
                latitude: tableList[i].endLineLatitude
              };
              distanceArr.push(obj);
            }


            let arr = [];//经纬度坐标数组
            distanceArr.forEach((item, index) => {
              arr.push(new AMap.LngLat(item.longitude, item.latitude));
            });

            let distance = Math.round(AMap.GeometryUtil.distanceOfLine(arr));

            let par = [
              {
                lineId: tableList[i].lineId,
                distance: distance
              }
            ];
            let str = master_calculated_mileage_function(par, "2");
            //回显
            gridTable.getToolBarForm().setFormData({
              totalMileage: str
            });

          }
        });
        gridTableList.push(gridTable);

      }, 200);
    }
  }

  //构建线路
  function renderMap(parArr, firstIndex, parData) {
    // console.log(parArr, "parArr");

    let mapList = [];
    let objlnglat = {};
    let objlnglat2 = {};
    let markList = [];


    // 如果有起点就要塞到数组第一个 如果有重点塞到数组最后一个
    if (parData.startLineLongitude) {
      let obj = {
        longitude: parData.startLineLongitude,
        latitude: parData.startLineLatitude,
        warehouse: parData.startLineName
      };
      parArr.unshift(obj);
    }
    if (parData.endLineLongitude) {
      let obj = {
        longitude: parData.endLineLongitude,
        latitude: parData.endLineLatitude,
        warehouse: parData.endLineName
      };
      parArr.push(obj);
    }

    let color = "#";
    for (let i = 0; i < 6; i++) {
      color += parseInt(Math.random() * 16).toString(16);
    }

    //构造路线导航类
    driving = new AMap.Driving({
      // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
      policy: AMap.DrivingPolicy.LEAST_TIME,
      map: map,
      outlineColor: color
      // panel: "panel"
    });


    var newArr = JSON.parse(JSON.stringify(parArr));
    //通过map方法将原始数组中的每一项循环

    newArr.forEach((item, index) => {
      // 点数组数据
      let markArr = [];
      markArr[0] = item.longitude;
      markArr[1] = item.latitude;
      markList.push(markArr);

      if (index == 0) {
        objlnglat = {
          longitude: item.longitude,
          latitude: item.latitude
        };
      }
      else if (index != 0 && index != newArr.length - 1) {

        //新数组的项，用来盛放每一项中的各个参数，每次清空，这样避免改变sevm的值

        var sevm = [];

        //给每一项中的参数初始化并赋值

        sevm[0] = item.longitude;

        sevm[1] = item.latitude;

        //将项放进新的数组


        mapList.push(sevm);


      }
      else if (index == newArr.length - 1) {
        objlnglat2 = {
          longitude: item.longitude,
          latitude: item.latitude
        };
      }
    });


    // 根据起终点经纬度规划驾车导航路线
    driving.search(
      new AMap.LngLat(objlnglat.longitude, objlnglat.latitude),
      new AMap.LngLat(objlnglat2.longitude, objlnglat2.latitude),
      {
        waypoints: mapList
      }, function (status, result) {
        // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === "complete") {
          // console.log("绘制驾车路线完成");
        }
        else {
          // console.log("获取驾车数据失败：" + result);
        }
      }
    );


    infowindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
    for (var i = 0, marker; i < markList.length; i++) {
      marker = new AMap.Marker({
        zIndex: 999999999,
        position: markList[i],
        map: map,
        label: {
          content: i + 1,
          offset: new AMap.Pixel(3, 0)
        }
      });


      if (parData.startLineLongitude && i == 0) {
        marker.content = "第" + (i + 1) + "站<br />仓: " + newArr[i].warehouse;

      }
      else if (parData.endLineLongitude && i == markList.length - 1) {
        marker.content = "第" + (i + 1) + "站<br />仓: " + newArr[i].warehouse;
      }
      else {
        marker.content = "第" + (i + 1) + "站<br />客户: " + newArr[i].customerName + "<br />收货方: " + newArr[i].consigneeName + "<br />收货地址: " + newArr[i].consigneeAddress;
      }
      marker.inObk = {
        firstIndex: firstIndex,
        secId: newArr[i].consigneeId
      };
      marker.on("click", markerClick);
      // marker.emit("click", { target: marker });
    }


  }

  // 地图构造点 点击方法
  function markerClick(e) {

    infowindow.setContent(e.target.content);
    infowindow.open(map, e.target.getPosition());


    gridTableList.forEach((item, index) => {
      for (let i = 0; i < item.getRowsNum(); i++) {
        item.setRowTextStyle(item.getRowId(i), "background-color: #fff;");
      }
    });


    setTimeout(() => {
      let grid999 = gridTableList[e.target.inObk.firstIndex];
      grid999.setRowTextStyle(e.target.inObk.secId, "background-color: #6ee690;");
    }, 200);


  }


  var gridAdjust_opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "consigneeId", name: "id", type: "ro", width: "100", hidden: true },
      { id: "consigneeId", name: "id", type: "ro", width: "100", hidden: true },
      { id: "customerCode", name: "客户编码", type: "ro", width: 150 },
      { id: "customerName", name: "客户名称", type: "ro", width: 100 },
      { id: "consigneeCode", name: "收货方编码", type: "ro", width: 100 },
      { id: "consigneeName", name: "收货方名称", type: "ro", width: 100 },
      { id: "consigneeContact", name: "联系人", type: "ro", width: 100 },
      { id: "consigneePhoneNumber", name: "联系方式", type: "ro", width: 100 },
      { id: "consigneeAddress", name: "收货方地址", type: "ro", width: 100 },
      { id: "deliveryOrder", name: "<span style='color:#096dd9;'>配送顺序</span>", type: "ed", width: 100 }, // 10
      {
        id: "lineCode2",
        width: 130,
        type: "selectTable",
        readonly: false,
        table: lineByMap_Table,
        tableWidth: 600,
        tableHeight: 500,
        fieldText: "lineCode",
        fieldValue: "lineCode",
        name: "<span style='color:#096dd9;'>线路编码</span>",
        listener: {
          "afterSelect": function (state, selectId, consignorGrid) {
            if (state) {
              var data = consignorGrid.getRowData(selectId);
              var id = gridAdjust.getSelectedRowId();
              gridAdjust.setCellValue(id, 12, data.lineCode);
              gridAdjust.setCellValue(id, 13, data.lineId);
              gridAdjust.setCellValue(id, 14, data.lineName);
            }
          },
          "init": function (grid) {
            setMethod(grid, lineByMap_Table, function () { });
          }
        }
      }, // 11
      { id: "lineCode", name: "线路编码", type: "ro", width: "120", hidden: true }, // 12
      { id: "lineId", name: "线路ID", type: "ro", width: 100, hidden: true }, // 13
      { id: "lineName", name: "线路名称", type: "ro", width: 100 } // 14

    ],
    multiselect: false, // 若改为true 去掉第一列占位列
    fixedLast: false, //开启固定列，固定最后一行，倒数第二列不能隐藏
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3", name: "lineCode", label: "线路编码:", placeholder: "请输入线路编码" },
          { type: "input", className: "layui-col-md3", name: "lineName", label: "线路名称:", placeholder: "请输入线路名称" },
          { type: "input", className: "layui-col-md3", name: "customerCode", label: "客户编码:", placeholder: "请输入客户编码" },
          { type: "input", className: "layui-col-md3", name: "customerName", label: "客户名称:", placeholder: "请输入客户名称" },
          { type: "input", className: "layui-col-md3", name: "consigneeCode", label: "收货方编码:", placeholder: "请输入收货方编码" },
          { type: "input", className: "layui-col-md3", name: "consigneeName", label: "收货方名称:", placeholder: "请输入收货方名称" },
          {
            type: "block", className: "layui-col-md3 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "querywork", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "work_Reset", value: "重 置" }
            ]
          }
        ]
      }
    ],



    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/selectMapDetails",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: "{}",//查询提交参数，分页参数默认为pageNum,pageSize
    page: false, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  gridAdjust = new PlgGrid(gridAdjust_opts);
  gridAdjust.renderTo("lineInformation_div422");
  // gridAdjust.loadData();
  // 默认给弹窗赋值显示
  gridAdjust.attachEvent("onDataReady", function () {
    for (let i = 0; i < gridAdjust.getRowsNum(); i++) {
      let { consigneeId, lineCode } = gridAdjust.getRowData(gridAdjust.getRowId(i));
      gridAdjust.setCellValue(consigneeId, 11, lineCode ? lineCode : "");
    }
  });
  gridAdjust.getGrid().enableEditEvents(true, false, true);
  gridAdjust.attachToolBarEvent("onButtonClick", function (name) {
    if (name == "querywork") {
      let lineIds = [];
      mapDataList.forEach((item) => {
        lineIds.push(item.lineId);
      });

      var fdata = gridAdjust.getToolBarForm().getFormData();
      fdata.lineIds = lineIds;

      gridAdjust.setParams(JSON.stringify(fdata));
      gridAdjust.reload();
    }
    if (name == "work_Reset") {
      gridAdjust.getToolBarForm().clear();
    }
  });
  //离开事件
  gridAdjust.attachEvent("onEditCell", function (stage, rId, cInd, nValue) {
    let rd = gridAdjust.getRowData(rId);
    if (cInd == 10 && stage == 2) {
      nValue = isNaN(nValue * 1) ? 0 : nValue;
      if (cInd == 10 && !/^\d+$/.test(nValue)) {
        layer.msg("请输入非负整数");
        return;
      }
      gridAdjust.setCellValue(rId, cInd, nValue);
    }
    else if (stage == 2) {
      gridAdjust.setCellValue(rId, cInd, nValue);
    }
    return true;
  });


  // 线路调整调接口跳转
  document.querySelector("#lineInformation_map_adjust").onclick = function () {
    let lineIds = [];
    mapDataList.forEach((item) => {
      lineIds.push(item.lineId);
    });
    let par = {
      lineIds: lineIds
    };
    gridAdjust.setParams(JSON.stringify(par));
    gridAdjust.reload();

    setView("#lineInformation_div9");
    return;
  };

  // 线路调整调完成保存后跳转
  document.querySelector("#lineInformation_div422_save").onclick = function () {


    let dataList = [];
    let indexNum = gridAdjust.getGrid().getRowsNum();
    for (let i = 0; i < indexNum; i++) {
      let rd = gridAdjust.getRowData(gridAdjust.getRowId(i));
      dataList.push(rd);
    }

    // 调用保存接口
    utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/saveMap", "post", JSON.stringify(dataList), function (res) {
      if (res.success) {


        let par = [];
        mapDataList.forEach((item) => {
          par.push({ lineId: item.lineId });
        });

        getMapPageData(par);
        setView("#lineInformation_div_map");
      }
    }, "application/json");


  };


  // 导入弹窗
  function importDialog() {
    let pload;
    PlgDialog.open({
      title: "导入",
      shadeClose: true,
      type: 1, // 设置为1，手动控制dialog的开关
      area: ["500px", "300px"],
      content: "<div id =\"lineInformation_dialog\"></div>" //iframe的url
    });
    let dialogForm_opts = {
      renderer: "lineInformation_dialog",
      items: [
        { type: "settings", labelAlign: "right", labelWidth: 75 },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md12 importName", name: "importName", label: "导入文件:", readonly: true, placeholder: "点击选择导入文件" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "radio", className: "layui-col-md3", name: "acceptOrNot", value: "1", label: "线路", checked: true },
            { type: "radio", className: "layui-col-md3", name: "acceptOrNot", value: "2", label: "收货方" },
            { type: "radio", className: "layui-col-md3", name: "acceptOrNot", value: "3", label: "承运方" }
          ]
        },
        {
          type: "row",
          list: [
            {
              type: "block", className: "layui-col-md12 right",
              list: [
                { type: "button", name: "dialog_import", className: "dialog_import btn-normal", value: "导入" },
                { type: "newcolumn" },
                { type: "button", name: "dialog_download", className: "btn-normal", value: "下载模板" },
                { type: "newcolumn" },
                { type: "button", name: "dialog_cancel", value: "取消" }
              ]
            }
          ]
        }
      ]
    };
    dialogForm = new PlgForm(dialogForm_opts);
    // 初始化上传
    var uploadInst = layui.upload.render({
      headers: {
        "Authorization": Prolog.token,
      },
      elem: ".importName",
      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/batch_import",
      size: 10 * 1024,
      accept: "file",
      exts: "xlsx|xls",
      field: "file",
      auto: false,
      bindAction: ".dialog_import",
      choose: function (obj) {
        obj.preview(function (index, file) {
          dialogForm.setItemValue("importName", file.name);
        });
      },
      before: function () {
        pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      },
      done: function (res) {
        PlgDialog.close(pload);
        PlgDialog.alert(res.message);
        if (res.success) {
          layer.closeAll();
          master_grid.reload();
        }
        else {
        }
      },
      error: function () { PlgDialog.close(pload); PlgDialog.msg("接口调用失败"); }
    });

    // 表单按钮点击事件
    dialogForm.attachEvent("onButtonClick", function (name) {
      let { acceptOrNot } = dialogForm.getFormData();
      if (name === "dialog_download") {
        let url, name;
        if (acceptOrNot === "1") {
          url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/download_template_line";
          name = "线路导入模板";
        }
        else if (acceptOrNot === "2") {
          url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/download_template_line_consignee";
          name = "收货方导入模板";
        }
        else if (acceptOrNot === "3") {
          url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/download_template_line_carrier";
          name = "承运方导入模板";
        }
        Prolog.exportFile(url, name + ".xlsx", "", "post");
      }
      else if (name === "dialog_import") {
        if (!dialogForm.getItemValue("importName")) {
          layer.msg("请选择导入文件");
          return false;
        }
        if (acceptOrNot === "1") {
          uploadInst.config.url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/batch_import";
        }
        else if (acceptOrNot === "2") {
          uploadInst.config.url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/batch_import_consignee";
        }
        else if (acceptOrNot === "3") {
          uploadInst.config.url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/line/batch_import_carrier";
        }
      }
      else if (name === "dialog_cancel") {
        layer.closeAll();
      }
    });
  }

  // 行政区域 isView-是否查看 true-查看 false-新增/修改
  function treeInit(isView) {
    let tree_config = {
      renderer: "lineInformation_tree",
      skin: "menu-tree",
      setting: {
        async: {
          enable: true,
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/zone/get-by-pid",
          contentType: "application/json",
          type: "post",
          autoParam: ["id=fatherid"],
          headers: {
            "Authorization": Prolog.reloadToken()
          },
          dataFilter: (treeId, parentNode, childNodes) => filter(treeId, parentNode, childNodes, isView)
        },
        check: {
          enable: !isView,
          chkDisabledInherit: true,
          chkStyle: "checkbox",
          autoCheckTrigger: true,
        },
      },
    }
    tree = new PlgZtree(tree_config);
  }

  function filter(treeId, parentNode, childNodes, isView) {
    if (!childNodes.success) return null;
    let list = []
    childNodes.data.forEach(v => {
      v.name = v.zname;
      v.id = v.zoneid;
      v.pId = v.fatherid;
      v.isParent = true;
      if (isView && checkList.includes(v.id)) {
        list.push(v)
      }
      else if (!isView) {
        v.checked = checkList.includes(v.id)
        list.push(v)
      }
    });
    return list;
  }

  // 省市区联动
  function provinceCityDistrict(fdata) {
    if (fdata.lineStartType == '2' && fdata.startLineCode) {
      ddfrom.hideItem("buyername1")
      ddfrom.showItem("province")
      ddfrom.showItem("city")
      ddfrom.showItem("district")
      let list = fdata.startLineCode.split("")

      let province = (list[0] + list[1]).padEnd(6, 0)
      let city = (list[2] + list[3]) === '00' ? '' : (list[0] + list[1] + list[2] + list[3]).padEnd(6, 0)
      let district = (list[4] + list[5]) === '00' ? '' : fdata.startLineCode
      console.log(province, city, district);

      ddfrom.setFormData({ province })
      city && getByPid(province, 'city', city)
      district && getByPid(city, 'district', district)
    }

    ddfrom.attachComboEvent('lineStartType', 'onChange', function (id) {
      ddfrom.setText("buyername1", "");
      ddfrom.setFormData({ startLineId: "", startLineCode: "", startLineName: "", startLineLatitude: "", startLineLongitude: "" })
      ddfrom.getCombo('province').setComboText('')
      ddfrom.getCombo('city').clearAll()
      ddfrom.getCombo('city').setComboText('')
      ddfrom.getCombo('district').clearAll()
      ddfrom.getCombo('district').setComboText('')
      if (id === '1') {
        ddfrom.showItem("buyername1")
        ddfrom.hideItem("province")
        ddfrom.hideItem("city")
        ddfrom.hideItem("district")
      } else {
        ddfrom.hideItem("buyername1")
        ddfrom.showItem("province")
        ddfrom.showItem("city")
        ddfrom.showItem("district")
      }
    })

    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('district').clearAll()
      ddfrom.getCombo('district').setComboText('')
      if (id) {
        ddfrom.loadComboData('district', {
          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.syncAjax({
      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
      },
    })
  }
};
