// 定向派单接单
<template>
  <div class="openDistribution">
    <div class="top">
      <el-form inline>
        <el-form-item>
          <el-select
            v-model="condition1"
            placeholder="请选择筛选条件"
            style="width:150px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入内容"
            v-model="input1"
            style="width:200px"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="condition2"
            placeholder="请选择筛选条件"
            style="width:150px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入内容"
            v-model="input2"
            style="width:200px"
            clearable
          >
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="elDivider">
      <el-divider></el-divider>
    </div>
    <div class="buttonModel">
      <div class="operation">
        <el-button v-if="activeName == 'second'" type="danger" @click="refuse">
          批量拒绝订单
        </el-button>
        <el-button
          v-if="activeName == 'five'"
          type="primary"
          @click="batchCloseOrderReceived"
        >
          <i></i>批量关闭订单
        </el-button>
      </div>
      <div class="search">
        <el-button type="primary" class="btn" @click="onclick1">
          <i class="el-icon-search"></i>查询
        </el-button>
      </div>
    </div>
    <div class="table">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="未派单" name="second">
          <dilTable
            v-bind.sync="second"
            ref="table1"
            @selection-change="currentSelectChange1"
            max-height="550"
            :pageSize="20"
          >
            <el-table-column fixed="right" label="操作" width="120">
              <template slot-scope="scope">
                <el-button @click="dispatch(scope)" type="text" size="small">
                  派单
                </el-button>
                <el-button
                  @click="detailclick1(scope.row)"
                  type="text"
                  size="small"
                >
                  物资详情
                </el-button>
              </template>
            </el-table-column>

            <!-- 物资详情抽屉 -->
            <el-table-column type="expand" width="1">
              <template slot-scope="props">
                <el-form
                  label-position="center"
                  inline
                  class="demo-table-expand"
                >
                  <div v-if="false">{{ props }}</div>
                  <div>
                    <el-table :data="tableData1" border>
                      <el-table-column
                        v-for="(item, i) in tableHead"
                        :key="i"
                        :prop="item.prop"
                        :label="item.label"
                        :width="item.width"
                      ></el-table-column>
                    </el-table>
                  </div>
                </el-form>
              </template>
            </el-table-column>
          </dilTable>
        </el-tab-pane>
        <el-tab-pane label="已派单" name="five">
          <dilTable
            v-bind.sync="five"
            ref="table2"
            @selection-change="currentSelectChange2"
            max-height="550"
            :pageSize="20"
          >
            <el-table-column fixed="right" label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  @click="updateCapacity(scope.row)"
                  type="text"
                  size="small"
                  v-if="scope.row.transOrderStatus == '已派单'"
                >
                  修改运力
                </el-button>
                <el-button
                  @click="detailclick1(scope.row)"
                  type="text"
                  size="small"
                >
                  物资详情
                </el-button>
                <el-button
                  @click="closeOrder(scope.row)"
                  type="text"
                  size="small"
                  v-if="scope.row.transOrderStatus == '已派单'"
                >
                  关闭订单
                </el-button>
              </template>
            </el-table-column>

            <!-- 物资详情抽屉 -->
            <el-table-column type="expand" width="1">
              <template slot-scope="props">
                <el-form
                  label-position="center"
                  inline
                  class="demo-table-expand"
                >
                  <div v-if="false">{{ props }}</div>
                  <div>
                    <el-table :data="tableData1" border>
                      <el-table-column
                        v-for="(item, i) in tableHead"
                        :key="i"
                        :prop="item.prop"
                        :label="item.label"
                        :width="item.width"
                      ></el-table-column>
                    </el-table>
                  </div>
                </el-form>
              </template>
            </el-table-column>
          </dilTable>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog title="车辆信息" :visible.sync="dialogTableVisible">
      <el-input
        placeholder="请输入内容"
        v-model="inputTruck"
        clearable
        style="width: 200px"
      >
      </el-input>
      <el-button type="primary" class="btn" @click="onClickTruck">
        <i class="el-icon-search"></i>查询
      </el-button>
      <dilTable v-bind.sync="truck" @radio-change="currentRadioChange1">
      </dilTable>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateTruckCapacity">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCookie } from '@/utils/util.js'
