<!-- 内转钢材到异地库派单界面 -->
<template>
  <div class="purchasFuelNewMonitor">
    <div class="tableTop">
      <el-form :inline="true" style="margin-top: 5px">
        <el-form-item>
          <el-select
            v-model="screen"
            placeholder="请选择需筛选的内容"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            style="width: 200px"
            v-model="input"
            placeholder="请输入查询条件"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="screen1"
            placeholder="请选择需筛选的内容"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            style="width: 200px"
            v-model="input1"
            placeholder="请输入查询条件"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <label class="el-form-item__label" style="width: auto"
            >订单时间：</label
          >
          <el-date-picker
            v-model="startTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 200px"
          >
          </el-date-picker>
          <span>至</span>
          <el-date-picker
            v-model="endTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 200px"
          >
          </el-date-picker>
          <el-button type="primary" class="btn" @click="onclick">
            <i class="el-icon-search"></i>
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refresh">
            <i class="el-icon-refresh"></i>
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportAllReportToExcel"
            ><i class="el-icon-download"></i>Excel</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="showDialog">多拼派车</el-button>、
          <el-button type="primary" @click="mergeSplit()">
            <i class="el-icon-pie-chart"></i>
            合并或拆分
          </el-button>
          <el-button @click="deleteClick" type="primary">
            关闭
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table
        :data="tableData"
        :span-method="objectSpanMethod"
        ref="tableRef"
        border
        style="width: 100%; margin-top: 20px"
        max-height="500px"
        @cell-click="cellClik"
        :row-style="{ height: '30px' }"
        :cell-style="{ fontWeight: '700' }"
      >
        <el-table-column type="selection" width="30" align="center">
        </el-table-column>
        <el-table-column
          prop="index"
          width="30"
          label="序号"
          align="center"
          :resizable="false"
        >
          <template slot-scope="scope">{{ scope.row.group + 1 }}</template>
        </el-table-column>
        <el-table-column
          prop="netWeight"
          label="净重"
          align="center"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="tareWeight"
          label="皮重"
          align="center"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="inwardSteelType"
          label="类型"
          align="center"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="consigneeName"
          label="收货单位"
          width="196px"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="sendStation"
          column-key="sendStation"
          label="发站"
          align="center"
          width="70px"
          :filters="[
            { text: '专用线', value: '专用线' },
            { text: '达州站', value: '达州站' }
          ]"
          :filter-method="filterSend"
        >
        </el-table-column>
        <el-table-column
          prop="capacityNo"
          column-key="capacityNo"
          label="车牌号"
          align="center"
          width="200px"
        >
          <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 || scope.row.orderStatus == 2
              "
            ></el-autocomplete>
            <el-button
              @click="updateCapacity(scope.row)"
              type="primary"
              v-if="scope.row.isCapacityShow == 1 && scope.row.orderStatus != 2"
              >提交</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="toTheStation"
          label="到站"
          align="center"
          width="108px"
        >
        </el-table-column>
        <el-table-column
          prop="materialName"
          label="物资名称"
          align="center"
          width="125px"
        >
        </el-table-column>
        <el-table-column
          prop="materialSpe"
          label="物资规格"
          align="center"
          width="100px"
        >
        </el-table-column>
        <el-table-column
          prop="materialNum"
          label="件数"
          align="center"
          width="40px"
        >
          <!-- <template slot-scope="scope">
            <button
              type="primary"
              @click="scope.row.materialNum--"
              v-if="scope.row.isNumShow == 1"
              style="height: 40px"
            >
              -
            </button>
            <input
              v-model="scope.row.materialNum"
              disabled
              style="
                width: 40px;
                height: 40px;
                font-size: 16px;
                line-height: 40px;
                text-align: center;
              "
            />
            <el-button
              type="primary"
              @click="updateBillOrder(scope.row)"
              v-if="scope.row.isNumShow == 1"
              >提交</el-button
            >
          </template> -->
        </el-table-column>
        <el-table-column
          prop="flId"
          label="分录ID"
          align="center"
          width="120px"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="saleOrderNo"
          label="单据编号"
          width="200px"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="transInDep"
          label="调入部门"
          width="120px"
          align="center"
          column-key="transInDep"
        >
        </el-table-column>
        <el-table-column
          prop="transInWarehouse"
          label="调入仓库"
          width="120px"
          align="center"
          column-key="transInWarehouse"
        >
        </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-autocomplete>
            <el-button
              @click="updateTruckCarrier(scope.row)"
              type="primary"
              v-if="scope.row.isCarrierShow == 1"
              >提交</el-button
            >
          </template> -->
        </el-table-column>
        <el-table-column
          prop="orderNumber"
          label="运输订单号"
          width="180px"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="transOutDep"
          label="调出部门"
          width="120px"
          align="center"
          column-key="transOutDep"
        >
        </el-table-column>
        <el-table-column
          prop="capacityTel"
          label="司机电话"
          width="250px"
          align="center"
        >
          <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="shipperName"
          label="发货单位"
          width="170px"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="optionCode"
          label="派车人"
          width="120px"
          align="center"
        >
        </el-table-column>
      </el-table>
    </div>
    <!-- 多拼弹出层-->
    <el-dialog
      title="生成多拼"
      :visible.sync="dialogTableVisible"
      style="width: 500px"
    >
      <el-form :inline="true">
        <el-form-item>
          <el-autocomplete
            style="width: 120px"
            v-model="capacityNo"
            :fetch-suggestions="querySearch"
            placeholder="请输入车牌号"
            @select="handleMulSelect"
          ></el-autocomplete>
          <el-button @click="updateMulCapacity" type="primary">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { sjTime, isVehicleNumber } from '@/utils/sharedJsFile'
