<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 in optionsObj.IocnType"
            :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"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in optionsObj.IocnType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图标上传" prop="path">
          <el-upload
            class="avatar-uploader"
            :action="VUE_APP_BASE_API + '/file/uploadFile'"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-error="handleUploadError"
            :on-remove="handleUploadRemove"
            :data="{ fileModule: 1 }"
            :file-list="fileList"
            :headers="{ token }"
            accept=".jpg,.jpeg,.gif,.png"
          >
            <img v-if="form.path" :src="VUE_APP_BASE_API + form.path" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传 jpg / jpeg / gif / png 文件，且不超过 5 MB
            </div>
          </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
        v-for="item in iconTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
        <template slot-scope="scope">
          <img
            style="width:32px;height:32px"
            v-if="item.prop === 'path'"
            :src="VUE_APP_BASE_API + scope.row.path"
            alt=""
          />
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'icon:edit', 'icon:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation :data="scope.row" :permission="permission" />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudIcon from '@/api/system/icon'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { getOptions } from '@/api/system/public'

// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { iconTableOptions } from '../tableConfig'
import { getToken } from '@/utils/auth'
import getters from '@/store/getters'
const defaultForm = {
  id: '',
  name: '', //图标内容
  type: '', //图标类型
  path: '' // 图标地址
}

export default {
  name: 'Icon',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps },
  cruds() {
    return CRUD({
      title: '标签',
      url: 'system/icon/getPageListJson',
      listOrder: [],
      crudMethod: { ...crudIcon }
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    }
  },
  data() {
    return {
      iconTableOptions,
      viewLoading: false,
      permission: {
        add: ['admin', 'icon:add'],
        edit: ['admin', 'icon:edit'],
        del: ['admin', 'icon:del']
      },
      rules: {
        name: [{ required: true, message: '请输入图标名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择图标类型', trigger: 'blur' }],
        mac: [{ required: true, message: '请输入MAC', trigger: 'blur' }]
      },
      buildings: [
        { label: '西南成都作业区', value: 1 },
        { label: '西北西安作业区', value: 2 }
      ],
      electricOptions: [
        { label: '低于25%', value: 1 },
        { label: '低于50%', value: 2 },
        { label: '低于75%', value: 3 },
        { label: '低于100%', value: 4 }
      ],
      optionsObj: {
        IocnType: []
      },
      token: getToken() ?? '',
      fileList: []
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    getOptions() {
      Object.keys(this.optionsObj).forEach(async key => {
        try {
          let res
          if (key === 'Label') {
            res = await getOptions(key, { id: null })
          } else {
            res = await getOptions(key)
          }
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    beforeUpload(file) {
      if (file.size > 1024 * 1024 * 5) {
        this.$message.warning('文件最大限制为 5MB')
        return false
      }
      let fileName = file.name
      let fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
      const whiteList = ['jpg', 'jpeg', 'gif', 'png']
      if (!whiteList.includes(fileExtension)) {
        this.$message.warning(`只能上传扩展名为 ${whiteList.join(' / ')} 的文件`)
        return false
      }
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 20000) {
        this.form.path = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },
    handleUploadError(err, file, fileList) {
      console.log(err)
      this.$message.error('上传失败')
    },
    handleUploadRemove(file, fileList) {
      if (fileList.length == 0) {
        this.form.Path = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
::v-deep .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