export default {
  data() {
    return {
      inputTruck: '',
      dialogTableVisible: false,
      condition1: null,
      condition2: null,
      input1: null,
      input2: null,
      startTime: null,
      endTime: null,
      options: [
        {
          label: '收货单位',
          value: 'consigneeCompanyName'
        },
        {
          label: '物资名称',
          value: 'materialName'
        },
        {
          label: '备注',
          value: 'saleRemark'
        },
        {
          label: '车牌号',
          value: 'capacityNumber'
        }
      ],
      drawer: false,
      ssoId: null,
      direction: 'rtl',
      activeName: 'second',
      inputText: '',
      dispatchId: null,
      input: '',
      //所有选中的车序号订单
      selectTruckOrder: [],
      second: {
        requestUrl: '',
        selectionType: 'select'
      },
      five: {
        requestUrl: '',
        selectionType: 'select',
        mapList1: []
      },
      closeList: [],
      //记录旧的row对象(未接收)
      oldRow: '',
      //记录上一个展开的点击次数，单数为展开状态，复数为闭合状态(未接收)
      oldRowCount: 1,
      //记录旧的row对象(已接收)
      oldRow1: '',
      //记录上一个展开的点击次数，单数为展开状态，复数为闭合状态(已接收)
      oldRowCount1: 1,
      tableHead: [
        {
          prop: 'materialName',
          label: '物资名称',
          width: 150
        },
        {
          prop: 'specificationModel',
          label: '规格型号',
          width: 150
        },
        {
          prop: 'materialNumber',
          label: '物资件数',
          width: 100
        },
        {
          prop: 'materialWeight',
          label: '物资重量',
          width: 100
        }
      ],
      tableData: [],
      tableData1: [],
      truck: {
        requestUrl: '',
        selectionType: 'radio'
      }
    }
  },
  created() {
    this.fiveGetRequestUrl()
    this.secondGetRequestUrl()
  },
  activated() {
    this.fiveGetRequestUrl()
    this.secondGetRequestUrl()
  },
  methods: {
    onClickTruck() {
      if (getCookie('orgCode') == 'chengyunshang') {
        this.truck.requestUrl =
          '/api/v1/uc/getAllCapacityByCarrierLike?apiId=248&carrierSsoId=' +
          getCookie('userId') +
          '&index=' +
          this.inputTruck
      } else {
        this.truck.requestUrl =
          '/api/v1/uc/getAllCapacityByCarrierLike?apiId=248&carrierSsoId=' +
          null +
          '&index=' +
          this.inputTruck
      }
    },
    getRequestUrl() {
      this.fiveGetRequestUrl()
      this.secondGetRequestUrl()
    },
    //关闭选中行的订单
    closeOrder(row) {
      this.$confirm('是否关闭', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          this.axios
            .post('/api/v1/oms/closeOrder?orderId=' + row.orderId)
            .then(res => {
              if (res.data.code == '200') {
                this.getRequestUrl()
                this.$message({
                  type: 'success',
                  message: '关闭成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: '关闭失败!'
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消关闭!'
          })
        })
    },
    updateTruckCapacity() {
      if (this.capacityId == null) {
        this.$message.error('未选中运力')
        return
      }
      this.axios
        .post('/api/v1/oms/updateCapacityId', {
          capacityId: this.capacityId,
          orderId: this.orderId
        })
        .then(res => {
          if (res.data.code == '200') {
            this.$message.success('修改运力成功')
            this.getRequestUrl()
            this.dialogTableVisible = false
          } else {
            this.$message.error('修改运力失败')
          }
        })
    },
    updateCapacity(row) {
      this.getTruckRequestUrl()
      this.orderId = row.orderId
      this.dialogTableVisible = true
    },
    currentRadioChange1(row) {
      console.log(row)
      this.capacityId = row.capacityId
    },
    getTruckRequestUrl() {
      if (getCookie('orgCode') == 'chengyunshang') {
        this.truck.requestUrl =
          '/api/v1/uc/getAllCapacityByCarrierLike?apiId=429&carrierSsoId=' +
          getCookie('userId') +
          '&test=' +
          new Date()
      } else {
        this.truck.requestUrl =
          '/api/v1/uc/getAllCapacityByCarrierLike?apiId=429&carrierSsoId=' +
          null +
          '&test=' +
          new Date()
      }
    },
    currentSelectChange1(selection) {
      this.closeList = selection
    },
    currentSelectChange2(selection) {
      this.five.mapList1 = selection
    },
    batchCloseOrderReceived() {
      if (this.five.mapList1.length == 0) {
        this.$message({
          type: 'warning',
          message: '请先选择要关闭的订单!'
        })
      } else {
        this.$confirm('是否关闭这些订单(出皮无法关闭)', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
          .then(() => {
            //初始化maplist
            var mapList = []
            this.five.mapList1.forEach(item => {
              //初始化mapItem
              let mapItem = {
                //销售订单物资中间表id
                orderId: 0
              }
              mapItem.orderId = item.orderId
              mapList.push(mapItem)
            })
            this.axios
              .post('/api/v1/oms/batchCloseOrder', mapList)
              .then(res => {
                if (res.data.code == '200') {
                  this.getRequestUrl()
                  this.$message({
                    type: 'success',
                    message: '关闭成功!'
                  })
                } else {
                  this.$message({
                    type: 'error',
                    message: '关闭失败!'
                  })
                }
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消关闭!'
            })
          })
      }
    },
    close() {
      this.$confirm('是否将选中的订单批量关闭? 继续?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //请求后端
          this.axios
            .post('/api/v1/ams/refuseDispatchSaleOrderList', this.closeList)
            .then(res => {
              if (res.data.code == 200) {
                this.closeList = []
                this.$message.success('关闭成功')
                this.secondGetRequestUrl()
              } else {
                this.$message.error('关闭失败')
              }
            })
            .catch(() => {
              this.$message.error('关闭失败')
            })
        })
        .catch(() => {
          this.$message.info('取消关闭')
        })
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    fiveGetRequestUrl() {
      let _this = this
      new Promise((resolve, reject) => {
        let option = {
          requestQuery: {},
          selectionType: 'select'
        }
        option.requestQuery[this.condition1] = []
        option.requestQuery[this.condition2] = []
        if (this.condition1 == this.condition2) {
          option.requestQuery[this.condition1] = [this.input1, this.input2]
        } else {
          option.requestQuery[this.condition1] = [this.input1]
          option.requestQuery[this.condition2] = [this.input2]
        }
        if (getCookie('orgCode') == 'chengyunshang') {
          option.requestUrl =
            '/api/v1/oms/getDriverInfoForSale?apiId=226&orderType=2&shipperId=2&carrierSsoId=' +
            getCookie('userId') +
            '&t=' +
            new Date()
        } else {
          option.requestUrl =
            '/api/v1/oms/getDriverInfoForSale?apiId=226&orderType=2&shipperId=2&carrierSsoId=' +
            '' +
            '&t=' +
            new Date()
        }
        resolve(option)
      }).then(option => {
        _this.five = option
      })
    },
    firstGetRequestUrl() {
      let _this = this
      new Promise((resolve, reject) => {
        let option = {
          requestQuery: {},
          selectionType: 'select'
        }
        option.requestQuery[this.condition1] = []
        option.requestQuery[this.condition2] = []
        if (this.condition1 == this.condition2) {
          option.requestQuery[this.condition1] = [this.input1, this.input2]
        } else {
          option.requestQuery[this.condition1] = [this.input1]
          option.requestQuery[this.condition2] = [this.input2]
        }
        if (getCookie('orgCode') == 'chengyunshang') {
          option.requestUrl =
            '/api/v1/ams/getPCDispatchSaleOrderList?apiId=242&dispatchType=0&carrierSsoId=' +
            getCookie('userId')
        } else {
          option.requestUrl =
            '/api/v1/ams/getPCDispatchSaleOrderList?apiId=242&dispatchType=0&carrierSsoId=' +
            this.ssoId
        }
        resolve(option)
      }).then(option => {
        _this.first = option
      })
    },
    secondGetRequestUrl() {
      let _this = this
      new Promise((resolve, reject) => {
        let option = {
          requestQuery: {},
          selectionType: 'select'
        }
        option.requestQuery[this.condition1] = []
        option.requestQuery[this.condition2] = []
        if (this.condition1 == this.condition2) {
          option.requestQuery[this.condition1] = [this.input1, this.input2]
        } else {
          option.requestQuery[this.condition1] = [this.input1]
          option.requestQuery[this.condition2] = [this.input2]
        }
        if (getCookie('orgCode') == 'chengyunshang') {
          option.requestUrl =
            '/api/v1/ams/selectDispatchSaleOrderList?apiId=233&carrierSsoId=' +
            getCookie('userId') +
            '&con=' +
            this.input
        } else {
          option.requestUrl =
            '/api/v1/ams/selectDispatchSaleOrderList?apiId=233&carrierSsoId=' +
            this.ssoId +
            '&con=' +
            this.input
        }
        resolve(option)
      }).then(option => {
        _this.second = option
      })
    },
    onclick1() {
      if (this.activeName == 'five') {
        this.fiveGetRequestUrl()
      } else if (this.activeName == 'second') {
        this.secondGetRequestUrl()
      }
    },
    dispatch(scope) {
      this.dispatchId = scope.row.dispatchId
      this.$router.push('/openDistributionSection/' + scope.row.dispatchId)
    },
    // handleBtnClick1(){
    // 		this.drawer=true
    // 	},
    //车序号订单表格
    currentSelectChange(select) {
      this.selectTruckOrder = []
      this.selectTruckOrder = select
    },
    onclick() {
      this.third.requestUrl =
        '/api/v1/oms/getCapacityAndDriverList?apiId=246&con=' + this.input
    },
    makeSure() {
      this.$confirm('是否派发', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          //初始化承运商SsoId
          var carrierSsoId = ''
          if (getCookie('orgCode') == 'chengyunshang') {
            carrierSsoId = getCookie('userId')
          } else {
            carrierSsoId = null
          }
          this.axios
            .post(
              '/api/v1/oms/addAppTruckOrder?orderType=' +
                1 +
                '&carrierId=' +
                carrierSsoId +
                '&dispatchId=' +
                this.dispatchId +
                '&capacityNumber=' +
                this.mapList.capacityNumber
            )
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '派单成功！'
                })
                this.$router.go(0)
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'warning'
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '派发操作已取消!'
          })
        })
    },

    // -------查看物资详情(未接收)
    detailclick(row) {
      // 记录重复点击次数
      if (this.oldRow === row) {
        this.oldRowCount += 1
      }
      // 切换当前详情表
      this.$refs.table.toggleRowExpansion(row)
      // 打开前关闭上一个详情表
      if (this.oldRow != '') {
        if (this.oldRow != row) {
          if (this.oldRowCount % 2 === 1) {
            this.$refs.table.toggleRowExpansion(this.oldRow)
          } else {
            this.oldRowCount = 1
          }
        } else {
          this.oldRow = null
          return
        }
      }
      // 重置上一个点击对象
      this.oldRow = row
      this.getMaterial(row.dispatchId)
    },
    // 根据销售订单物资中间表id查询物资信息
    getMaterial(dispatchId) {
      this.axios
        .post('/api/v1/ams/getDispatchMaterialList?dispatchId=' + dispatchId)
        .then(res => {
          this.tableData = res.data.data
        })
    },

    // -------查看物资详情(已接收)
    detailclick1(row) {
      // 记录重复点击次数
      if (this.oldRow1 === row) {
        this.oldRowCount1 += 1
      }
      // 切换当前详情表
      this.$refs.table1.toggleRowExpansion(row)
      // 打开前关闭上一个详情表
      if (this.oldRow1 != '') {
        if (this.oldRow1 != row) {
          if (this.oldRowCount1 % 2 === 1) {
            this.$refs.table1.toggleRowExpansion(this.oldRow)
          } else {
            this.oldRowCount1 = 1
          }
        } else {
          this.oldRow1 = null
          return
        }
      }
      // 重置上一个点击对象
      this.oldRow1 = row
      // 根据销售订单物资中间表id查询物资信息
      this.axios
        .post(
          '/api/v1/ams/getDispatchMaterialList?dispatchId=' + row.dispatchId
        )
        .then(res => {
          this.tableData1 = res.data.data
        })
    },

    //接收所有已选中的订单
    receive() {
      this.$confirm('是否接收已选中的订单', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          //初始化承运商SsoId
          var carrierSsoId = ''
          if (getCookie('orgCode') == 'chengyunshang') {
            carrierSsoId = getCookie('userId')
          } else {
            carrierSsoId = null
          }
          //所有选中的分派Id
          var dispatchIdList = []
          this.selectTruckOrder.forEach(item => {
            //初始化mapItem
            var mapItem = {
              //分派Id
              dispatchId: 0
            }
            mapItem.dispatchId = item.dispatchId
            dispatchIdList.push(mapItem)
          })
          //保存承运商SsoId和所有选中的分派Id
          let map = {
            carrierSsoId: carrierSsoId,
            mapList: dispatchIdList
          }
          //请求后端
          this.axios
            .post('/api/v1/ams/lockDispatchSaleOrderList', map)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '接收成功!'
                })
                if (getCookie('orgCode') == 'chengyunshang') {
                  // this.first.requestUrl =
                  //   '/api/v1/ams/getPCDispatchSaleOrderList?apiId=242&dispatchType=0&carrierSsoId=' +
                  //   getCookie('userId') +
                  //   '&i=' +
                  //   new Date()
                } else {
                  // this.first.requestUrl =
                  //   '/api/v1/ams/getPCDispatchSaleOrderList?apiId=242&dispatchType=0&carrierSsoId=' +
                  //   this.ssoId +
                  //   '&i=' +
                  //   new Date()
                }
              } else {
                this.$message({
                  message: '接单失败,请联系管理员!',
                  type: 'warning'
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '接单操作已取消!'
          })
        })
    },
    //拒绝所有已选中的订单
    refuse() {
      this.$confirm('是否拒绝已选中的订单', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          //所有选中的分派Id
          var mapList = []
          this.closeList.forEach(item => {
            //初始化mapItem
            var mapItem = {
              //分派Id
              dispatchId: 0
            }
            mapItem.dispatchId = item.dispatchId
            mapList.push(mapItem)
          })
          //请求后端
          this.axios
            .post('/api/v1/ams/refuseDispatchSaleOrderList', mapList)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '拒绝成功!'
                })
                this.secondGetRequestUrl()
              } else {
                this.$message({
                  message: '拒绝失败,请联系管理员!',
                  type: 'error'
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '拒绝操作已取消!'
          })
        })
    }
  }
}
</script>

<style lang="scss" scode>
.openDistribution {
  .top {
    margin-top: 10px;
    margin-left: 10px;
  }
  .buttonModel {
    margin-top: 5px;

    display: flex;
    justify-content: space-between;
    align-items: center;
    .operation {
      margin-left: 10px;
    }
    .search {
      margin-right: 10px;
    }
  }
  .table {
    margin-left: 10px;
    margin-top: 5px;
  }
}
</style>
