<template>
  <div class="app-container">

    <el-tabs v-model="activeName" @tab-click="handleChange">
      <el-tab-pane label="未提交" :name="SubmitState.WILL_SUBMIT"></el-tab-pane>
      <el-tab-pane label="已提交" :name="SubmitState.HAS_SUBMIT"></el-tab-pane>
    </el-tabs>
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input v-model="queryForm.licensePlate" @keyup.enter.native="handleQuery"
                  placeholder="请输入车牌号"></el-input>
      </el-form-item>
      <el-form-item label="用车类型" prop="vehicleType">
        <el-select v-model="queryForm.vehicleType" style="width: 100%" placeholder="请选择用车类型">
          <el-option
            v-for="dict in dict.type.vehicle_types"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="司机" prop="driver">
        <el-input v-model="queryForm.driver" @keyup.enter.native="handleQuery" placeholder="请输入司机名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-show="activeName === SubmitState.WILL_SUBMIT"
          v-hasPermi="['system:application:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          icon="el-icon-search"
          :disabled="single"
          v-show="activeName === SubmitState.WILL_SUBMIT"
          @click="openTableData"
        >详情
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-show="activeName === SubmitState.WILL_SUBMIT"
          v-hasPermi="['system:application:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-show="activeName === SubmitState.WILL_SUBMIT"
          v-hasPermi="['system:application:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:application:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>-->
    </el-row>

    <el-table
      stripe
      ref="applyTable"
      v-loading="loading"
      :data="infoList"
      :cell-style="cellStyle"
      @selection-change="handleSelectionChange">
      <el-table-column key="selection" fixed type="selection" width="55" align="center"/>
      <el-table-column
        label="申请人"
        align="center"
        key="applicantName"
        v-if="columns[1].visible && activeName !== SubmitState.WILL_SUBMIT"
        prop="applicantName">
      </el-table-column>
      <el-table-column
        label="车牌号"
        key="licensePlate"
        align="center"
        width="120px"
        v-if="columns[2].visible"
        prop="licensePlate">
      </el-table-column>
      <el-table-column
        label="人数"
        align="center"
        key="peopleNumber"
        v-if="columns[2].visible"
        prop="peopleNumber">
      </el-table-column>
      <el-table-column
        label="出发地点"
        align="center"
        key="departurePlace"
        v-if="columns[3].visible"
        prop="departurePlace"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        label="目的地"
        align="center"
        key="destination"
        v-if="columns[4].visible"
        prop="destination"
        show-overflow-tooltip/>
      <el-table-column
        label="用车开始时间"
        align="center"
        v-if="columns[5].visible"
        prop="startTime"
        key="startTime"
        min-width="100%"
        show-overflow-tooltip/>
      <el-table-column
        label="用车结束时间"
        align="center"
        v-if="columns[6].visible"
        prop="endTime"
        key="endTime"
        min-width="100%"
        show-overflow-tooltip/>
      <el-table-column
        label="司机"
        align="center"
        key="driver"
        v-if="columns[7].visible"
        prop="driver"
        show-overflow-tooltip/>
      <el-table-column
        label="用车类型"
        align="center"
        key="vehicleType"
        v-if="columns[8].visible"
        prop="vehicleType"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.vehicle_types" :value="scope.row.vehicleType"/>
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        align="center"
        v-if="columns[10].visible && activeName !== SubmitState.WILL_SUBMIT"
        prop="applyTime"
        key="applyTime"
        min-width="100%"
        show-overflow-tooltip/>
      <el-table-column
        width="100"
        label="公里数(km)"
        align="center"
        v-if="columns[11].visible"
        prop="kilometers"
        key="kilometers"
        show-overflow-tooltip/>
      <el-table-column
        :width="queryForm.submitState ? 100 : 250"
        label="操作"
        align="center"
        v-if="columns[12].visible"
        fixed="right"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div v-if="queryForm.submitState">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-search"
              @click="handleDetail(scope.row)"
            >查看
            </el-button>
          </div>
          <div v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="submitApply(scope.row)"
              v-hasPermi="['system:application:edit']"
            >提交申请
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:application:remove']"
            >修改
            </el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:application:remove']"
            >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增用车申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="cancel">
      <el-form ref="postForm" :model="postForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <div style="margin: 0 30px 0 0">
              <el-form-item label="车辆" prop="licensePlate">
                <el-input
                  v-model="postForm.licensePlate"
                  placeholder="请选择车辆"
                  @focus="selectChange"
                  :disabled="isDisabled"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
              <el-form-item label="用车部门" prop="departmentId">
                <treeselect
                  v-model="postForm.departmentId"
                  :options="deptOptions"
                  :disabled="isDisabled"
                  :show-count="true"
                  :readonly="readonly"
                  disable-branch-nodes
                  :defaultExpandLevel="1"
                  placeholder="请选择用车部门"/>
              </el-form-item>
              <el-form-item label="用车开始时间" prop="startTime">
                <el-date-picker
                  v-model="postForm.startTime"
                  type="date"
                  value-format="yyyy-MM-dd"

                  :readonly="readonly"
                  style="width: 100%"
                  placeholder="请选择日期">
                </el-date-picker>
                <!--                :picker-options="limitStart"-->
              </el-form-item>
              <el-form-item label="出发地点" prop="departurePlace">
                <el-input v-model="postForm.departurePlace" :readonly="readonly"
                          placeholder="请输入出发地点"></el-input>
              </el-form-item>
              <el-form-item label="司机姓名" prop="driver">
                <el-input v-model.trim="postForm.driver" :readonly="readonly" placeholder="请输入司机姓名"></el-input>
              </el-form-item>
              <el-form-item label="公里数" prop="kilometers">
                <el-input v-model="postForm.kilometers" :readonly="readonly" placeholder="请输入公里数">
                  <template slot="append"><span>km</span></template>
                </el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用车类型" prop="vehicleType">
              <el-select v-model="postForm.vehicleType" style="width: 100%" placeholder="请选择用车类型">
                <el-option
                  v-for="dict in dict.type.vehicle_types"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>

            </el-form-item>
            <el-form-item label="人数" prop="peopleNumber">
              <el-input v-model="postForm.peopleNumber" :readonly="readonly" placeholder="请输入人数"></el-input>
            </el-form-item>
            <el-form-item label="用车结束时间" prop="endTime">
              <el-date-picker
                v-model="postForm.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="limitEnd"
                :readonly="readonly"
                style="width: 100%"
                placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="目的地" prop="destination">
              <el-input v-model="postForm.destination" :readonly="readonly" placeholder="请输入目的地"></el-input>
            </el-form-item>
            <el-form-item label="用途" prop="type">
              <el-select v-model="postForm.type" placeholder="请选择用途" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.vehicle_use_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="用车原因" prop="reason">
              <el-input v-model="postForm.reason" type="textarea" :rows="2" :readonly="readonly"
                        placeholder="请用车原因"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="postForm.remarks" :readonly="readonly"
                        placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: center" v-show="isShow">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-show="!isShow">
        <el-button type="primary" @click="close">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 选择车辆对话框 -->
    <el-dialog :title="title" :visible.sync="workableVehicle" width="960px" append-to-body>
      <el-form :model="queryVehicleForm" inline @submit.native.prevent>
        <el-form-item label="车牌号">
          <el-input v-model="queryVehicleForm.licensePlate" placeholder="请输入车牌号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleQueryVehicle"
          >搜索
          </el-button>
          <el-button
            plain
            size="small"
            icon="el-icon-refresh"
            @click="resetQueryVehicle"
          >重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table

        v-loading="vehicleLoading"
        :data="vehicleList"
        max-height="350"

        ref="vehicleSelectTable"
        @row-click="rowClick"
        @selection-change="selectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="车牌号" align="center" v-if="columns[14].visible" prop="licensePlate">
        </el-table-column>
        <el-table-column label="车辆类型" align="center" v-if="columns[15].visible" prop="vehicleType"
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <dict-tag :options="dict.type.vehicle_type" :value="scope.row.vehicleType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="车辆状态" align="center" v-if="columns[16].visible" prop="vehicleState"
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <dict-tag :options="dict.type.vehicle_state" :value="scope.row.vehicleState"></dict-tag>
          </template>
        </el-table-column>
      </el-table>
      <ExPagination
        v-show="vehicleTotal > 0"
        :total="vehicleTotal"
        :page.sync="queryVehicleForm.pageNum"
        :limit.sync="queryVehicleForm.pageSize"
        @pagination="getVehicleList"
      ></ExPagination>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selectVehicle" :disabled="!multi">确 定</el-button>
        <el-button @click="abolish">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批历史对话框 -->
    <el-dialog :title="title" :visible.sync="historyView" width="600px" append-to-body @close="cancel">
      <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="queryForm.taskName" @keyup.enter.native="searchList"></el-input>
        </el-form-item>
        <el-form-item label="办理人ID" prop="assigneeName">
          <el-input v-model="queryForm.assigneeName" @keyup.enter.native="searchList"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="historyList">
        <el-table-column label="任务名称" align="center" v-if="columns[17].visible" prop="taskName">
        </el-table-column>
        <el-table-column label="处理人ID" align="center" v-if="columns[18].visible" prop="vehicleType"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="处理人" align="center" v-if="columns[19].visible" prop="assigneeName"
                         show-overflow-tooltip/>
        <el-table-column label="审批意见" align="center" v-if="columns[20].visible" prop="comment"
                         show-overflow-tooltip/>
        <el-table-column label="开始时间" align="center" v-if="columns[21].visible" prop="startTime"
                         show-overflow-tooltip/>
        <el-table-column label="结束时间" align="center" v-if="columns[22].visible" prop="endTime"
                         show-overflow-tooltip/>
        <el-table-column label="耗时" align="center" v-if="columns[23].visible" prop="assigneeName"
                         show-overflow-tooltip/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 进度查看对话框 -->
    <el-dialog :title="title" :visible.sync="progressView" width="500px" append-to-body @close="cancel">
      <div slot="footer" class="dialog-footer">
        <el-button @click="close" type="primary">确 定</el-button>
        <el-button @click="close">关 闭</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
    ></pagination>

    <HandleResolve
      v-if="progress.open"
      :id="progress.id"
      :instance-id="progress.instanceId"
      :title="progress.title"
      :is-approver="false"
      :process-open.sync="progress.open"
    ></HandleResolve>
    <!-- 导出对话框 -->
    <ExportTable
      :open-export.sync="exportOptions.open"
      :title="exportOptions.title"
      @export="exportFile"
    ></ExportTable>

  </div>
