<template>
  <div>
    <el-form ref="form" :model="form">
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="form.datasource"
        :needPage="false"
        :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: false,
              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: false,
              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: false,
              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: false,
              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: false,
              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: false,
              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: false,
              message: '请选择任务类型',
              trigger: ['blur', 'change']
            }"
          >
            <DictSelection
              clearable
              dictName="派车任务类型"
              v-model="row.taskType"
              :disabled="dialogType === 'view'"
              disabled
              @itemChange="(val) => handleChangeFinLink(val, row, $index)"
            ></DictSelection>
          </el-form-item>
        </template>
        <template v-slot:headerGLLXMC="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>

    <!-- 选择司机   -->
    <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 { checkDriverIsBusyAPI } from '@/api/transportManager/shipManage';
  import SelectDriverDialog from '@/views/transportManager/shipManage/dispatchManage/components/selectDriverDialog.vue';
  import SelectCarDialog from '@/views/transportManager/shipManage/dispatchManage/components/selectCarDialog.vue';
  import { getWarehouseOutStock } from '@/api/saleManage/saleorder';

  export default {
    name: 'relatedInfoTable',
    components: { SelectCarDialog, SelectDriverDialog },
    props: {
      trakNoteList: {
        type: Array,
        default: () => []
      },
      dialogType: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        editIndex: undefined, //当前修改数据的下标
        selectDriverDialogFlag: false,
        selectCarDialogFlag: 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
          },
          {
            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: '1',
          taskCode: ''
        });
        this.$emit('setAddress')
      },
      setSelectData(val) {
        this.$set(this.form.datasource[this.editIndex], 'taskId', val.id);
        this.$set(this.form.datasource[this.editIndex], 'taskCode', val.code);
      },
      setAddress(startPlace, endPlace) {
        this.form.datasource.forEach((item) => {
          item.startPlace = startPlace;
          item.endPlace = endPlace;
        });
      },
      //删除任务信息数据
      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');
        });
      },
      //选择司机
      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);
          }
        }
      },
      //修改回显
      putTableValue(data) {
        if (data) {
          this.form.datasource = data;
        }
      },
      getTableValue() {
        return this.form.datasource;
      },
      getTableValidate(callback) {
        this.$refs.form.validate((valid) => {
          callback(valid);
        });
      }
    }
  };
</script>

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