<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="输入预案名称"
          style="width: 160px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.type"
          filterable
          clearable
          size="small"
          placeholder="请选择预案类型"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item of options.typeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.level"
          filterable
          clearable
          size="small"
          placeholder="请选择预案级别"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item of options.levelArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.status"
          filterable
          clearable
          size="small"
          placeholder="请选择预案状态"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item of options.statusArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission"></crudOperation>
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible="crud.status.cu > 0"
      :title="crud.status.title"
      width="500px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="预案名称" prop="name">
          <el-input v-model="form.name" style="width: 370px" />
        </el-form-item>
        <el-form-item label="预案类型" prop="type">
          <el-select
            v-model="form.type"
            filterable
            size="small"
            placeholder="请选择预案类型"
            class="filter-item"
            style="width: 370px"
          >
            <el-option
              v-for="item in options.typeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预案级别" prop="type">
          <el-select
            v-model="form.level"
            filterable
            size="small"
            placeholder="请选择预案类型"
            class="filter-item"
            style="width: 370px"
          >
            <el-option
              v-for="item in options.levelArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预案版本" prop="version">
          <el-input v-model="form.version" style="width: 370px" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="form.updateTime"
            type="datetime"
            placeholder="选择日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 370px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预案上传" prop="path">
          <el-upload
            style="width: 100%"
            name="fileList"
            :action="VUE_APP_BASE_API + '/file/uploadFile'"
            :show-file-list="true"
            :on-exceed="handleUploadExceed"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-error="handleUploadError"
            :on-remove="handleUploadRemove"
            :data="{ fileModule: 50 }"
            :file-list="fileList"
            :headers="{ token }"
            :limit="1"
            accept=".pdf"
          >
            <el-button icon="el-icon-upload">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="预案名称" prop="name" align="center">
        <template slot-scope="scope">
          <span style="color: #409eff; cursor: pointer" @click="openPDF(scope.row)">
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="预案类型"
        prop="type"
        align="center"
        :filters="options.typeArr"
        :filter-method="filterHandler"
      ></el-table-column>
      <el-table-column
        label="预案级别"
        prop="level"
        align="center"
        :filters="options.levelArr"
      ></el-table-column>
      <el-table-column label="预案版本" prop="version" align="center"></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        align="center"
        :sortable="true"
      ></el-table-column>
      <el-table-column
        label="预案状态"
        prop="status"
        align="center"
        :filters="options.statusArr"
      ></el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'preplan:edit', 'preplan:del'])"
        label="操作"
        width="240px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="table-opt-box">
            <div class="slot-btn">
              <el-button size="mini" icon="el-icon-upload2" type="success"></el-button>
              <el-button size="mini" icon="el-icon-download" type="success"></el-button>
            </div>
            <udOperation :data="scope.row" :permission="permission" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <preview-PDF :dialogConfig="pdfConfig" />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudPreplan from '@/api/emergency/preplan'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { deleteFile } from '@/api/data'
import { preplanList } from '../tableConfig'
import { getToken } from '@/utils/auth'
import PreviewPDF from '@/components/PreviewPDF'
const defaultForm = {
  id: '',
  name: '', //预案内容
  type: '', //预案类型
  level: '', // 预案级别
  version: '', // 预案版本
  updateTime: '', // 预案更新时间
  status: '', // 预案状态
}

export default {
  name: 'preplan',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, PreviewPDF },
  cruds() {
    return CRUD({
      title: '预案',
      url: 'emergency/plan/getList',
      listOrder: [],
      crudMethod: { ...crudPreplan },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    token() {
      return getToken() ?? ''
    },
  },
  data() {
    return {
      permission: {
        add: ['admin', 'preplan:add'],
        edit: ['admin', 'preplan:edit'],
        del: ['admin', 'preplan:del'],
      },
      rules: {
        name: [{ required: true, message: '请输入预案名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择预案类型', trigger: 'blur' }],
        mac: [{ required: true, message: '请输入MAC', trigger: 'blur' }],
      },
      options: {
        typeArr: [
          { label: '总部', text: '总部', value: '1' },
          { label: '合资公司', text: '合资公司', value: '2' },
          { label: '管理处', text: '管理处', value: '3' },
          { label: '维抢修中心', text: '维抢修中心', value: '4' },
        ],
        levelArr: [
          { label: '一级', text: '一级', value: '1' },
          { label: '二级', text: '二级', value: '2' },
          { label: '三级', text: '三级', value: '3' },
        ],
        statusArr: [
          { label: '已过期', text: '已过期', value: '1' },
          { label: '即将过期', text: '即将过期', value: '2' },
          { label: '正常', text: '正常', value: '3' },
        ],
      },
      fileList: [],
      pdfConfig: {
        show: false,
        url: 'http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf',
      },
    }
  },
  methods: {
    [CRUD.HOOK.afterRefresh]() {
      // this.crud.page.total = preplanList.length
      // this.crud.data = preplanList
      // this.crud.resetDataStatus()
    },
    // 打开
    [CRUD.HOOK.beforeToEdit]() {
      this.fileList = [this.form.filePath]
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    beforeUpload(file, type) {
      if (file.size > 1024 * 1024 * 10) {
        this.$message.warning('文件最大限制为 10MB')
        return false
      }
      let fileName = file.name
      let fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
      const whiteList = ['pdf']
      if (!whiteList.includes(fileExtension)) {
        this.$message.warning(`只能上传扩展名为 ${whiteList.join(' / ')} 的文件`)
        return false
      }
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 20000) {
        console.log(res)
        this.form.filePath = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },
    handleUploadError(err, file, fileList) {
      console.log(err)
      this.$message.error('上传失败')
    },
    handleUploadRemove(file, fileList) {
      console.log(file)
      const param = { fileModule: 50, filePath: file.response.data }
      deleteFile(param)
        .then((res) => {
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
          this.$message.error('删除文件失败')
        })
    },
    handleUploadExceed(file, fileList) {
      this.$message.warning('超出限制！只能上传一个文件')
    },
    openPDF(row) {
      this.pdfConfig.show = true
      this.pdfConfig.url = row.filePath
    },
  },
}
</script>

<style lang="scss" scoped>
.table-opt-box {
  display: flex;
  justify-content: center;
  .slot-btn {
    .el-button {
      margin-left: 0;
      margin-right: 8px;
    }
  }
}
</style>
