<template>
  <el-table
    :data="tableData"
    :span-method="objectSpanMethod"
    border
    stripe
    style="width: 100%; margin-top: 20px"
    max-height="500px"
    @cell-click="cellClik"
  >
    <el-table-column
      width="50"
      label="序号"
      align="center"
      fixed="left"
      :resizable="false"
    >
      <template slot-scope="scope">{{ scope.row.group + 1 }}</template>
    </el-table-column>
    <el-table-column
      prop="saleOrderNo"
      label="销售订单号"
      width="200px"
      align="center"
    >
    </el-table-column>
    <el-table-column
      prop="consigneeName"
      label="下单客户"
      :width="flexColumnWidth('consigneeName', tableData, 'max')"
      align="center"
    >
    </el-table-column>
    <el-table-column
      prop="carrierName"
      label="承运商"
      align="center"
      width="250px"
    >
      <template slot-scope="scope">
        <el-autocomplete
          style="width:120px"
          v-model="scope.row.carrierName"
          :fetch-suggestions="querySearchCarrier"
          placeholder="请输入承运商"
          @select="handleSelectCarrier(scope.row, scope.$index)"
          :disabled="scope.row.isCarrierShow != 1"
        >
          <el-button
            @click="updateTruckCarrier(row)"
            type="primary"
            v-if="scope.row.isCarrierShow == 1"
            >提交</el-button
          >
        </el-autocomplete>
      </template>
    </el-table-column>
    <el-table-column
      prop="capacityNo"
      label="车牌号"
      align="center"
      width="250px"
    >
      <template slot-scope="scope">
        <el-autocomplete
          style="width:120px"
          v-model="scope.row.capacityNo"
          :fetch-suggestions="querySearch"
          placeholder="请输入车牌号"
          @select="handleSelect(scope.row, scope.$index)"
          :disabled="scope.row.isCapacityShow != 1"
        ></el-autocomplete>
        <el-button
          @click="updateCapacity(row)"
          type="primary"
          v-if="scope.row.isCapacityShow == 1"
          >提交</el-button
        >
      </template>
    </el-table-column>
    <el-table-column prop="capacityTel" label="司机电话" width="250px">
      <template slot-scope="scope">
        <el-input
          style="width:120px"
          v-model="scope.row.capacityTel"
          placeholder="请输入电话号码"
          :disabled="scope.row.isTelShow != 1"
        ></el-input>
        <el-button
          @click="updateDriverTel(scope.row)"
          type="primary"
          v-if="scope.row.isTelShow == 1"
          >提交</el-button
        >
      </template>
    </el-table-column>
    <el-table-column
      prop="addressPlace"
      label="收货地址"
      :width="flexColumnWidth('addressPlace', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column prop="orderStatus" label="运单状态" align="center">
    </el-table-column>
    <el-table-column
      prop="materialName"
      label="物资名称"
      align="center"
      :width="flexColumnWidth('materialName', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column prop="materialSpe" label="物资规格" align="center">
    </el-table-column>
    <el-table-column prop="grossWeight" label="毛重"> </el-table-column>
    <el-table-column
      prop="grossWeightTime"
      label="毛重时间"
      :width="flexColumnWidth('grossWeightTime', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column prop="tareWeight" label="皮重"> </el-table-column>
    <el-table-column
      prop="tareWeightTime"
      label="皮重时间"
      :width="flexColumnWidth('tareWeightTime', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column prop="netWeight" label="净重"> </el-table-column>
    <el-table-column
      prop="entryGateTime"
      label="进厂时间"
      :width="flexColumnWidth('entryGateTime', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column
      prop="loadTime"
      label="装货时间"
      :width="flexColumnWidth('loadTime', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column
      prop="outGateTime"
      label="出厂时间"
      :width="flexColumnWidth('outGateTime', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column
      prop="arrivalAddress"
      label="抵达地址"
      :width="flexColumnWidth('arrivalAddress', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column
      prop="receiptAddress"
      label="签收地址"
      :width="flexColumnWidth('receiptAddress', tableData, 'max')"
    >
    </el-table-column>
    <el-table-column prop="orderNo" label="运输订单号"> </el-table-column>
    <el-table-column prop="saler" label="业务员"> </el-table-column>
    <el-table-column prop="shipperName" label="发货单位"> </el-table-column>
    <el-table-column prop="truckNo" label="车序号"> </el-table-column>
    <el-table-column prop="consigneeTel" label="收货客户电话">
    </el-table-column>
    <el-table-column prop="isSelfMention" label="是否自提"> </el-table-column>
    <el-table-column prop="saleOrderStatus" label="销售订单状态">
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="200px">
      <template slot-scope="scope">
        <el-button type="text" size="small" @click="deleteEasEntryId(scope.row)"
          >关闭分录</el-button
        >
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { sjTime } from "@/utils/sharedJsFile";
import { getCookie } from "@/utils/util.js";
export default {
  name: "steelReport",
  data() {
    return {
      capacityList: [],
      carrierList: [],
      tableData: [],
      spanArr: [],
      pos: 0,
      isCellClick: 0,
      columnIndexs: [
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        15,
        16,
        17,
        18,
        19,
        20,
        21,
        22,
        23,
        24,
        25,
        26
      ]
    };
  },
  mounted() {
    this.getSteelReport();
  },
  methods: {
    cellClik(row, column, cell, event) {
      if (column.property == "capacityNo") {
        this.$set(row, "isCapacityShow", 1);
      }
      if (column.property == "carrierName") {
        this.$set(row, "isCarrierShow", 1);
      }
      if (column.property == "capacityTel") {
        this.$set(row, "isTelShow", 1);
      }
      if (column.property == "capacityTel") {
        this.$set(row, "isTelShow", 1);
      }
    },
    //承运商弹出层
    handleSelectCarrier(row, index, item) {
      console.log(this.carrierList);
      console.log(row);
    },
    //承运商边输边查
    querySearchCarrier(queryString, cb) {
      this.axios
        .post("/api/v1/uc/getCarrierMesByLike?index=" + queryString)
        .then(res => {
          if (res.data.code == "200") {
            var restaurants = res.data.data;
            this.carrierList = res.data.data;
            console.log(restaurants);
            var results = queryString
              ? restaurants.filter(this.createFilterCarrier(queryString))
              : restaurants;
            cb(results);
          }
        });
    },
    createFilterCarrier(queryString) {
      return restaurants => {
        return (
          restaurants.value1.toLowerCase().indexOf(queryString.toLowerCase()) >
          -1
        );
      };
    },
    //以下是车牌号边输边查搜索
    querySearch(queryString, cb) {
      if (queryString.length > 3) {
        this.axios
          .post("/api/v1/uc/getCapacityByLike?index=" + queryString)
          .then(res => {
            if (res.data.code == "200") {
              if (res.data.data.length == 0) {
                this.$message.info("车牌号不存在");
                return;
              }
              this.capacityList = [];
              var restaurants = res.data.data;
              this.capacityList = 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
        );
      };
    },
    //车牌号弹出层
    handleSelect(row, index) {
      this.capacityList.forEach(item => {
        if (item.capacityNumber === row.capacityNo) {
          row.newCapacityId = item.capacityId;
        }
      });
    },
    //更换车牌号接口
    updateCapacitySure() {
      let map = {
        orderId: this.orderId,
        saleOrderMaterialId: this.saleOrderMaterialId,
        lineSequence: this.lineSequence,
        capacityId: this.newCapacityId
      };
      this.axios
        .post("/api/v1/ams/updateCapacityNumberInFactory", map)
        .then(res => {
          if (res.data.code == 200) {
            this.$message.success("变更成功");
            this.getSteelReport();
          } else {
            this.$message.success("变更失败，请联系管理员");
            this.getSteelReport();
          }
        })
        .catch(() => {
          this.$message.success("变更失败，请联系管理员");
          this.getSteelReport();
        });
    },
    //修改司机电话号码
    updateDriverTel(row) {
      console.log(row.capacityTel);
      this.axios
        .post("/api/v1/uc/updateDriverTel", {
          orderId: parseInt(row.orderId),
          driverTel: row.capacityTel
        })
        .then(res => {
          if (res.data.code == "200") {
            this.$message.success("修改成功");
            this.getSteelReport();
          } else {
            this.$message.error("修改失败");
            this.getSteelReport();
          }
        })
        .catch(() => {
          this.$message.error("修改失败");
          this.getSteelReport();
        });
    },
    //关闭金蝶分录
    deleteEasEntryId(row) {
      let title = `确定关闭-${this.capacityNumber}-金蝶分录?`;
      this.$confirm(title, {
        confirmButtonText: "是",
        cancelButtonText: "否",
        center: true,
        type: "warning"
      })
        .then(() => {
          let map = row;
          map.isCloseEas = Number(0);
          map.saleOrderId = this.$route.params.saleOrderId;
          this.axios
            .post("/api/v1/ams/updateCarAddress", map)
            .then(res => {
              if (res.data.code == "200") {
                this.$message.success("关闭成功");
                this.getOrderList();
              } else {
                this.$message.error("关闭失败");
                this.getOrderList();
              }
            })
            .catch(() => {
              this.$message.error("关闭失败");
              this.getOrderList();
            });
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },
    //修改承运商授权
    //修改承运商授权
    updateTruckCarrier(row) {
      console.log(row);
      let map = {
        carrierId: this.carrierId,
        saleOrderMaterialId: this.saleOrderMaterialId
      };
      this.axios.post("/api/v1/ams/updateTruckNoCarrier", map).then(res => {
        if (res.data.code == "200") {
          this.$message.success("修改授权成功");
          this.getRequestUrl();
          this.dialogTableVisible = false;
        }
      });
    },
    //记录每一行的合并数
    getSpanArr(data) {
      //每次调用方法初始化
      this.spanArr = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          data[i].group = i;
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].saleOrderMaterialId === data[i - 1].saleOrderMaterialId) {
            this.spanArr[this.pos] += 1;
            data[i].group = data[i - 1].group;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
            data[i].group = data[i - 1].group + 1;
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.columnIndexs.indexOf(columnIndex) != -1) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    getSteelReport() {
      let carrierSsoId = null;
      if (getCookie("orgCode") == "chengyunshang") {
        carrierSsoId = getCookie("userId");
      }
      this.axios
        .post(
          "/api/v1/tms/getSaleSteelReport?startTime=" +
            null +
            "&endTime=" +
            null +
            "&carrierSsoId=" +
            carrierSsoId
        )
        .then(res => {
          this.tableData = res.data.data;
          this.getSpanArr(res.data.data);
        });
    },
    flexColumnWidth(str, tableData, flag) {
      // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
      // flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
      // flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
      str = str + "";
      let columnContent = "";
      if (
        !tableData ||
        !tableData.length ||
        tableData.length === 0 ||
        tableData === undefined
      ) {
        return;
      }
      if (!str || !str.length || str.length === 0 || str === undefined) {
        return;
      }
      if (flag === "equal") {
        // 获取该列中第一个不为空的数据(内容)
        for (let i = 0; i < tableData.length; i++) {
          if (tableData[i][str].length > 0) {
            columnContent = tableData[i][str] + "";
            break;
          }
        }
      } else {
        // 获取该列中最长的数据(内容)
        let index = 0;
        for (let i = 0; i < tableData.length; i++) {
          if (tableData[i][str] === null) {
            // 当数据为空时跳过本次循环获取下一条数据长度
            continue;
          }
          const now_temp = tableData[i][str] + "";
          const max_temp = tableData[index][str] + "";
          if (now_temp.length > max_temp.length) {
            index = i;
          }
        }
        columnContent = tableData[index][str] + "";
      } // 以下分配的单位长度可根据实际需求进行调整
      let flexWidth = 0;
      if (columnContent != undefined) {
        for (const char of columnContent) {
          if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
            // 如果是英文字符，为字符分配10个单位宽度
            flexWidth += 10;
          } else if (char >= "\u4e00" && char <= "\u9fa5") {
            // 如果是中文字符，为字符分配16个单位宽度
            flexWidth += 14;
          } else {
            // 其他种类字符，为字符分配10个单位宽度
            flexWidth += 10;
          }
        }
      }
      if (flexWidth < 80) {
        // 设置最小宽度
        flexWidth = 80;
      }
      if (flexWidth > 500) {
        // 设置最大宽度
        flexWidth = 500;
      }
      return flexWidth + "px";
    }
  }
};
</script>
