/**
 * zzx
 * 2020.08.24
 * 二次补约
    */
    import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE,UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_INTERFACE_SERVICE} from '@/config/serviceSettings.js';
    import { getSelectGJ, querySysPicture } from '@/utils/prolog.ajax.js';
export default () => {
  var master_grid, modify_form;
  // var details_grid;

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

  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var endTime = Prolog.formatDate(new Date()) + " 23:59:59";
  // 获取下拉框
  var dataSelect = {
    TMS_APPOINT_TYPE: [],
    TIME_SECTION: []
  };
  getSelectGJ([
    { "objectcode": "TMS_APPOINT_TYPE" },
    { "objectcode": "TIME_SECTION" }], function (data) {
      dataSelect = data.data;
      dataSelect.TMS_APPOINT_TYPE.unshift({ "value": "", "text": "" });
      dataSelect.TIME_SECTION.unshift({ "value": "", "text": "" });
    });

  // 配送中心table
  var branchTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "配送中心编号", type: "ro" },
      { id: "companyname", 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: "companycode", label: "配送中心编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyBranch",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  // 车型table
  var appointVehicleModelTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "vehicleSpecsNo", name: "规格编号", type: "ro" },
      { id: "vehicleSpecsName", name: "规格名称", type: "ro" }
    ],
    multiselect: false,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/tBaseVehicleSpecs/queryTBaseVehicleSpecs",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true // 是否启用分页
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "appointBillNo", name: "id", type: "ro", width: "130", hidden: true },
      { id: "branchid", name: "配送中心编号", type: "ro", width: 120 },
      { id: "branchname", name: "配送中心名称", type: "ro", width: 120 },
      { id: "appointBillNo", name: "预约单号", type: "ro", width: 120 },
      { id: "billdate", name: "单据时间", type: "ro", width: 120 },
      {
        id: "appointType", name: "预约类型", type: "ro", width: 120, render: function (v) {
          return Prolog.getNameByID(dataSelect.TMS_APPOINT_TYPE, v);
        }
      },
      { id: "customerId", name: "预约单位id", type: "ro", width: 120 },
      { id: "customerCode", name: "预约单位编号", type: "ro", width: 120 },
      { id: "customerName", name: "预约单位名称", type: "ro", width: 120 },
      { id: "appointVehicle", name: "预约车辆", type: "ro", width: 120 },
      { id: "appointDriver", name: "预约司机", type: "ro", width: 120 },
      { id: "appointDriverTel", name: "手机号", type: "ro", width: 120 },
      { id: "appointDate", name: "预约日期", type: "ro", width: 120 },
      {
        id: "appointTime", name: "预约时间", type: "ro", width: 120, render: function (v) {
          return Prolog.getNameByID(dataSelect.TIME_SECTION, v);
        }
      },
      { id: "appointPackage", name: "预约件数", type: "ro", width: 120 },
      { id: "appointWhight", name: "预约重量", type: "ro", width: 120 },
      { id: "appointPerson", name: "预约人", type: "ro", width: 120 },
      //{ id: "shipbillid", name: "运单id", type: "ro", width: 120 },
      { id: "shipbillno", name: "运单编号", type: "ro", width: 120 },
      { id: "status", name: "单据状态", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "left", width: 80, fixed: "right", render: function () {
          return "二次补约^secondaryContract_contract";
        }
      }
    ],
    toolbar: [
      { type: "settings", labelWidth: 70, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "startdate", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "enddate", label: "结束时间:", value: endTime },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择配送中心",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "branchidList",
            label: "配送中心:",
            listener: function (Grid) {
              setMethod(Grid, branchTable, function () { });
            }
          },
          { type: "input", className: "layui-col-md3", name: "appointBillNo", label: "预约单号:" },
          { type: "input", className: "layui-col-md3", name: "shipbillno", label: "运单号:" },
          { type: "input", className: "layui-col-md3", name: "voucherno", label: "车牌号:" },
          { type: "input", className: "layui-col-md3", name: "driver1st", label: "司机:" },
          {
            type: "block", className: "layui-col-md2 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" }

            ]
          }
        ]
      }
    ],
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/secondAppoint/secondAppointQuery", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ startdate: startTime, enddate: endTime }),
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("secondaryContract_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.startdate = request.startdate ? Prolog.formatDate(request.startdate) + " 00:00:00" : "";
        request.enddate = request.enddate ? Prolog.formatDate(request.enddate) + " 23:59:59" : "";
        if (request.startdate > request.enddate) {
          layer.msg("开始时间不能大于结束时间");
          return false;
        }
        request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
        dealNullQueryCondition(request);
        delete request.branchidList;
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        // details_grid.clearAll();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setFormData({ startdate: startTime, enddate: endTime });
        master_grid.getToolBarForm().setText("branchidList", "");
        break;
    }
  });
  // 单击一行显示明细
  // master_grid.on("onRowSelect", function (id) {
  //   let rdata = master_grid.getRowData(id);
  //   details_grid.setParams(JSON.stringify({ appointBillNo: id, branchid: rdata.branchid }));
  //   details_grid.reload();
  // });

  // 二次补约
  window.secondaryContract_contract = function (rid, rdata) {
    modify_form.clear();
    modify_form.setText("customerModelTypeList", "");
    modify_form.setFormData(rdata);
    changePanel("#secondaryContract_modify");
  };

  // 详情表grid
  // var details_grid_opts = {
  //   skin: "card",
  //   columns: [
  //     { id: "shipbillno", name: "运单号", type: "ro", width: "130", hidden: true },
  //     { id: "shipbillno", name: "运单号", type: "ro" },
  //     { id: "appointBillNo", name: "预约单号", type: "ro" },
  //     { id: "itemno", name: "产品编号", type: "ro" },
  //     { id: "itemname", name: "产品名称", type: "ro" },
  //     { id: "itemtype", name: "物料类型", type: "ro" },
  //     { id: "rsumcases", name: "件数", type: "ro" },
  //     { id: "rsumgoodsweight", name: "重量", type: "ro" },
  //     { id: "rsumgoodsvol", name: "体积", type: "ro" },
  //     { id: "memo", name: "备注", type: "ro" }
  //   ],
  //   fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
  //   multiselect: false, // 是否支持多选
  //
  //   url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/secondAppoint/secondAppointQueryDtl", // 数据接口
  //   type: "post", // 数据提交方式，默认为get
  //   params: "{}",
  //   page: false, // 是否启用分页
  //   contentType: "application/json",
  //   totalCount: "totalCount" // 总记录数字段，默认totalCount
  // };
  // details_grid = new PlgGrid(details_grid_opts);
  // details_grid.renderTo("secondaryContract_details");

  // 二次补约form
  var modify_form_opts = {
    renderer: "secondaryContract_modify_form",
    items: [
      { type: "settings", labelWidth: 100, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "customerName", label: "承运商/供应商:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "appointBillNo", label: "预约单号:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "appointDriver", label: "司机:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "appointVehicle", label: "车辆:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "appointPackage", label: "总件数:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "reqshipmentdate", label: "预计到厂时间:" },
          { type: "input", className: "layui-col-md3", name: "driverTel", label: "手机号:" },
          { type: "input", className: "layui-col-md3", name: "driver1st", label: "司机:" },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择车型",
            readonly: false,
            table: appointVehicleModelTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "vehicleSpecsName",
            fieldValue: ["vehicleSpecsNo", "vehicleSpecsName"],
            name: "customerModelTypeList",
            label: "车型:",
            listener: {
              "afterClose": function (text, value) {
                let selectedLength = JSON.parse(value).length;
                if (selectedLength) {
                  let data = JSON.parse(value)[0];
                  modify_form.setFormData({ "customerModelType": data.vehicleSpecsNo, "customerModelTypeName": data.vehicleSpecsName });
                }
                else {
                  modify_form.setFormData({ "customerModelType": "", "customerModelTypeName": "" });
                }
              }
            }
          },
          { type: "input", className: "layui-col-md3", name: "voucherno", label: "车牌号:" },
          { type: "input", className: "layui-col-md3", name: "rplsumcases", label: "件数:" }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md9", name: "memo", label: "备注:" },
          { type: "hidden", className: "layui-col-md9", name: "customerModelType", label: "车型code:" },
          { type: "hidden", className: "layui-col-md9", name: "customerModelTypeName", label: "车型name:" },
          { type: "hidden", name: "customerId", label: "承运商/供应商ID:"}
        ]
      }
    ]
  };
  modify_form = new PlgForm(modify_form_opts);

  let formInputList = document.getElementById("secondaryContract_modify_form").getElementsByTagName("input");
  formInputList[6].onblur = function () {
    getDriverVehicleInfo();
  };
  formInputList[6].onkeydown = function (data) {
    if (data.key == "Enter") {
      formInputList[6].blur();
    }
  };

  // 通过手机号查询司机其他信息
  function getDriverVehicleInfo() {
    let { driverTel, customerId } = modify_form.getFormData();
    let phoneValidate = /^1\d{10}$/;
    if (!phoneValidate.test(driverTel)) {
      layer.msg("请输入正确的手机号");
      formInputList[6].focus();
    }
    else {
      let request = {
        phone: driverTel,
        cId: customerId
      };
      let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
      Prolog.ajax({
        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/sysUserDuty/getDriverVehicleInfo", type: "post", contentType: "application/x-www-form-urlencoded", data: request,
        success: function (res) {
          PlgDialog.close(pload);
          if (res.success) {
            if (res.data) {
              let { userName, vehicleBindId, vehicleType, vehicleName } = res.data;
              modify_form.setFormData({
                driver1st: userName,
                customerModelType: vehicleType,
                customerModelTypeName: vehicleName,
                customerModelTypeList: JSON.stringify([{ vehicleSpecsNo: vehicleType, vehicleSpecsName: vehicleName }]),
                voucherno: vehicleBindId
              });
              modify_form.setText("customerModelTypeList", vehicleName || "");
              formInputList[11].focus();
            }
            else {
              modify_form.setFormData({
                driver1st: "",
                customerModelType: "",
                customerModelTypeName: "",
                customerModelTypeList: "[]",
                voucherno: ""
              });
              modify_form.setText("customerModelTypeList", "");
              formInputList[7].focus();
            }
          }
          else {
            modify_form.setFormData({
              driver1st: "",
              customerModelType: "",
              customerModelTypeName: "",
              customerModelTypeList: "[]",
              voucherno: ""
            });
            modify_form.setText("customerModelTypeList", "");
            formInputList[7].focus();
          }
        }, error: function () { PlgDialog.close(pload); return false; }
      });
    }
  }

  // 保存
  $("#secondaryContract_modify_save").on("click", function () {
    let rdata = modify_form.getFormData();
    if (!rdata.reqshipmentdate) {
      layer.msg("请选择预计到厂时间");
      return false;
    }
    if (!rdata.driverTel) {
      layer.msg("请输入手机号");
      return false;
    }
    if (!rdata.driver1st) {
      layer.msg("请输入司机");
      return false;
    }
    if (!rdata.customerModelType) {
      layer.msg("请选择车型");
      return false;
    }
    if (!rdata.voucherno) {
      layer.msg("请输入车牌号");
      return false;
    }
    if (!Prolog.isCarID(rdata.voucherno)) {
      layer.msg("请输入正确的车牌号");
      return false;
    }
    if (!rdata.rplsumcases) {
      layer.msg("请输入件数");
      return false;
    }
    if (!/^[1-9]\d*$/.test(rdata.rplsumcases) || rdata.rplsumcases - rdata.appointPackage >= 0) {
      layer.msg("件数为正整数并且不能大于等于总件数");
      return false;
    }
    let request = {
      appointBillNo: rdata.appointBillNo,
      branchid: rdata.branchid,
      reqshipmentdate: Prolog.formatDate(rdata.reqshipmentdate),
      driverTel: rdata.driverTel,
      driver1st: rdata.driver1st,
      customerModelType: rdata.customerModelType,
      customerModelTypeName: rdata.customerModelTypeName,
      voucherno: rdata.voucherno,
      rplsumcases: rdata.rplsumcases,
      memo: rdata.memo
    };
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/secondAppoint/secondAppointConfirm", type: "post", contentType: "application/json", data: JSON.stringify(request),
      success: function (data) {
        PlgDialog.close(pload);
        if (data.success) {
          PlgDialog.msg(data.message);
          changePanel("#secondaryContract_main");
          master_grid.reload();
          // details_grid.clearAll();
          return true;
        }
        setTimeout(() => { PlgDialog.alert(data.message || "接口调用失败"); }, 300);
        return false;

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