<template>
  <div>
    <el-form ref="form" :model="form">

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="form.datasource"
        :needPage="false"
        :toolkit="[]"
        :minHeight="100"
        tool-class="ele-toolbar-form"
        cache-key="eomContactPageTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            v-if="dialogType!=='view'"
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handleAddInfo">
            新增任务
          </el-button>
        </template>

        <template v-slot:action="{row,$index}" v-if="dialogType!=='view'">
          <el-popconfirm
            class="ele-action"
            title="确定要删除此信息吗？"
            @confirm="handleDelInfo($index)">
            <template v-slot:reference>
              <el-link
                type="danger"
                :underline="false"
                icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
        <template v-slot:trakNumber="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.trakNumber'"
                        :rules="{required:true,message:'请选择车辆',trigger:['blur','change']}">
            <el-input v-model="row.trakNumber" @click.native="handleCar(row,$index)"></el-input>
          </el-form-item>

        </template>
        <template v-slot:driverName="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.driverName'"
                        :rules="{required:true,message:'请选择司机',trigger:['blur','change']}">
            <el-input v-model="row.driverName" @click.native="()=>handleDriver(row,$index)"></el-input>
          </el-form-item>

        </template>
        <template v-slot:phone="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.phone'"
                        :rules="{required:true,message:'请输入司机电话',trigger:['blur','change']}">
            <el-input v-model="row.phone"></el-input>
          </el-form-item>

        </template>
        <template v-slot:startPlace="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.startPlace'"
                        :rules="{required:true,message:'请输入出发地',trigger:['blur','change']}">
            <el-input v-model="row.startPlace"></el-input>
          </el-form-item>

        </template>
        <template v-slot:endPlace="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.endPlace'"
                        :rules="{required:true,message:'请输入目的地',trigger:['blur','change']}">
            <el-input v-model="row.endPlace"></el-input>
          </el-form-item>
        </template>
        <template v-slot:planTimeStart="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.planTimeStart'"
                        :rules="{required:true,message:'请选择发车时间',trigger:['blur','change']}">
            <el-date-picker
              v-model="row.planTimeStart"
              :picker-options="{disabledDate:(time)=>{return row.planTimeEnd&&time.getTime()>new Date(row.planTimeEnd)}}"
              type="datetime"
              @change="()=>handleCheckCarOrDriverIsBusy(row)"
              style="width: 90%"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </template>
        <template v-slot:planTimeEnd="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.planTimeEnd'"
                        :rules="{required:true,message:'请选择结束时间',trigger:['blur','change']}">
            <el-date-picker
              v-model="row.planTimeEnd"
              :picker-options="{disabledDate:(time)=>{return row.planTimeStart&&time.getTime()<new Date(row.planTimeStart)}}"
              type="datetime"
              @change="()=>handleCheckCarOrDriverIsBusy(row)"
              style="width: 90%"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </template>
        <template v-slot:remark="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.remark'">
            <el-input type="textarea" v-model="row.remark"></el-input>
          </el-form-item>
        </template>
        <template v-slot:taskType="{row,$index}">
          <el-form-item :prop="'datasource.'+$index+'.taskType'"
                        :rules="{required:true,message:'请选择任务类型',trigger:['blur','change']}">
            <DictSelection clearable dictName="派车任务类型" v-model="row.taskType"
                           :disabled="dialogType==='view'"
                           @itemChange="(val)=>handleChangeFinLink(val,row,$index)"></DictSelection>
          </el-form-item>
        </template>
        <template v-slot:taskCode="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.taskCode'"
                        :rules="{required:true,message:'请选择',trigger:['blur','change']}">
            <el-input v-model="row.taskCode" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
        </template>
        <template v-slot:headerGLLXMC="{column}">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>
    <!--  销售发货单  -->
    <sendListDialog
      ref="sendListDialogRef"
      @changeParent="changeOrder"
    ></sendListDialog>
    <!-- 委外发货单   -->
    <out-source-send-dialog :out-source-send-dialog-flag.sync="outSourceSendDialogFlag" v-if="outSourceSendDialogFlag"
                            ref="outSourceSendDialogRef"
                            @changeParent="getOutSourceInfo"></out-source-send-dialog>
    <!--  采购收货单  -->
    <purchaseReceivingGoodsDialog
      ref="purchaseReceivingGoodsRef"
      @changeParent="getPurchaseReceivingGoodsInfo"
    ></purchaseReceivingGoodsDialog>
    <!--  受托发货单  -->
    <entrusted-receive-dialog :entrusted-receive-dialog-flag.sync="entrustedReceiveDialogFlag"
                              v-if="entrustedReceiveDialogFlag"
                              @changeParent="getEntrustedReceiveInfo"
                              ref="entrustedReceiveDialogRef"></entrusted-receive-dialog>
    <!-- 销售退货   -->
    <return-order-dialog :returnOrderDialogFlag.sync="returnOrderDialogFlag" v-if="returnOrderDialogFlag"
                         @changeParent="getSReturnOrderInfo" ref="returnOrderDialogRef">
    </return-order-dialog>
    <!-- 采购退货   -->
    <purchase-return-order-dialog :purchaseReturnOrderDialogFlag.sync="purchaseReturnOrderDialogFlag"
                                  v-if="purchaseReturnOrderDialogFlag"
                                  @changeParent="getPReturnOrderInfo"
                                  ref="returnOrderDialogRef"></purchase-return-order-dialog>
    <!-- 选择司机   -->
    <select-driver-dialog ref="selectDriverDialogRef" :selectDriverDialogFlag.sync="selectDriverDialogFlag"
                          v-if="selectDriverDialogFlag" @changeParent="getDriverInfo"></select-driver-dialog>
    <select-car-dialog ref="selectCarDialogRef" :selectCarDialogFlag.sync="selectCarDialogFlag"
                       v-if="selectCarDialogFlag" @changeParent="getCarInfo"></select-car-dialog>
  </div>
