<template>
  <div>
    <card-container>
      <vxe-toolbar>
        <template #buttons>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="$refs['AddVehicle'].setType('vehicle'),isShowAdd = true">新增车辆</el-button>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="$refs['AddVehicle'].setType('boat'),isShowAdd = true">新增艇</el-button>

          <el-button icon="el-icon-search" type="primary" plain size="small" @click="getList">搜索</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px;"
        :loading="loading"
        keep-source
        show-overflow
        :column-config="{ resizable: true }"
        :edit-rules="validRules"
        :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true, autoClear: false }"
        :align="allAlign"
        :data="tableData"
      >
        <vxe-column type="seq" width="58" align="center" />
        <vxe-column field="name" width="160" title="型号" :edit-render="{ name: 'input', attrs: { type: 'text' } }" />
        <vxe-column field="type" title="类型" width="120" :edit-render="{ name: 'select', options: [{ label: '车', value: 'vehicle' },{ label: '船', value: 'boat' }] }" />
        <vxe-column field="license" width="140" title="号码" :edit-render="{ name: 'input', attrs: { type: 'text' } }" />
        <vxe-column field="driver" width="120" title="驾驶员" :edit-render="{ name: 'input', attrs: { type: 'text' } }" />
        <vxe-column field="start_date" width="170" title="上牌日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.start_date" size="small" value-format="yyyy-MM-dd" />
          </template>
        </vxe-column>
        <vxe-column width="200" title="照片" field="photo_file.original_name" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-upload v-model="row.photo_file" progress-text="{percent}%" :more-config="{ maxCount: 1, layout: 'horizontal' }" :limit-size="20" :show-button-text="false" :upload-method="({file}) => uploadMethod(file, row)"></vxe-upload>
          </template>
        </vxe-column>
        <vxe-column field="insurance_expire" width="170" title="保险到期日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.insurance_expire" value-format="yyyy-MM-dd" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="inspect_date" width="170" title="年检日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.inspect_date" value-format="yyyy-MM-dd" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="maintain_expire" width="170" title="保养日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.maintain_expire" value-format="yyyy-MM-dd" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="discard_date" width="170" title="报废日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.discard_date" value-format="yyyy-MM-dd" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="end_date" width="170" title="归属结束日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.end_date" value-format="yyyy-MM-dd" size="small" />
          </template>
        </vxe-column>
        <vxe-column field="status" title="车辆状态" width="120" :edit-render="{}" :formatter="({ cellValue }) => cellValue ? '正常可用' : '维修中'">
          <template #edit="{ row }">
            <el-select v-model="row.status" style="width: 100%;" size="small">
              <el-option :value="1" label="正常可用" />
              <el-option :value="-1" label="维修中" />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="is_open_detail" title="是否开放精准预约" width="120" :edit-render="{}" :formatter="({ cellValue }) => cellValue ? '开放' : '不开放'">
          <template #edit="{ row }">
            <el-select v-model="row.is_open_detail" style="width: 100%;" size="small">
              <el-option :value="1" label="开放" />
              <el-option :value="0" label="不开放" />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="operate" title="操作" min-width="220" fixed="right">
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button size="small" type="primary" @click="saveRowEvent(row)">保存</el-button>
              <el-button size="small" type="primary" plain @click="cancelRowEvent(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="small" type="warning" @click="editRowEvent(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="destroyRowEvent(row)">删除</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px;"
        :current-page.sync="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size.sync="select.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="e => {
          select.page_size = e;
          select.page = 1;
          getList();
        }"
        @current-change="e => {
          select.page = e;
          getList();
        }"
      />
    </card-container>
    <add-vehicle ref="AddVehicle" :departments="departments" :is-show.sync="isShowAdd" @refresh="getList" />
  </div>
</template>

<script>
import { index as departmentIndex } from '@/api/department'
import { deepCopy } from '@/utils'
import { index, save, destroy } from '@/api/vehicle'
import AddVehicle from './components/AddVehicle.vue'
import axios from "axios";
import {getToken} from "@/utils/auth";
export default {
  components: {
    AddVehicle
  },
  data() {
    return {
      departments: [],
      isShowAdd: false,

      loading: false,
      select: {
        page: 1,
        page_size: 20,
        show_relation: ['photo_file']
      },
      total: 0,
      allAlign: null,
      tableData: [],
      validRules: {
        name: [
          { required: true, message: '请输入角色' }
        ]
      },
      form: {
        id: '',
        name: '',
        license: '',
        driver: '',
        photo_file_id: '',
        start_date: '',
        insurance_expire: '',
        maintain_expire: '',
        status: 1,
        department_id: '',
        discard_date: '',
        inspect_date: '',
        is_open_detail: '',
        type: '',
        end_date: ''
      }
    }
  },
  computed: {
    isActiveStatus() {
      return function(row) {
        if (this.$refs['table']) {
          return this.$refs['table'].isEditByRow(row)
        }
      }
    }
  },
  created() {
    this.getDepartments()
    this.getList()
  },
  methods: {
    uploadMethod(file, row) {
      const formData = new FormData()
      formData.append('file', file)
      return axios.post(process.env.VUE_APP_UPLOAD_API, formData, {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        }
      }).then((response) => {
        if (response.status === 200 && !response.data.code) {
          row.photo_file_id = response.data.data.id
          row.photo_file = response.data.data
        } else {
          this.$message.error("上传失败")
        }
      })
    },
    editRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].setEditRow(row)
      }
    },
    cancelRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].clearEdit().then(() => {
          // 还原行数据
          this.$refs['table'].revertData(row)
        })
      }
    },

    async getDepartments() {
      try {
        this.departments = await departmentIndex({
          page: 1,
          page_size: 9999
        })
      } catch (err) {
        console.error(err)
      }
    },
    async getList() {
      this.loading = true
      try {
        const res = await index(this.select)
        this.tableData = res.data
        this.total = res.total
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },

    async saveRowEvent(row) {
      try {
        await this.$confirm('确认保存？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        await this.$refs['table'].clearEdit()
        const form = deepCopy(this.form)
        for (const key in form) {
          form[key] = row[key]
        }
        if (!form.password) {
          delete form.password
        }
        this.loading = true
        await save(form)
        await this.getList()
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    async destroyRowEvent(row) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        this.loading = true
        if (row.id) {
          await destroy({
            id: row.id
          })
          await this.getList()
        } else {
          console.log(row)
          this.tableData.splice(this.tableData.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY), 1)
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.total {
  color: #666;
  text-align: right;
  line-height: 3;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
