<template>
  <div class="addSaleOrderSend">
    <page-title>新增销售订单钢材派车</page-title>
    <!-- 派车表格 -->
    <div class="selectionTable from">
      <el-table
        :data="selectionList"
        border
        style="width: 100%"
        highlight-current-row
        :span-method="cellMerge"
      >
        <el-table-column
          v-for="(item, i) in tableTop"
          :key="i"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          align="center"
          show-overflow-tooltip
        >
          <template slot="scope" v-if="item.label !== '车牌号'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '承运商'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '件数'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '运输线路'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '运输单价'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '订单有效期'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '收货客户'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '收货客户电话号码'">
            <span>{{ item.label }}</span>
          </template>
          <template slot="scope" v-if="item.label !== '备注'">
            <span>{{ item.label }}</span>
          </template>
          <!-- 插入输入框 -->
          <template slot-scope="scope">
            <template v-if="item.slot">
              <!-- 车牌号 -->
              <template v-if="item.prop == 'capacityNumber'">
                <el-autocomplete
                  class="inline-input"
                  v-model="scope.row.capacityNumber"
                  :fetch-suggestions="querySearch"
                  placeholder="(必填)"
                  :trigger-on-focus="false"
                  @select="handleSelect(scope.row, scope.$index)"
                  @blur="checkRelationship(scope.$index)"
                  @change="batchUpdateValue(scope.row, scope.$index)"
                ></el-autocomplete>
              </template>

              <!-- 司机电话号码 -->
              <template v-if="item.prop == 'driverTel'">
                <el-input
                  class="textinput"
                  placeholder="(必填)"
                  @blur="checkIsTelephone(scope.$index)"
                  v-model="scope.row.driverTel"
                ></el-input>
              </template>

              <!-- 承运商 -->
              <template v-if="item.prop == 'carrierName'">
                <el-select
                  v-model="scope.row.carrierName"
                  placeholder="请选择"
                  @change="batchUpdateValue(scope.row, scope.$index)"
                  disabled
                >
                  <el-option
                    v-for="item in carrierNameOptions[scope.$index]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>

              <!-- 物资件数 -->
              <template v-if="item.prop == 'orderPlanWeight'">
                <el-input
                  class="textinput"
                  @input="onInput"
                  placeholder="(必填)"
                  v-model.number="scope.row.orderPlanWeight"
                  disabled
                ></el-input>
              </template>

              <!-- 物资重量 -->
              <template v-if="item.prop == 'materialWeight'">
                <el-input
                  class="textinput"
                  v-model.number="scope.row.materialWeight"
                  disabled
                ></el-input>
              </template>

              <!-- 运输单价id -->
              <template v-if="item.prop == 'priceValue'">
                <el-input v-model="scope.row.priceValue" disabled> </el-input>
              </template>
              <!-- 订单有效期 -->
              <template v-if="item.prop == 'saleDateOfReceipt'">
                <el-date-picker
                  class="textinput3"
                  type="date"
                  v-model.number="scope.row.saleDateOfReceipt"
                  style="width:135px"
                  disabled
                ></el-date-picker>
              </template>
              <!-- 收货客户 -->
              <template v-if="item.prop == 'saleOrderConsignee'">
                <el-input
                  class="textinput4"
                  placeholder="(非必填)"
                  v-model.number="scope.row.saleOrderConsignee"
                  disabled
                ></el-input>
              </template>
              <!-- 收货客户电话号码 -->
              <template v-if="item.prop == 'saleOrderConsigneeTel'">
                <el-input
                  class="textinput5"
                  placeholder="(非必填)"
                  v-model.number="scope.row.saleOrderConsigneeTel"
                  @input="onInput"
                  disabled
                ></el-input>
              </template>
            </template>
            <template v-else>
              <span>{{ scope.row[item.prop] }}</span>
            </template>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <!-- <el-table-column fixed="right" label="操作" width="100">
        </el-table-column> -->
      </el-table>
    </div>

    <div class="button_box">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="makeSure" :loading="isLoading"
        >确定</el-button
      >
    </div>
  </div>
</template>