</template>


<script>
import selectCarDialog from "./selectCarDialog.vue";
import selectDriverDialog from "./selectDriverDialog.vue";
import sendListDialog from "@/views/saleManage/saleOrder/returnGoods/components/sendListDialog.vue";
import outSourceSendDialog from "@/views/purchasingManage/purchaseOrder/invoice/components/outSourceSendDialog.vue";
import purchaseReceivingGoodsDialog
  from "@/views/purchasingManage/purchaseOrder/returnGoods/components/sendListDialog.vue";
import entrustedReceiveDialog from "@/views/saleManage/saleOrder/invoice/components/entrustedReceiveDialog.vue";
import returnOrderDialog from "@/views/saleManage/saleOrder/customerReturnOrder/returnOrderDialog.vue";
import purchaseReturnOrderDialog from "./purchaseReturnOrderDialog.vue";
import {checkDriverIsBusyAPI} from "@/api/transportManager/shipManage";

export default {
  name: "relatedInfoTable",
  components: {
    returnOrderDialog,
    entrustedReceiveDialog,
    outSourceSendDialog,
    sendListDialog,
    purchaseReceivingGoodsDialog,
    purchaseReturnOrderDialog,
    selectCarDialog,
    selectDriverDialog,
  },
  props: {
    trakNoteList: {
      type: Array,
      default: () => []
    },
    dialogType: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      editIndex: undefined,//当前修改数据的下标
      selectCarDialogFlag: false,
      selectDriverDialogFlag: false,
      outSourceSendDialogFlag: false,
      entrustedReceiveDialogFlag: false,
      returnOrderDialogFlag: false,
      purchaseReturnOrderDialogFlag: false,
      form: {
        datasource: []
      },

    }
  },
  computed: {
    columns() {
      let list = [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'trakNumber',
          label: '车牌号',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'trakNumber',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'startPlace',
          label: '出发地',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'startPlace',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'endPlace',
          label: '目的地',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'endPlace',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'planTimeStart',
          label: '预计发车日期',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 240,
          slot: 'planTimeStart',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'planTimeEnd',
          label: '预计结束日期',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 240,
          slot: 'planTimeEnd',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'driverName',
          label: '司机',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'driverName',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'phone',
          label: '司机电话',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'phone',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'taskType',
          label: '任务类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'taskType',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'taskCode',
          label: '单据名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130,
          slot: 'taskCode',
          headerSlot: 'headerGLLXMC'
        },
        {
          prop: 'remark',
          label: '备注',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'remark',
        },
      ]
      let action = [{
        columnKey: 'action',
        slot: 'action',
        label: '操作',
        resizable: false,
        width: 80,
        align: 'center',
        showOverflowTooltip: true,
        fixed: 'right'
      },]
      this.dialogType === 'view' ? list = [...list] : list = [...list, ...action]
      return list
    },
  },
  mounted() {

    this.form.datasource = this.trakNoteList
    console.log(this.form.datasource);
  },
  methods: {
    //新增任务信息数据
    handleAddInfo() {
      this.form.datasource.push(
        {
          driverId: '',
          driverName: "",
          endPlace: "",
          phone: "",
          planId: '',
          planTimeEnd: "",
          planTimeStart: "",
          realEntTime: "",
          realStartTime: "",
          remark: "",
          startPlace: "",
          trakId: '',
          trakNumber: "",
          taskId: "",
          taskType: "",
          taskCode: ""
        }
      )
    },
    //
    handleSelectData(val, row, index) {
      this.editIndex = index
      if (val.target.nodeName == 'I') {
        row.taskId = ''
        row.taskCode = ''
        return
      }
      switch (row.taskType) {
        case '1': //销售发货
          this.handleOrderBtn(row);
          break;
        case '2': //委外发货
          this.handleOutsourceSend(row);
          break
        case '3': //采购收货
          this.handlePurchaseReceivingGoods(row);
          break
        case '4': //受托发货
          this.handleEntrustedReceive(row);
          break;
        case '5': //销售退货
          this.handleSaleReturnOrder(row);
          break;
        case '6': //采购退货
          this.handlePurchaseReturnOrder(row);
          break
      }
    },
    setSelectData(val) {
      this.$set(this.form.datasource[this.editIndex], 'taskId', val.id)
      this.$set(this.form.datasource[this.editIndex], 'taskCode', val.code)
    },
    //删除任务信息数据
    handleDelInfo(index) {
      this.form.datasource.splice(index, 1)
    },
    //修改任务类型
    handleChangeFinLink(val, row, index) {
      this.editIndex = index
      this.setSelectData({
        id: '',
        code: ''
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate('datasource.' + index + '.taskCode')
      })
    },

    //选择发货单
    handleOrderBtn() {
      this.$refs.sendListDialogRef.open();
    },
    //选择发货单回调
    changeOrder(params) {
      let row = {
        id: params.id,
        code: params.docNo
      }
      this.setSelectData(row)
    },
    //选择采购收货单
    handlePurchaseReceivingGoods() {
      this.$refs.purchaseReceivingGoodsRef.open();
    },
    //选择采购收货单回调
    getPurchaseReceivingGoodsInfo(params) {
      let row = {
        id: params.id,
        code: params.receiveNo
      }
      this.setSelectData(row)
    },

    //选择委外发货单弹框
    handleOutsourceSend() {
      this.outSourceSendDialogFlag = true
      this.$nextTick(() => {
        this.$refs.outSourceSendDialogRef.init();
      })
    },
    //选择委外发货单回调
    getOutSourceInfo(params) {
      let row = {
        id: params.id,
        code: params.code
      }
      this.setSelectData(row)
    },
    //选择受托收货单弹框
    handleEntrustedReceive(e) {
      this.entrustedReceiveDialogFlag = true
      this.$nextTick(() => {
        this.$refs.entrustedReceiveDialogRef.init();
      })
    },
    //获取受托收货单数据回调
    async getEntrustedReceiveInfo(params) {
      let row = {
        id: params.id,
        code: params.code
      }
      this.setSelectData(row)
    },
    //选择销售退货单
    handleSaleReturnOrder() {
      this.returnOrderDialogFlag = true
      // this.$nextTick(() => {
      //   this.$refs.returnOrderDialogRef.init()
      // })
    },
    //销售退货单回调
    getSReturnOrderInfo(params) {
      let row = {
        id: params.id,
        code: params.returnNo
      }
      this.setSelectData(row)
    },
    //选择采购退货单
    handlePurchaseReturnOrder() {
      this.purchaseReturnOrderDialogFlag = true
    },
    //采购退货单回调
    getPReturnOrderInfo(params) {
      let row = {
        id: params.id,
        code: params.returnNo
      }
      this.setSelectData(row)
    },

    //选择司机
    handleDriver(row, index) {
      this.editIndex = index
      this.selectDriverDialogFlag = true
    },
    //选择司机回调
    getDriverInfo(row) {
      this.$set(this.form.datasource[this.editIndex], 'driverId', row.driverId)
      this.$set(this.form.datasource[this.editIndex], 'driverName', row.driverName)
      this.$set(this.form.datasource[this.editIndex], 'phone', row.phone)

      this.handleCheckCarOrDriverIsBusy(this.form.datasource[this.editIndex])
    },
    //选择车辆
    handleCar(row, index) {
      this.editIndex = index
      this.selectCarDialogFlag = true
    },
    //选择车辆回调
    getCarInfo(row) {
      this.$set(this.form.datasource[this.editIndex], 'driverId', row.defaultDriverId)
      this.$set(this.form.datasource[this.editIndex], 'driverName', row.defaultDriver)
      this.$set(this.form.datasource[this.editIndex], 'phone', row.phone)
      this.$set(this.form.datasource[this.editIndex], 'trakNumber', row.trakNumber)
      this.$set(this.form.datasource[this.editIndex], 'trakId', row.id)

      this.handleCheckCarOrDriverIsBusy(this.form.datasource[this.editIndex])

    },
    //检查车辆或司机是否在运输中
    async handleCheckCarOrDriverIsBusy(row) {
      if ((row.driverName || row.trakNumber) && row.planTimeStart && row.planTimeEnd) {
        let data = await checkDriverIsBusyAPI(row)
        console.log(data);
        if (data.code == 1) {
          this.$message.warning(data.message)
        }
      }

    },
    getTableValidate() {
      return new Promise((resolve, reject) => {
        if (this.form.datasource.length == 0) return this.$message.warning('请填写任务信息')
        this.$refs.form.validate((valid) => {
          if (!valid) return this.$message.warning('请填写完整信息')
          resolve(this.form.datasource)
        })
      })
    },
  }
}
</script>


<style scoped lang="scss">
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