</template>

<script>
import {
  getInfoList,
  addInfo,
  editInfo,
  deleteInfo,
  getInfo,
  submitApply,
  getVehicleList,
  listHistory
} from "@/api/smartSchool/personWork/vehicleApply";
import {deptTreeSelect, getUser} from "@/api/system/user"
import Treeselect from "@riophae/vue-treeselect";
import {CustomCellStyle} from '@/enums/customStyle';
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {SubmitState} from "@/enums/apply";
import HandleResolve from '@/views/smartSchool/personWork/vehicleApply/components/HandleResolve';
import {ExportType} from "@/enums/common";

export default {
  name: 'Application',
  dicts: ['vehicle_types', "vehicle_type", "vehicle_state", "vehicle_use_type"],
  components: {
    Treeselect,
    HandleResolve
  },
  watch: {
    'postForm.departmentId'() {
      this.$nextTick(() => {
        this.$refs['postForm'].validateField('departmentId')
      })
    }
  },
  data() {
    const checkKilometers = (rule, value, callback) => {
      let regPos = new RegExp(/^\d+$/)
      if (regPos.test(value)) {
        callback()
      } else {
        callback(new Error('请输入数值'));
      }
    };
    return {
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      // 提交状态
      SubmitState,
      // 自定义列表单元格样式
      cellStyle: CustomCellStyle,
      // 当前选中的状态(未提交， 已提交)
      activeName: SubmitState.WILL_SUBMIT,
      // 查询表单
      queryForm: {
        submitState: 0,
        pageNum: 1,
        pageSize: 10,
        title: '',//标题
        type: '',//类型
        vehicleId: '',//车辆id
        applicantId: '',//申请人id
        applicantName: '',//用车人姓名
        departmentId: undefined,//用车部门id
        reason: '',//用车原因
        peopleNumber: '',//人数
        departurePlace: '',//出发地点
        destination: '',//目的地
        startTime: '',//用车开始时间
        endTime: '',//用车结束时间
        driver: '',//司机
        vehicleType: '',//用车类型
        remarks: '',//备注
        kilometers: '',//公里数
        state: '',//状态
        instanceId: '',//流程实例id
        // applyUser: '',//创建人
        applyTime: '',//申请时间
        taskName: '',//任务名称
        comment: '',//批注
        assignee: '',//
        assigneeName: '',//办理人
        realityStartTime: '',//实际开始时间
        realityEndTime: '',//实际结束时间
      },
      // 审批历史表单
      historyForm: {
        instanceId: '',
        comment: '',
        assigneeName: '',
      },
      // 审批历史列表
      historyList: [],
      // 遮罩层
      loading: false,
      // 可选车辆列表
      vehicleList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否只读
      readonly: false,
      // 多个禁用
      multi: false,
      // 显示搜索条件
      showSearch: true,
      // 信息列表
      infoList: [],
      // 数据总数
      total: 0,
      // 部门树选项
      deptOptions: undefined,
      // 新增/修改表单
      postForm: {},
      // 是否显示新增弹出层
      open: false,
      // 是否显示选择车辆弹出层
      workableVehicle: false,
      // 是否显示审批历史弹出层
      historyView: false,
      // 是否显示进度查看弹出层
      progressView: false,
      // 展示确定取消按钮
      isShow: true,
      // 是否禁用输入框
      isDisabled: false,
      // // 表单校验
      rules: {
        licensePlate: [
          {required: true, message: "车辆不能为空", trigger: "change"},
        ],
        departmentId: [
          {required: true, message: "用车部门不能为空", trigger: "change"}
        ],
        kilometers: [
          {required: true, message: "公里数不能为空", trigger: "blur"},
          {validator: checkKilometers, trigger: 'blur'}
        ]
      },
      // 弹出层标题
      title: '',
      // 列表信息
      columns: [
        {key: 0, label: `流程实例ID`, visible: true},
        {key: 1, label: `申请人`, visible: true},
        {key: 2, label: `人数`, visible: true},
        {key: 3, label: `出发地点`, visible: true},
        {key: 4, label: `目的地`, visible: true},
        {key: 5, label: `用车开始时间`, visible: true},
        {key: 6, label: `用车结束时间`, visible: true},
        {key: 7, label: `司机`, visible: true},
        {key: 8, label: `用车类型`, visible: true},
        {key: 9, label: `用车原因`, visible: true},
        {key: 10, label: `申请时间`, visible: true},
        {key: 11, label: `备注`, visible: true},
        {key: 12, label: `公里数`, visible: true},
        {key: 13, label: `操作`, visible: true},
        {key: 14, label: `车牌号`, visible: true},
        {key: 15, label: `车辆类型`, visible: true},
        {key: 16, label: `车辆状态`, visible: true},
        {key: 17, label: `任务名称`, visible: true},
        {key: 18, label: `处理人ID`, visible: true},
        {key: 19, label: `处理人`, visible: true},
        {key: 20, label: `审批意见`, visible: true},
        {key: 21, label: `开始时间`, visible: true},
        {key: 22, label: `结束时间`, visible: true},
        {key: 23, label: `耗时`, visible: true},
      ],
      // limitStart: {
      //   disabledDate: time => Date.parse(time) < Date.parse(new Date()) - 24 * 60 * 60 * 1000
      // },
      limitEnd: {
        disabledDate: time => Date.parse(time) < Date.parse(this.postForm.startTime) - 24 * 60 * 60 * 1000
      },
      // 选中的车辆
      selectedCar: null,
      // 开始结束时间
      dateRange: [],
      // 角色选项
      roleOptions: [],
      // 用车列表
      queryVehicleForm: {
        pageNum: 1,
        pageSize: 10,
        licensePlate: ''
      },
      // 用车列表加载
      vehicleLoading: false,
      // 用车列表总数
      vehicleTotal: 0,
      // 进度查看
      progress: {
        title: "审批查看",
        open: false,
        id: undefined,
        instanceId: undefined
      },

    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getUserRoles();
  },
  methods: {
    /** 获取列表数据 */
    getList() {
      this.loading = true; // 加载效果
      getInfoList(this.queryForm).then(response => {
        this.loading = false;
        this.infoList = response.rows;
        this.total = response.total;
      }).catch(err => {
        this.loading = false;
      })
    },
    rowClick(row) {
      this.$refs.vehicleSelectTable.clearSelection();
      this.$refs.vehicleSelectTable.toggleRowSelection(row, true);
    },
    // 搜索按钮
    handleQuery() {
      this.throttle(() => {
        this.queryForm.pageNum = 1;
        this.getList();
      })
    },
    // 搜索审批历史
    searchList() {

    },
    // 重置按钮
    resetQuery() {
      const submitState = this.queryForm.submitState;
      this.queryForm = {
        submitState: submitState,
        pageNum: 1,
        pageSize: 10,
      }
      this.dateRange = [];
      this.handleQuery(); // 重新发一次请求
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      const userId = this.$store.state.user.userId;
      this.isShow = true;
      this.isDisabled = false;
      this.open = true;
      this.title = "添加申请";
    },
    // 修改按钮操作
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.title = "修改申请";
      this.$modal.loading('正在加载数据，请稍等...');
      getInfo(id).then(response => {
        this.postForm = response.data;
        this.open = true;
        this.isDisabled = false;
        this.$modal.closeLoading();
      }).catch(err => {
        this.$modal.closeLoading();
      })
    },
    // 删除按钮操作
    handleDelete(row) {
      this.throttle(() => {
        const ids = row.id || this.ids;
        if (ids) {
          this.$modal.confirm(`是否确认删除选中的${Object.hasOwnProperty.call(ids, 'length') ? ids.length : 1}条数据？`).then(() => {
            this.$modal.loading('正在处理数据，请稍等...');
            return deleteInfo(ids);
          }).then(() => {
            this.$modal.closeLoading();
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {
            this.$modal.closeLoading();
          });
        }
      })
    },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids;
      const options = [
        {type: ExportType.TOTAL, path: '/vehicleApplication/export', params: {SubmitState: this.pageState}},
        {type: ExportType.SELECT, path: '/vehicleApplication/export/' + ids, params: {}},
        {
          type: ExportType.QUERY, path: '/vehicleApplication/export', params: {
            SubmitState: this.pageState,
            ...this.queryParams
          }
        },
      ]
      callback(options, `用车申请${new Date().getTime()}.xlsx`);
    },
    // 导出按钮操作
    handleExport() {
      this.exportOptions.open = true;

      // this.throttle(() => {
      //   this.download('vehicleApplication/export', {
      //     ...this.queryForm
      //   }, `申请${new Date().getTime()}.xlsx`)
      // })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 选择车辆对话框选中数据
    selectionChange(selection) {
      this.selectedCar = selection[0];
      this.multi = selection.length === 1;
    },
    // 查询部门下拉树结构
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getUserRoles() {
      const userId = this.$store.state.userId;
      getUser(userId).then(response => {
        this.roleOptions = response.roles;
      })
    },
    // 提交表单
    submitForm() {
      this.throttle(() => {
        this.$refs["postForm"].validate(valid => {
          if (valid) {
            this.$modal.loading('正在上传数据，请稍等...');
            if (this.postForm.id != null) {
              // 查看表单
              editInfo(this.postForm).then(response => {
                this.$modal.closeLoading();
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(err => {
                this.$modal.closeLoading();
              });
            } else {
              // 新增
              addInfo(this.postForm).then(response => {
                this.$modal.closeLoading();
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(err => {
                this.$modal.closeLoading();
              });
            }
          }
        });
      })
    },

    // 选择车辆
    selectVehicle() {
      // 这里面就来给表单赋值
      this.postForm.vehicleId = this.selectedCar.id;
      this.$set(this.postForm, 'licensePlate', this.selectedCar.licensePlate);
      // this.postForm.licensePlate = this.selectedCar.licensePlate;
      this.abolish();
    },

    // 打开表单数据
    openTableData(row) {
      const id = row.id || this.ids;
      this.title = '用车申请详细'
      this.$modal.loading('正在加载数据，请稍等...');
      getInfo(id).then(response => {
        this.postForm = response.data;
        this.open = true;
        this.isShow = false;
        this.isDisabled = true;
        this.readonly = true;
        this.$modal.closeLoading();
      }).catch(err => {
        this.$modal.closeLoading();
      });
    },
    // 审批历史对话框
    openApprovalHistory(row) {
      this.loading = true;
      this.title = "查看审批历史";
      this.historyForm.instanceId = row.instanceId;
      listHistory(this.historyForm).then(response => {
        this.historyList = response.rows;
        this.loading = false;
      }).catch(err => {
        this.loading = false;
      })
    },
    // 查看流程对话框
    openProgressView() {
      this.progressView = true;
      this.title = "查看进度";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.resetQuery();
      this.reset();
    },

    reset() {
      // 这里需要重置对话框表单
      this.postForm = {
        pageNum: 1,
        pageSize: 10,
        title: undefined,//标题
        type: undefined,//类型
        vehicleId: undefined,//车辆id
        applicantId: undefined,//申请人id
        applicantName: undefined,//用车人姓名
        departmentId: undefined,//用车部门id
        reason: undefined,//用车原因
        peopleNumber: undefined,//人数
        departurePlace: undefined,//出发地点
        destination: undefined,//目的地
        startTime: undefined,//用车开始时间
        endTime: undefined,//用车结束时间
        driver: undefined,//司机
        vehicleType: undefined,//用车类型
        remarks: undefined,//备注
        kilometers: undefined,//公里数
        state: undefined,//状态
        instanceId: undefined,//流程实例id
        applyUser: undefined,//申请人
        applyTime: undefined,//申请时间
        realityStartTime: undefined,//实际开始时间
        realityEndTime: undefined,//实际结束时间
      };
      this.resetForm('postForm');
    },

    // 关闭按钮
    close() {
      this.open = false;
      this.historyView = false;
      this.progressView = false;
    },
    // 可选车辆取消按钮
    abolish() {
      this.workableVehicle = false;
      this.$nextTick(() => {
        this.$refs.postForm.validateField('licensePlate');
      })
    },
    // 弹出选择车辆对话框
    selectChange() {
      this.workableVehicle = true;
      this.handleQueryVehicle();
    },

    // 查询用车列表
    handleQueryVehicle() {
      this.throttle(() => {
        this.getVehicleList();
      })
    },

    // 重置用车列表查询
    resetQueryVehicle() {
      this.queryVehicleForm = {
        pageNum: 1,
        pageSize: 10,
        licensePlate: ''
      };
      this.handleQueryVehicle();
    },

    // 列表查询用车列表
    getVehicleList() {
      this.vehicleLoading = true;
      console.log('this.queryVehicleForm', this.queryVehicleForm)
      this.$set(this.queryVehicleForm, 'vehicleState', 0)
      getVehicleList(this.queryVehicleForm).then(response => {
        this.vehicleLoading = false;
        this.vehicleList = response.rows;
        this.vehicleTotal = response.total;
      }).catch(err => {
        this.vehicleLoading = false;
      })
    },

    // 提交申请
    submitApply(row) {
      this.throttle(() => {
        const id = row.id;
        this.$modal.confirm(`是否提交此用车申请`).then(() => {
          this.$modal.loading('正在提交申请中...');
          return submitApply(id);
        }).then(() => {
          this.$modal.closeLoading();
          this.$message.success('提交成功');
          this.getList();
        })
          .catch(err => {
            this.$modal.closeLoading();
          })
      })
    },
    /** 【切换tab】 */
    handleChange({name}) {
      if (name == SubmitState.WILL_SUBMIT) {
        this.pageState = 0
      } else {
        this.pageState = 1
      }
      console.log(name);
      this.queryForm.submitState = Number(name);
      this.resetQuery();
      this.$nextTick(() => {
        this.$refs.applyTable.doLayout();
      })
    },
    /** 【已提交】查看详情 */
    handleDetail({id, instanceId}) {
      this.progress.id = id;
      this.progress.instanceId = instanceId;
      this.progress.open = true;
    },
    // 获取审批组角色ID
    getRoleKey(roleKey) {
      this.$set(this.postForm, 'roleKey', roleKey)
      // this.postForm.roleKey = roleKey
    },
  }
}
</script>

<style>

</style>