import { getCookie } from '@/utils/util.js'
export default {
  data() {
    return {
      // 线路名称
      lineName: '',
      //线路id
      lineId: null,
      drawer: false,
      clickIndex: null,
      input: null,
      screen: '',
      input1: null,
      screen1: '',
      dialogTableVisible: false,
      newsCapacityId: null,
      capacityNo: null,
      selection: [],
      options: [
        {
          value: '收货单位',
          lable: '收货单位'
        },
        {
          value: '车牌号',
          lable: '车牌号'
        },
        {
          value: '物资名称',
          lable: '物资名称'
        },
        {
          value: '规格型号',
          lable: '规格型号'
        },
        {
          value: '发站',
          lable: '发站'
        }
      ],
      options1: [
        {
          value: '收货单位',
          lable: '收货单位'
        },
        {
          value: '车牌号',
          lable: '车牌号'
        },
        {
          value: '物资名称',
          lable: '物资名称'
        },
        {
          value: '规格型号',
          lable: '规格型号'
        },
        {
          value: '发站',
          lable: '发站'
        }
      ],
      startTime: null,
      endTime: null,
      //合计净重
      totalNumber: 0,
      //合计车数
      totalCapacity: 0,
      tableTitle: '库存调拨派单',
      capacityList: [],
      carrierList: [],
      // 线路
      LineList: [],
      tableData: [],
      spanArr: [],
      pos: 0,
      a: 1,
      isCellClick: 0,
      //需要合并的行
      mergeList: [
        'saleOrderNo',
        'shipperName',
        'capacityTel',
        'orderNo',
        'carrierName',
        'transInWarehouse',
        'transOutDep',
        'transInDep',
        'capacityNo',
        'sendStation',
        'consigneeName',
        'index'
      ],
      //钢材多拼车辆线路ID
      //索引从1-10为1-10拼路线ID
      // lineSpelling: [
      //   0,
      //   110001,
      //   110002,
      //   110003,
      //   110004,
      //   110005,
      //   110006,
      //   110007,
      //   110008,
      //   110009,
      //   110010
      // ],
      //达州站内转多拼车辆线路ID,从1-5为1-5拼线路id
      lineDazhou: [0, 189982, 189983, 189984, 189985, 189986],
      //专用线内转多拼车辆线路ID,从1-5为1-5拼线路id
      lineZhuanxian: [0, 189987, 189988, 189989, 189990, 189991],
      sendStationId: null,
      sendStations: [],
      direction: 'rtl',
      filterMap: {}
    }
  },
  mounted() {
    this.getSteelReport()
    this.getSendStations()
  },
  methods: {
    deleteClick() {
      if (this.$refs.tableRef.selection.length == 1) {
        let map = {
          orderId: this.$refs.tableRef.selection[0].orderId,
          userId: getCookie('userId')
        }
        this.$confirm('是否关闭?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.axios.post('/api/v1/oms/closeOmstruckOrder', map).then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '关闭成功!'
                })
                this.getRequestUrl()
              } else {
                this.$message({
                  message: '关闭失败',
                  type: 'warning'
                })
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else {
        this.$message({
          type: 'error',
          duration: '2500',
          message: '请选择一条订单',
          offset: '250'
        })
        return
      }
    },
    mergeSplit() {
      if (this.$refs.tableRef.selection.length > 0) {
        if (!this.$refs.tableRef.selection[0].saleOrderMaterialId) {
          this.$message({
            type: 'error',
            duration: '2500',
            message: '请所有分录均派车后再进行该操作',
            offset: '250'
          })
          return
        }
      }
      if (this.$refs.tableRef.selection.length == 1) {
        this.$confirm(
          `尊敬的用户${getCookie(
            'loginName'
          )},系统温馨提示您进行拆分操作前,请确认所拆分的订单将不会在金蝶进行提交,审核等操作!`,
          '提醒',
          {
            confirmButtonText: '我已确认',
            cancelButtonText: '我再想想',
            center: true,
            type: 'warning'
          }
        )
          .then(() => {
            this.splitOrder()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              duration: '2500',
              message: '操作取消',
              offset: '250'
            })
          })
      } else if (this.$refs.tableRef.selection.length > 1) {
        this.$confirm(
          `尊敬的用户${getCookie(
            'loginName'
          )},系统温馨提示您进行合并操作前,请确认所合并的订单将不会在金蝶进行提交,审核等操作!`,
          '提醒',
          {
            confirmButtonText: '我已确认',
            cancelButtonText: '我再想想',
            center: true,
            type: 'warning'
          }
        )
          .then(() => {
            this.mergeOrder()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              duration: '2500',
              message: '操作取消',
              offset: '250'
            })
          })
      } else {
        this.$message({
          type: 'warning',
          message: '请勾选/点击需要操作的行',
          offset: '250',
          duration: '2300'
        })
      }
    },
    splitOrder() {
      this.$confirm(
        `勾选了${this.$refs.tableRef.selection.length}条运单将执行拆分操作`,
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }
      )
        .then(() => {
          let mapList = this.$refs.tableRef.selection.map(e => {
            let map = {}
            map.saleOrderMaterialId = e.saleOrderMaterialId
            return map
          })
          let map = {
            mapList: mapList,
            userName: getCookie('loginName')
          }
          this.axios
            .post('/api/v1/ams/splitOrder', map)
            .then(res => {
              if (res.data.code == '200') {
                this.onclick(this.filterMap)
                this.$message({
                  type: 'success',
                  message: '拆分成功',
                  offset: '250',
                  duration: '2500'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.data,
                  offset: '250',
                  duration: '2500'
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '拆分失败',
                offset: '250',
                duration: '2500'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            duration: '2500',
            message: '操作取消',
            offset: '250'
          })
        })
    },
    mergeOrder() {
      this.$confirm(
        `勾选了${this.$refs.tableRef.selection.length}条运单将执行合并操作,此操作不可逆!`,
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }
      )
        .then(() => {
          console.log(
            this.$refs.tableRef.selection,
            'this.$refs.tableRef.selection'
          )
          let mapList = this.$refs.tableRef.selection.map(e => {
            let map = {}
            map.saleOrderMaterialId = e.saleOrderMaterialId
            map.orderId = e.orderId
            map.saleOrderId = e.saleOrderId
            map.orderNo = e.orderNo
            map.capacityNo = e.capacityNo
            map.userName = getCookie('loginName')
            return map
          })
          let map = {
            mapList: mapList,
            userName: getCookie('loginName')
          }
          this.axios
            .post('/api/v1/ams/mergeOrder', map)
            .then(res => {
              if (res.data.code == '200') {
                this.onclick(this.filterMap)
                this.$message({
                  type: 'success',
                  message: '合并成功,请提醒驾驶员!',
                  offset: '250',
                  duration: '3000'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.data,
                  offset: '250',
                  duration: '2500'
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '合并失败',
                offset: '250',
                duration: '2500'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            duration: '2500',
            message: '操作取消',
            offset: '250'
          })
        })
    },
    // dispatchSome() {
    //   console.log(this.tableData);
    //   //首先过滤掉已派车的数据
    //   let arr = this.tableData.filter(item => {
    //     return item.capacityIds == 0;
    //   });
    //   if (arr.length == 0) {
    //     ths.$message.error("没有符合条件的分录可供拼装");
    //     return;
    //   }
    //   console.log(arr);
    //   this.selection = arr;
    //   this.updateMulCapacity();
    // },
    //禁用已派车
    selectInit(row) {
      console.log(row)
      if (row.capacityIds != 0) {
        return false
      } else {
        return true
      }
    },
    filterSend(value, row, column) {
      return row.sendStation === value
    },
    //反关闭整条分录
    adverseCloseSaleMaterial(row) {
      console.log(row.saleMaterialId)
      this.$confirm('确定反关闭该条分录?', '提示', {
        cancelButtonText: '确定',
        confirmButtonText: '取消',
        center: true
      }).then(() => {
        this.axios
          .post(
            '/api/v1/ams/adverseCloseSaleMaterial?saleMaterialId=' +
              row.saleMaterialId
          )
          .then(res => {
            if (res.data.code == '200') {
              this.$message.success('反关闭成功')
              this.getSteelReport()
            } else {
              this.$message.error('反关闭失败')
              this.getSteelReport()
            }
          })
          .catch(() => {
            this.$message.error('反关闭失败')
            this.getSteelReport()
          })
      })
    },

    //销售钢材报表导出excel
    exportAllReportToExcel() {
      const loading = this.$loading({
        lock: true,
        text: '正在导出Excel',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      var title = this.tableTitle
      let tHeader = []
      let filterVal = []
      console.log(this.$refs.tableRef)
      this.$refs.tableRef.$children.forEach(item => {
        if (item.label != undefined && item.prop != undefined) {
          if (tHeader.indexOf(item.label) === -1) {
            tHeader.push(item.label)
          }
          if (filterVal.indexOf(item.prop) === -1) {
            filterVal.push(item.prop)
          }
        }
      })
      this.downloadLoading = true
      require.ensure([], () => {
        const {
          export_json_to_excel
        } = require('@/assets/excel/Export2Excel.js') //这里必须使用绝对路径，使用@/+存放export2Excel的路径
        let data = this.tableData.map(v => filterVal.map(j => v[j])) //3.formatJson格式转换
        export_json_to_excel(tHeader, data, title) // (title)导出的表格名称
      })
      loading.close()
    },
    cellClik(row, column, cell, event) {
      if (row.group != this.clickIndex) {
        // this.getSteelReport();
        this.tableData.forEach(item => {
          if (item.group == this.clickIndex) {
            this.$set(item, 'isCapacityShow', 0)
            this.$set(item, 'isCarrierShow', 0)
            this.$set(item, 'isTelShow', 0)
            this.$set(item, 'isSendStationName', 0)
          }
        })
      }
      if (column.property == 'capacityNo') {
        this.$set(row, 'isCapacityShow', 1)
        this.clickIndex = row.group
      }
      if (column.property == 'sendStation') {
        this.$set(row, 'isSendStationName', 1)
        this.clickIndex = row.group
        this.filterMap.sendStation = row.sendStation
        this.onclick(this.filterMap)
      }
      if (column.property == 'toTheStation') {
        this.filterMap.toTheStation = row.toTheStation
        this.onclick(this.filterMap)
      }
      if (column.property == 'consigneeName') {
        this.filterMap.consigneeName = row.consigneeName
        this.onclick(this.filterMap)
      }
      if (column.property == 'materialSpe') {
        this.filterMap.materialSpe = row.materialSpe
        this.onclick(this.filterMap)
      }
      if (column.property == 'materialName') {
        this.filterMap.materialName = row.materialName
        this.onclick(this.filterMap)
      }
      if (column.property == 'inwardSteelType') {
        this.filterMap.inwardSteelType = row.inwardSteelType
        this.onclick(this.filterMap)
      }
      if (column.property == 'carrierName') {
        this.$set(row, 'isCarrierShow', 1)
        this.clickIndex = row.group
      }
      if (column.property == 'capacityTel') {
        this.$set(row, 'isTelShow', 1)
        this.clickIndex = row.group
      }
    },
    //承运商弹出层
    handleSelectCarrier(row, index, item) {
      this.carrierList.forEach(item => {
        if (item.carrierName == row.carrierName) {
          row.newCarrierId = item.carrierId
          row.carrierId = item.carrierId
          row.carrierIds = item.carrierId
        }
      })
    },
    //承运商边输边查
    querySearchCarrier(queryString, cb) {
      if (queryString.length > 1) {
        this.axios
          .post('/api/v1/uc/getCarrierMesByLike?index=' + queryString)
          .then(res => {
            if (res.data.code == '200') {
              this.carrierList = []
              if (res.data.data.length == 0) {
                this.$message.info('承运商不存在,请前往注册')
                return
              }
              var restaurants = res.data.data
              this.carrierList = res.data.data
              var results = queryString
                ? restaurants.filter(this.createFilterCarrier(queryString))
                : restaurants
              cb(results)
            }
          })
      }
    },
    //获取发站
    getSendStations() {
      this.axios.get('/api/v1/uc/getInwardSendStation').then(res => {
        console.log(res.data.data)
        if (res.data.code == '200') {
          this.sendStations = res.data.data
        }
      })
    },
    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 => {
            this.capacityList = []
            if (res.data.code == '200') {
              if (res.data.data.length == 0) {
                this.$message.info('车牌号不存在,请前往注册')
                return
              }
              var restaurants = res.data.data
              this.capacityList = res.data.data
              var results = queryString
                ? restaurants.filter(this.createFilter(queryString))
                : restaurants
              // console.log("res",+results);
              // 调用 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.newsCapacityId = item.capacityId
        }
      })
    },
    //多拼弹出层绑定车牌号
    handleMulSelect(item) {
      console.log(item)
      this.capacityList.forEach(e => {
        if (item.capacityNumber === e.capacityNumber) {
          this.capacityNumber = e.capacityNumber
          this.capacityId = e.capacityId
        }
      })
    },

    updateSendStation(selection, row) {
      let sendStation = this.sendStations.find(
        item => item.sendStationId == row.sendStationId
      )
      row.sendStation = sendStation.sendStation
      console.log('sendStation', sendStation)
      console.log('row:', row)
    },

    updateCapacity(row) {
      row.isIwardSteel = 4
      row.capacityId = row.newsCapacityId
      if (row.newsCapacityId == null) {
        this.$message.warning('请先注册车牌号或者选中弹出后再提交!')
        return
      }
      if (!isVehicleNumber(row.capacityNo) && row.capacityNo != '车皮一个') {
        this.$message.error('请输入正确格式的车牌号!')
        return
      }
      if (row.capacityIds != 0) {
        const loading = this.$loading({
          lock: true,
          text: '正在变更车牌号',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        console.log('updateCapacityRow:', row)
        this.axios
          .post('/api/v1/ams/updateCapacityNumberInFactory', row)
          .then(res => {
            if (res.data.code == '200') {
              this.$message({
                message: '变更成功!',
                duration: 2000,
                type: 'success',
                offset: '250'
              })
              this.getSteelReport()
              loading.close()
            } else {
              this.$message({
                message: '变更失败，请联系管理员!',
                duration: 2000,
                type: 'error',
                offset: '250'
              })
              this.getSteelReport()
              loading.close()
            }
          })
          .catch(() => {
            this.$message({
              message: '变更失败，请联系管理员!',
              duration: 2000,
              type: 'error',
              offset: '250'
            })
            this.getSteelReport()
            loading.close()
          })
      } else {
        if (row.carrierIds == 0) {
          this.$message.error('请先选择承运商！')
          return
        }
        if (row.sendStation == null || row.sendStation == '') {
          this.$message.error('请先选择发站')
          return
        }
        row.driverTel = row.capacityTel
        row.capacityNumber = row.capacityNo
        let arr = []
        arr.push(row)
        if (arr[0].sendStation == '达州站') {
          arr.forEach(item => {
            item.lineId = this.lineDazhou[arr.length]
            item.lineName = '达州站'
          })
        } else if (arr[0].sendStation == '专用线') {
          arr.forEach(item => {
            item.lineId = this.lineZhuanxian[arr.length]
            item.lineName = '专用线'
          })
        } else {
          console.log('没有该发站的线路')
          this.$message.error('未匹配到线路,请联系管理员')
          this.getSteelReport()
          return
        }
        let map = {
          userName: getCookie('loginName'),
          sendStationId: row.sendStationId,
          saleOrderId: row.saleOrderId,
          mapList: arr
        }
        console.log('map', map)
        if (!map.saleOrderId || !map.sendStationId || !map.mapList) {
          this.$message.warning('数据异常，请确认已选发站')
          return
        }
        console.log('map:', map)
        const loading = this.$loading({
          lock: true,
          text: '正在派车',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios
          .post('/api/v1/ams/dispatchInwardTruckOrderBySale', map)
          .then(res => {
            if (res.data.code == '200') {
              this.$message({
                message: '派车成功',
                duration: 2000,
                offset: '250px',
                type: 'success'
              })
              this.getSteelReport()
              loading.close()
            } else {
              this.$message({
                message: res.data.data,
                duration: 2000,
                offset: '250px',
                type: 'error'
              })
              this.getSteelReport()
              loading.close()
            }
          })
          .catch(() => {
            this.$message.error('派车失败,请联系管理员')
            this.getSteelReport()
            loading.close()
          })
      }
    },
    //多拼派车
    updateMulCapacity() {
      let i = 0
      if (this.capacityId == null) {
        this.$message.error('请选择车牌号后再派发')
        return
      }
      this.selection.forEach(item => {
        item.isIwardSteel = 4
        item.saleOrderId = item.saleOrderId
        item.saleOrderMaterialId = item.saleOrderMaterialId
        item.capacityNumber = this.capacityNumber
      })
      if (this.selection[0].sendStation == '达州站') {
        this.selection.forEach(item => {
          item.lineId = this.lineDazhou[this.selection.length]
          item.lineName = '达州站'
        })
      } else if (this.selection[0].sendStation == '专用线') {
        this.selection.forEach(item => {
          item.lineId = this.lineZhuanxian[this.selection.length]
          item.lineName = '专用线'
        })
      } else {
        console.log('没有该发站的线路')
        this.$message.error('未匹配到线路,请联系管理员')
        this.getSteelReport()
        return
      }
      let map = {
        userName: getCookie('loginName'),
        sendStationId: this.selection[0].sendStationId,
        saleOrderId: this.selection[0].saleOrderId,
        mapList: this.selection
      }
      console.log('map', map)
      if (!map.saleOrderId || !map.sendStationId || !map.mapList) {
        this.$message.warning('数据异常，请确认已选发站')
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '正在派车',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios
        .post('/api/v1/ams/dispatchInwardTruckOrderBySale', map)
        .then(res => {
          if (res.data.code == '200') {
            this.$message({
              message: '派车成功',
              duration: 2000,
              offset: '250px',
              type: 'success'
            })
            this.getSteelReport()
            loading.close()
            this.capacityId = null
            this.dialogTableVisible = false
          } else {
            this.$message({
              message: res.data.data,
              duration: 2000,
              offset: '250px',
              type: 'error'
            })
            this.getSteelReport()
            loading.close()
            this.capacityId = null
            this.dialogTableVisible = false
          }
        })
        .catch(() => {
          this.$message.error('派车失败,请联系管理员')
          this.getSteelReport()
          loading.close()
          this.capacityId = null
          this.dialogTableVisible = false
        })
    },

    //修改司机电话号码
    updateDriverTel(row) {
      const loading = this.$loading({
        lock: true,
        text: '修改电话号码中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (row.capacityTel == null || row.capacityTel == '') {
        this.$message.error('电话号码不能为空')
        loading.close()
        return
      }
      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()
            loading.close()
          } else {
            this.$message.error('修改失败')
            this.getSteelReport()
            loading.close()
          }
        })
        .catch(() => {
          this.$message.error('修改失败')
          this.getSteelReport()
          loading.close()
        })
    },
    //关闭车辆金蝶分录
    deleteEasEntryId(row) {
      this.$confirm('确定关闭该车金蝶分录吗?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        center: true,
        type: 'warning'
      })
        .then(() => {
          let map = row
          map.isCloseEas = Number(0)
          const loading = this.$loading({
            lock: true,
            text: '正在关闭车辆',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.axios
            .post('/api/v1/ams/updateCarAddress', map)
            .then(res => {
              if (res.data.code == '200') {
                this.$message.success('关闭车辆成功')
                this.getSteelReport()
                loading.close()
              } else {
                this.$message.error('关闭车辆失败')
                this.getSteelReport()
                loading.close()
              }
            })
            .catch(() => {
              this.$message.error('关闭车辆失败')
              this.getSteelReport()
              loading.close()
            })
        })
        .catch(() => {
          this.$message.info('取消关闭')
        })
    },
    //修改承运商授权
    updateTruckCarrier(row) {
      if (row.newCarrierId == null) {
        this.$message.warning('请注册承运商或者选中弹出层之后再提交!')
        this.getSteelReport()
        return
      }
      console.log('carrierIdRow:', row)
      if (row.carrierIds != 0) {
        const loading = this.$loading({
          lock: true,
          text: '正在修改承运商授权',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios
          .post('/api/v1/ams/updateTruckNoCarrier', row)
          .then(res => {
            if (res.data.code == '200') {
              this.$message.success('修改承运商授权成功')
              this.getSteelReport()
              loading.close()
            } else {
              this.$message.error('修改失败,请联系管理员!')
              this.getSteelReport()
              loading.close()
            }
          })
          .catch(() => {
            this.$message.error('修改失败,请联系管理员!')
            this.getSteelReport()
            loading.close()
          })
      } else {
        //授权承运商
        let arr = []
        arr.push(row)
        const loading = this.$loading({
          lock: true,
          text: '正在授权承运商',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios
          .post('/api/v1/ams/dispatchToCarrier', arr)
          .then(res => {
            if (res.data.code == '0') {
              this.$message.success('授权承运商成功')
              this.getSteelReport()
              loading.close()
            } else {
              this.$message.error('授权失败,请联系管理员')
              this.getSteelReport()
              loading.close()
            }
          })
          .catch(() => {
            this.$message.error('授权失败,请联系管理员')
            this.getSteelReport()
            loading.close()
          })
      }
    },

    //记录每一行的合并数
    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].orderId === data[i - 1].orderId &&
              data[i].orderId != null &&
              data[i - 1].orderId != null) ||
            (data[i].saleOrderMaterialId === data[i - 1].saleOrderMaterialId &&
              data[i].saleOrderMaterialId != null &&
              data[i - 1].saleOrderMaterialId != null)
          ) {
            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
          }
        }
        this.totalCapacity = data[data.length - 1].group + 1
        this.totalNumber = data.reduce(function(prev, item) {
          return prev + item.materialNum
        }, 0)
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.mergeList.includes(column.property)) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // //减少物资件数
    // updateBillOrder(row) {
    //   const loading = this.$loading({
    //     lock: true,
    //     text: "修改物资件数中",
    //     spinner: "el-icon-loading",
    //     background: "rgba(0, 0, 0, 0.7)"
    //   });
    //   let map = {
    //     materialId: row.materialId,
    //     materialNum: row.materialNum
    //   };
    //   let arr = [];
    //   arr.push(map);
    //   let updateMap = {
    //     orderId: row.orderId,
    //     saleOrderId: row.saleOrderId,
    //     saleOrderMaterialId: row.saleOrderMaterialId,
    //     mapList: arr
    //   };
    //   this.axios
    //     .post("/api/v1/oms/updateMaterialMes", updateMap)
    //     .then(res => {
    //       if (res.data.code == "200") {
    //         this.$message.success("修改物资数量成功");
    //         this.getSteelReport();
    //         loading.close();
    //       } else {
    //         this.$message.error("修改物资数量失败,请联系管理员");
    //         this.getSteelReport();
    //         loading.close();
    //       }
    //     })
    //     .catch(() => {
    //       this.$message.error("修改物资数量失败,请联系管理员");
    //       this.getSteelReport();
    //       loading.close();
    //     });
    // },
    //关闭单条分录
    closeEasEntryId(row) {
      console.log(row)
      this.$prompt('确定关闭该条分录吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        inputPlaceholder: '请输入关闭理由'
      })
        .then(({ value }) => {
          if (value != null || value != '') {
            const loading = this.$loading({
              lock: true,
              text: '正在关闭该条分录',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            let map = {
              orderId: row.orderId,
              saleOrderMaterialId: row.saleOrderMaterialId,
              saleMaterialId: row.saleMaterialId,
              reason: value,
              number: row.saleOrderNo,
              closeEntryId: row.closeEntryId
            }
            this.axios
              .post('/api/v1/ams/closeSteelMaterialId', map)
              .then(res => {
                if (res.data.code == '200') {
                  this.$message.success('关闭成功')
                  this.getSteelReport()
                  loading.close()
                } else {
                  this.$message.error('关闭失败,请联系管理员')
                  this.getSteelReport()
                  loading.close()
                }
              })
              .catch(() => {
                this.$message.error('关闭失败,请联系管理员')
                this.getSteelReport()
                loading.close()
              })
          }
        })
        .catch(() => {
          this.$message.info('取消输入')
        })
    },
    //查询，输入查询条件
    onclick() {
      let obj = this.filterMap
      let startTime = null
      let endTime = null
      let consigneeName = null
      let capacityNo = null
      let remark = null
      let sendStation = null
      let materialSpe = null
      let materialName = null
      if (this.startTime && this.endTime) {
        startTime = sjTime(this.startTime)
        endTime = sjTime(this.endTime)
      }
      if (this.screen == '收货单位') {
        consigneeName = this.input
      } else if (this.screen == '车牌号') {
        capacityNo = this.input
      } else if (this.screen == '发站') {
        sendStation = this.input
        obj.sendStation = sendStation
      } else if (this.screen == '规格型号') {
        materialSpe = this.input
        obj.materialSpe = materialSpe
      } else if (this.screen == '物资名称') {
        materialName = this.input
        obj.materialName = materialName
      } else {
        remark = this.input
      }
      if (this.screen1 == '收货单位') {
        consigneeName = this.input1
      } else if (this.screen1 == '车牌号') {
        capacityNo = this.input1
      } else if (this.screen1 == '发站') {
        sendStation = this.input1
        obj.sendStation = sendStation
      } else if (this.screen1 == '规格型号') {
        materialSpe = this.input1
        obj.materialSpe = materialSpe
      } else if (this.screen1 == '物资名称') {
        materialName = this.input1
        obj.materialName = materialName
      } else {
        remark = this.input1
      }
      this.axios
        .post(
          '/api/v1/tms/getInwardSaleSteelOrder?startTime=' +
            startTime +
            '&endTime=' +
            endTime +
            '&i=' +
            new Date() +
            '&remark=' +
            remark +
            '&consigneeName=' +
            consigneeName +
            '&capacityNo=' +
            capacityNo,
          obj
        )
        .then(res => {
          this.tableData = res.data.data
          this.getSpanArr(res.data.data)
        })
    },
    //重新获取表格数据
    refresh() {
      this.filterMap = {}
      this.getSteelReport()
    },
    //获取钢材订单报表
    getSteelReport() {
      let startTime = null
      let endTime = null

      if (this.startTime && this.endTime) {
        startTime = sjTime(this.startTime)
        endTime = sjTime(this.endTime)
      }
      this.axios
        .post(
          '/api/v1/tms/getInwardSaleSteelOrder?startTime=' +
            startTime +
            '&endTime=' +
            endTime +
            '&i=' +
            new Date()
        )
        .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'
    },
    //多拼弹出层
    showDialog() {
      let selection = this.$refs.tableRef.selection
      console.log('selection', selection)
      if (selection && selection.length > 0) {
        if (
          selection.find(
            item =>
              item.lineId != selection[0].lineId ||
              item.saleOrderId != selection[0].saleOrderId ||
              item.sendStation != selection[0].sendStation
          )
        ) {
          this.$message({
            message: '无法生成多拼，订单或者线路不一致',
            type: 'warning'
          })
          return
        } else if (!selection[0].sendStationId) {
          this.$message({
            message: '无法生成多拼，请先选择发站',
            type: 'warning'
          })
          return
        }
        this.dialogTableVisible = true
        this.selection = selection
        this.capacityNo = selection[0].capacityNo
      } else {
        this.$message({
          message: '请先勾选再生成多拼',
          type: 'warning'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.purchasFuelNewMonitor {
  .tableTop {
    margin-left: 20px;
    margin-top: 20px;
  }
  .table {
    margin-left: 20px;
    margin-top: 20px;
  }
  .address {
    .button-box {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
