<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select
          v-model="query.device_type"
          class="filter-item"
          clearable
          placeholder="设备类型"
          size="small"
          style="width: 450px"
        >
          <el-option v-for="item in device_types" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :before-close="crud.cancelCU"
        :close-on-click-modal="false"
        :title="crud.status.title"
        :visible.sync="crud.status.cu > 0"
        width="800px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
          <el-form-item label="图片上传" prop="image_code">
            <el-upload
              :action="imagesUploadApi"
              :before-upload="beforeUpload_u"
              :file-list="fileList"
              :headers="headers"
              :limit="1"
              :on-success="handleSuccess"
              class="upload-demo"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="图片描述" prop="remark">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="适用驱动" prop="driver_code_json">
            <el-transfer
              v-model="value"
              :data="data"
              :filter-method="filterMethod"
              :titles="['未选','已选']"
              filter-placeholder="请输入驱动名称"
              filterable
              @change="handleChange"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图标" prop="image_name">
          <template slot-scope="{row}">
            <el-image
              :preview-src-list="[baseApi + '/file/图片/' + row.image_code]"
              :src=" baseApi + '/file/图片/' + row.image_code"
              class="el-avatar"
              fit="contain"
              lazy
            >
              <div slot="error">
                <i class="el-icon-document" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="适用驱动" prop="driver_code_json" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column
          v-permission="['admin','stageImage:edit','stageImage:del']"
          align="center"
          label="操作"
          width="150px"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudStageImage from '@/api/logicflow/stageImage'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { get } from '@/views/system/dict/dictDetail'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = {
  image_uuid: null,
  image_name: null,
  driver_code_json: null,
  remark: null,
  is_active: null,
  is_delete: null,
  create_by: null,
  create_time: null,
  update_by: null,
  update_time: null,
  image_code: null
}
export default {
  name: 'StageImage',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '舞台',
      url: 'api/stageImage',
      idField: 'image_uuid',
      sort: 'image_uuid,desc',
      crudMethod: { ...crudStageImage },
      optShow: {
        add: true,
        edit: true,
        del: true
      }
    })
  },
  data() {
    const generateData = _ => {
      const data = []
      const cities = []
      cities.forEach((city, index) => {
        data.push({
          label: city,
          key: index,
          cities: cities[index]
        })
      })
      return data
    }
    return {
      data: generateData(),
      value: [],
      cities: [],
      filterMethod(query, item) {
        return item.cities.indexOf(query) > -1
      },
      permission: {
        add: ['admin', 'stageImage:add'],
        edit: ['admin', 'stageImage:edit'],
        del: ['admin', 'stageImage:del']
      },
      headers: { 'Authorization': getToken() },
      rules: {
        image_uuid: [
          { required: true, message: '设备标识不能为空', trigger: 'blur' }
        ],
        image_name: [
          { required: true, message: '设备名字不能为空', trigger: 'blur' }
        ],
        is_active: [
          { required: true, message: '是否启用不能为空', trigger: 'blur' }
        ],
        is_delete: [
          { required: true, message: '是否删除不能为空', trigger: 'blur' }
        ],
        create_by: [
          { required: true, message: '创建者不能为空', trigger: 'blur' }
        ],
        create_time: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ],
        image_code: [
          { required: true, message: '图标编码不能为空', trigger: 'blur' }
        ]
      },
      fileList: [],
      device_types: []
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  created() {
    this.$nextTick(() => {
      // 获取设备类型字典
      get('device_type').then(data => {
        this.device_types = data.content
      })
    })
  },

  mounted() {
    this.getUserInfo()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterSubmit]() {
      this.fileList = []
      this.value = []
      this.cities = []
    }, [CRUD.HOOK.beforeToAdd]() {
      this.fileList = []
      this.value = []
      this.cities = []
    },
    [CRUD.HOOK.afterToEdit]() {
      const driver_code_json = this.form.driver_code_json
      const json_arr = driver_code_json.split(',')
      const new_arr = []
      if (json_arr) {
        json_arr.forEach(function(c) {
          new_arr.push(c)
        })
      }
      this.value = new_arr
      let new_lst = []
      const image_code = this.form.image_code
      const image_name = this.form.image_name
      new_lst = [{ name: image_code, url: image_name }]
      this.fileList = new_lst
    },
    beforeUpload_u(file) {
      const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = (testmsg === 'png' || testmsg === 'jpg' || testmsg === 'svg')

      let bool = false
      if (extension) {
        bool = true
      } else {
        bool = false
      }
      if (!extension) {
        this.$confirm(`上传文件只能是png/jpg/svg格式!`)
      }

      return bool
    },
    handleSuccess(response) {
      console.log(response)
      this.form.image_code = response.real_name
      this.form.image_name = response.path
    },
    handleChange(value) {
      let a = ''
      if (value) {
        value.forEach(function(c, index) {
          a = a + c
          if ((index + 1) !== value.length) {
            a = a + ','
          }
        })
      }
      this.form.driver_code_json = a
    },
    getUserInfo: function() {
      const me = this
      // 清空数据
      me.data = []
      me.value = []
      get('device_type').then(device => {
        if (device) {
          device.content.forEach(function(c, index) {
            me.cities.push(c.label)
            me.data.push({
              key: c.value,
              label: c.label,
              cities: c.label
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