<script>
import PageTitle from "@/components/Page/Title";
import { getCookie } from "@/utils/util.js";
import { sjTime, isNumber, isIntegerNumber } from "@/utils/sharedJsFile";
import returnResultVue from "../../../inward/components/offsetSteel/truckTransport/returnResult.vue";
export default {
  components: { PageTitle },
  data() {
    return {
      //是否正在加载
      isLoading: false,
      //存放每一行记录的合并数
      spanArr: [],
      //pos是spanArr的索引
      pos: 0,
      //加载
      selectLineLoading: false,
      //承运商下拉框中的值
      carrierNameOptions: [],
      //当前车序号物资
      selectionList: [],
      driverTel1: null,
      //是否可发送请求
      canSend: 1,
      statusStr: null,
      tableTop: [
        {
          prop: "truckNo",
          label: "车序号",
          width: "50"
        },
        {
          prop: "capacityNumber",
          label: "车牌号",
          width: "130",
          slot: true
        },
        {
          prop: "driverTel",
          label: "司机电话号码",
          width: "150",
          slot: true
        },
        {
          prop: "carrierName",
          label: "承运商",
          width: "240",
          slot: true
        },
        {
          prop: "materialName",
          label: "物资名称",
          width: "140"
        },
        {
          prop: "Specification",
          label: "规格型号",
          width: "140"
        },
        {
          prop: "orderPlanWeight",
          label: "件数",
          width: "80",
          slot: true
        },
        {
          prop: "materialWeight",
          label: "重量",
          width: "80",
          slot: true
        },
        {
          prop: "lineName",
          label: "厂内运输线路",
          width: "220"
        },
        {
          prop: "saleDateOfReceipt",
          label: "订单有效期",
          width: "150",
          slot: true
        },
        {
          prop: "saleShipperAddressName",
          label: "收货地址",
          width: "300"
        },
        {
          prop: "priceValue",
          label: "运输单价",
          width: "80",
          slot: true
        },
        {
          prop: "saleOrderConsignee",
          label: "收货客户",
          width: "150",
          slot: true
        },
        {
          prop: "saleOrderConsigneeTel",
          label: "收货客户电话号码",
          slot: true,
          width: "150"
        },
        {
          prop: "materialCode",
          label: "物资编码",
          width: "140"
        },
        {
          prop: "truckRemark",
          label: "备注",
          width: "140"
        }
      ]
    };
  },
  created() {
    this.getValue();
  },
  methods: {
    getValue() {
      let map = {};
      if (getCookie("orgCode") == "chengyunshang") {
        map.saleOrderId = this.$route.params.saleOrderId;
        map.carrierSsoId = getCookie("userId");
      } else {
        map.saleOrderId = this.$route.params.saleOrderId;
      }
      this.axios
        .post("/api/v1/ams/getCarrierTruckNoAndMaterialList", map)
        .then(res => {
          if (res.data.data.length == 0) {
            this.$confirm("该销售订单尚未排车!是否先进行排车?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              center: true
            })
              .then(() => {
                this.$router.push(
                  "/addSaleOrderArrange/" + this.$route.params.saleOrderId
                );
              })
              .catch(() => {
                this.$message({ type: "info", message: "取消!" });
              });
          }
          console.log("res.data.data", res.data.data);
          this.statusStr = res.data.data[0].statusStr;
          //赋值派车表格
          res.data.data.forEach((e, i) => {
            if (e.saleOrderConsignee == "null") {
              e.saleOrderConsignee = null;
            }
            if (e.saleOrderConsigneeTel == "null") {
              e.saleOrderConsigneeTel = null;
            }
            //带承运商初始化派车表格
            var addmap = {
              truckNo: e.truckNo,
              saleOrderMaterialId: e.saleOrderMaterialId,
              capacityNumber: null,
              driverTel: null,
              carrierName: e.carrierName,
              carrierId: e.carrierId,
              materialId: e.materialId,
              materialName: e.materialName,
              Specification: e.materialModelSpecification,
              materialCode: e.materialCode,
              orderPlanWeight: e.materialNumber,
              materialWeight: e.materialWeight,
              lineName: null,
              lineId: null,
              saleShipperAddressId: e.placeId,
              saleShipperAddressName: e.place,
              saleDateOfReceipt: e.receiptDate,
              saleOrderConsignee: e.saleOrderConsignee,
              saleOrderConsigneeTel: e.saleOrderConsigneeTel,
              truckRemark: e.truckRemark
            };
            this.selectionList.push(addmap);
            //调用记录每一行的合并数的方法
            this.getSpanArr(this.selectionList);
            //初始化每个车的线路
            this.initializeLine();
          });
        });
    },
    onInput(val) {
      if (!isNumber(val)) {
        this.$message.warning("重量/电话号码请输入数字");
      }
    },
    //校验是否为车牌
    isVehicleNumber(vehicleNumber) {
      var result = false;
      if (vehicleNumber != null) {
        if (vehicleNumber.length == 7) {
          var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
          result = express.test(vehicleNumber);
        }
      }
      return result;
    },
    //绑定车牌号和承运商的关系
    bindRelationship(mapValue) {
      let RmsCapacity = {
        capacityTypeId: 1,
        capacityNumber: mapValue.capacityNumber,
        capacityCorlor: "黄",
        capacityOwneris: "否",
        capacityVip: "否",
        capacityBlacklist: "否",
        remark: null,
        carrierId: mapValue.carrierId,
        state: mapValue.carrierName
      };
      this.$confirm(
        "车牌号(" +
          mapValue.capacityNumber +
          ")与承运商未有绑定关系, 是否立即绑定该车牌号和承运商?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.axios
            .post("/api/v1/rms/insertCapacity", RmsCapacity)
            .then(res => {
              console.log("res", res);
              if (res.data.data == 0) {
                this.$message.success("该车牌号与承运商绑定关系成功!");
              }
            });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    //失焦事件后确定车牌号与承运商是否有绑定关系
    checkRelationship(index) {
      if (this.selectionList[index].carrierId != null) {
        //暂存车牌号
        var capacityNumber1;
        if (this.isVehicleNumber(this.selectionList[index].capacityNumber)) {
          let mapValue = {
            capacityNumber: this.selectionList[index].capacityNumber,
            carrierId: this.selectionList[index].carrierId,
            carrierName: this.selectionList[index].carrierName
          };
          this.axios
            .post("/api/v1/uc/isInCapacityCarrier", mapValue)
            .then(res => {
              if (res.data.code == "201") {
                capacityNumber1 = res.data.data;
                if (capacityNumber1 == null) {
                  this.selectionList[index].capacityNumber = null;
                  this.$message.error("该车牌号未注册,请先前往注册!");
                } else {
                  this.bindRelationship(mapValue);
                }
              }
            });
        }
      }
    },
    //车牌号弹出层
    handleSelect(row, index) {
      this.axios
        .post(
          "/api/v1/ams/matchingDriverTelRecently?capacityNumber=" +
            row.capacityNumber
        )
        .then(res => {
          row.driverTel = res.data.data;
        });
    },
    //以下是车牌号边输边查搜索
    querySearch(queryString, cb) {
      this.axios
        .post("/api/v1/uc/getCapacityByLike?index=" + queryString)
        .then(res => {
          if (res.data.code == "200") {
            var restaurants = res.data.data;
            var results = queryString
              ? restaurants.filter(this.createFilter(queryString))
              : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
          }
        });
    },
    createFilter(queryString) {
      return restaurants => {
        return (
          restaurants.value.toLowerCase().indexOf(queryString.toLowerCase()) >
          -1
        );
      };
    },
    //以上是车牌号边输边查搜索

    //校验是否为电话号码
    checkIsTelephone(index) {
      //电话号码校验
      var reg = /^[1][345789]\d{9}$/;
      if (!reg.test(this.selectionList[index].driverTel)) {
        this.canSend = -1;
        this.$message.warning("电话号码格式不正确,请输入正确的电话号码!");
      } else {
        this.canSend = 1;
      }
    },
    //点击确定按钮的事件
    makeSure() {
      this.isLoading = true;
      //是否可发送请求
      if (this.canSend == -1) {
        this.$message.warning("电话号码格式不正确,请输入正确的电话号码!");
      } else {
        this.$confirm("是否确定进行钢材派单！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
          .then(() => {
            var mapList = [];
            for (var i = 0; i < this.spanArr.length; i++) {
              if (this.spanArr[i] > 0 && this.selectionList[i].capacityNumber) {
                var mapItem = {
                  //车牌号
                  capacityNumber: null,
                  //司机电话号码
                  driverTel: null,
                  //车序号主键
                  saleOrderMaterialId: 0,
                  //承运商Id
                  carrierId: 0,
                  //线路Id
                  lineId: 0
                };
                mapItem.capacityNumber = this.selectionList[i].capacityNumber;
                mapItem.driverTel = this.selectionList[i].driverTel;
                mapItem.saleOrderMaterialId = this.selectionList[
                  i
                ].saleOrderMaterialId;
                mapItem.carrierId = this.selectionList[i].carrierId;
                mapItem.lineId = this.selectionList[i].lineId;
                mapList.push(mapItem);
              }
            }
            this.axios
              .post("/api/v1/ams/dispatchSteelOrder", mapList)
              .then(res => {
                if (res.data.code == "200") {
                  this.cancel();
                  this.$message.success("派单成功！");
                  this.isLoading = false;
                } else {
                  this.$message.error("派单失败:" + res.data.data);
                  this.isLoading = false;
                }
                this.isLoading = false;
              });
          })
          .catch(() => {
            this.$message({ type: "info", message: "取消!" });
            this.isLoading = false;
          });
      }
    },
    //点击取消按钮的事件
    cancel() {
      this.$router.push("/saleOrderSteelCarrier");
    },

    //批量修改内层值
    batchUpdateValue(row, index) {
      for (var i = index; i < this.spanArr[index] + index; i++) {
        this.selectionList[i].capacityNumber = row.capacityNumber;
        this.selectionList[i].driverTel = this.driverTel1;
      }
    },
    //初始化线路
    initializeLine() {
      for (var i = 0; i < this.spanArr.length; i++) {
        if (this.spanArr[i] == 1) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材单拼路线" + " " + "进厂-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110001;
          }
        }
        if (this.spanArr[i] == 2) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材二拼路线" +
              " " +
              "计皮-进厂-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110002;
          }
        }
        if (this.spanArr[i] == 3) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材三拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110003;
          }
        }
        if (this.spanArr[i] == 4) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材四拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110004;
          }
        }
        if (this.spanArr[i] == 5) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材五拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110005;
          }
        }
        if (this.spanArr[i] == 6) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材六拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110006;
          }
        }
        if (this.spanArr[i] == 7) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材七拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110007;
          }
        }
        if (this.spanArr[i] == 8) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材八拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110008;
          }
        }
        if (this.spanArr[i] == 9) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材九拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110009;
          }
        }
        if (this.spanArr[i] == 10) {
          for (var j = i; j < this.spanArr[i] + i; j++) {
            this.selectionList[j].lineName =
              "总厂：销售钢材十拼路线" +
              " " +
              "进厂-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-计皮-装货-计毛-出厂";
            this.selectionList[j].lineId = 110010;
          }
        }
      }
    },
    //记录每一行的合并数
    getSpanArr(data) {
      //每次调用方法初始化
      this.spanArr = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].truckNo === data[i - 1].truckNo) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
        }
      }
    },
    //根据条件合并行
    cellMerge({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 1) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 2) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 3) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 8) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 9) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 10) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 11) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 12) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 13) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 15) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    }
  }
};
</script>

<style lang="scss">
.addSaleOrderSend {
  .from {
    margin-top: 20px;
    .line {
      display: flex;
      justify-content: center;
      align-items: center;
      .el-input {
        width: 350px;
        margin-left: 10px;
        margin-right: 10px;
      }
    }
    .sendCar {
      display: flex;
      justify-content: center;
      align-items: center;
      .el-input {
        width: 70px;
        margin-left: 10px;
        margin-right: 10px;
        margin-top: 10px;
      }
    }
    .vehicle {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 20px;
      .el-button {
        width: 250px;
        margin-left: 10px;
        margin-right: 10px;
      }
      .span {
        width: 70px;
      }
    }
  }
  .tablecls {
    margin-top: 20px;
  }
  .button_box {
    display: flex;
    justify-content: center;
    margin: 20px;
    .el-button {
      width: 100px;
      margin-left: 20px;
    }
  }
}
</style>
