<template>
  <div class="meta-container">
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="输入模型名称/编号进搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.complex"
          clearable
          size="small"
          placeholder="模型类型"
          class="filter-item"
          style="width: 140px"
          @change="crud.toQuery"
        >
          <el-option label="单体" value="1"></el-option>
          <el-option label="复合" value="2"></el-option>
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="540px"
    >
      <div class="dialog-main">
        <el-tabs v-model="activeTab" type="card" @tab-click="handleChangeTab">
          <el-tab-pane label="基本信息" name="baseInfo">
            <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
              <el-form-item label="模型名称" prop="name">
                <el-input v-model="form.name" />
              </el-form-item>
              <el-form-item label="模型编号" prop="code">
                <el-input v-model="form.code" />
              </el-form-item>
              <el-form-item label="所属分类">
                <tree-select
                  v-model="form.categoryId"
                  :options="modelCategoryData"
                  style="width: 100%"
                  placeholder="选择上级分类（顶级分类该项不选）"
                />
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input v-model="form.sort" />
              </el-form-item>
              <el-form-item label="模型类型">
                <el-radio-group v-model="form.complex" style="width: 370px">
                  <el-radio label="0">单体模型</el-radio>
                  <el-radio label="1">复合模型</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="缩略图文件" prop="path">
                <!-- :http-request="uploadFiles" -->
                <el-upload
                  style="width: 100%"
                  name="fileList"
                  :action="VUE_APP_BASE_API + '/file/uploadFile'"
                  :show-file-list="true"
                  :on-exceed="(file, fileList) => handleUploadExceed(file, fileList, 'img')"
                  :on-success="(res, file, fileList) => handleSuccess(res, file, fileList, 'img')"
                  :before-upload="(file) => beforeUpload(file, 'img')"
                  :on-error="(res, file, fileList) => handleUploadError(res, file, fileList, 'img')"
                  :on-remove="(file, fileList) => handleUploadRemove(file, fileList, 'img')"
                  :data="{ fileModule: 41 }"
                  :file-list="fileList.img"
                  :headers="{ token }"
                  :limit="1"
                  accept=".jpg,.jpeg,.gif,.png,.webp"
                >
                  <el-button icon="el-icon-upload">选择文件</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item v-if="form.complex === '0'" label="模型文件" prop="path">
                <el-upload
                  style="width: 100%"
                  name="fileList"
                  :action="VUE_APP_BASE_API + '/file/uploadFile'"
                  :show-file-list="true"
                  :on-exceed="(file, fileList) => handleUploadExceed(file, fileList, 'model')"
                  :on-success="(res, file, fileList) => handleSuccess(res, file, fileList, 'model')"
                  :before-upload="(file) => beforeUpload(file, 'model')"
                  :on-error="
                    (res, file, fileList) => handleUploadError(res, file, fileList, 'model')
                  "
                  :on-remove="(file, fileList) => handleUploadRemove(file, fileList, 'model')"
                  :data="{ fileModule: 40 }"
                  :file-list="fileList.model"
                  :headers="{ token }"
                  :limit="1"
                  accept=".glb,.gltf,"
                >
                  <el-button icon="el-icon-upload">选择文件</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="模型描述" prop="desc">
                <el-input type="textarea" :rows="3" v-model="form.desc" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="参数信息" name="paramInfo">
            <el-table
              class="info-table"
              :data="form.modelInfoList"
              size="small"
              style="width: 100%"
              border
            >
              <!-- @cell-mouse-enter="handleCellEnter" @cell-mouse-leave="handleCellLeave" -->
              <el-table-column prop="label" label="数据项" align="center">
                <template slot-scope="scope">
                  <el-input
                    v-if="scope.row.isEdit"
                    class="item"
                    v-model="scope.row.name"
                    placeholder="请输入内容"
                    size="mini"
                  ></el-input>
                  <div v-else class="txt">{{ scope.row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="value" label="值/变量" align="center">
                <template slot-scope="scope">
                  <el-input
                    v-if="scope.row.isEdit"
                    class="item"
                    v-model="scope.row.value"
                    placeholder="请输入内容"
                    size="mini"
                  ></el-input>
                  <div v-else class="txt">{{ scope.row.value }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px">
                <template slot="header">
                  <div class="slot-header">
                    <span>操作</span>
                    <i class="icon-edit el-icon-circle-plus" @click="addRow"></i>
                  </div>
                </template>
                <template slot-scope="scope">
                  <!-- <i class="el-icon-plus"></i> -->
                  <div class="opt-box">
                    <i
                      class="icon-edit"
                      @click="editOrSave(scope.row)"
                      :class="scope.row.isEdit ? 'el-icon-document-checked' : 'el-icon-edit'"
                    ></i>
                    <i
                      class="icon-delete el-icon-delete"
                      @click.prevent="deleteRow(scope.$index)"
                    ></i>
                    <i class="icon-up el-icon-sort-up"></i>
                    <i class="icon-down el-icon-sort-down"></i>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <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"
      :empty-text="crud.query.categoryId ? '暂无数据' : '请选择模型查看模型信息'"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in modelTableOptions"
        :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">
          <template v-if="item.prop === 'thumbnail'">
            <el-button type="text" size="mini" @click="handleView(scope.row)"> 查看 </el-button>
            <el-image
              :ref="'thumbnail' + scope.row.id"
              v-show="false"
              fit="contain"
              :preview-src-list="[`${VUE_APP_BASE_API}${scope.row.thumbnail}`]"
            />
          </template>
          <template v-else-if="item.prop === 'complex'">
            {{ scope.row[item.prop] === '0' ? '单体' : '复合' }}
          </template>
          <template v-else>{{ scope.row[item.prop] }}</template>
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'model:edit', 'model:del'])"
        label="操作"
        width="240"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="table-opt-box">
            <div class="slot-btn">
              <el-button size="mini" icon="el-icon-info" type="info"></el-button>
              <el-button size="mini" icon="el-icon-view" type="warning"></el-button>
            </div>
            <udOperation :data="scope.row" :permission="permission" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudComps from '@crud'
import crudModel from '@/api/modelLibrary/list'
import { modelTableOptions } from '../tableConfig'
import { initData, deleteFile } from '@/api/data'
import { getToken } from '@/utils/auth'
// vue-treeselect
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
const defaultForm = {
  id: '',
  name: '',
  code: '',
  categoryId: '',
  complex: '0',
  sort: '',
  desc: '',
  thumbnail: '',
  modelUri: '',
  modelInfoList: [],
  modelComponentList: [],
}
export default {
  name: 'ModelList',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, TreeSelect },
  cruds() {
    return CRUD({
      title: '模型',
      url: 'modelConfiguration/model/getList',
      crudMethod: { ...crudModel },
    })
  },
  props: {
    modelCategoryData: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      permission: {
        add: ['admin', 'model:add'],
        edit: ['admin', 'model:edit'],
        del: ['admin', 'model:del'],
      },
      modelTableOptions,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        color: [{ required: true, message: '请选择颜色', trigger: ['blur', 'change'] }],
        imageUrl: [{ required: true, message: '请选择图标', trigger: ['blur', 'change'] }],
      },
      activeTab: 'baseInfo',
      fileList: {
        img: [],
        model: [],
      },
    }
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    token() {
      return getToken() ?? ''
    },
  },
  created() {},
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.beforeToAdd](crud, form) {
      console.log(form)
      if (!crud.query.categoryId) {
        this.$message.warning('请先选择模型分类！')
        return false
      } else {
        form.categoryId = crud.query.categoryId + ''
      }
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      form.categoryId = form.categoryId + ''
      console.log(form)
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      // 选择label类型时的处理
    },
    checkboxT(row, rowIndex) {
      return true
      // return row.id !== this.modelInfo.id
    },
    handleChangeTab() {},
    /** 编辑或保存 */
    editOrSave(row, column, cell, event) {
      this.$set(row, 'isEdit', !row.isEdit)
      // row.isEdit = true;
    },
    /** 新增一条 */
    addRow() {
      this.form.modelInfoList.push({ name: '', value: '', sort: this.form.modelInfoList.length })
    },
    // 删除当前行
    deleteRow(index) {
      this.form.modelInfoList.splice(index, 1)
    },
    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 = {
        img: ['jpg', 'jpeg', 'gif', 'png', 'webp'],
        model: ['glb', 'gltf'],
      }
      if (!whiteList[type].includes(fileExtension)) {
        this.$message.warning(`只能上传扩展名为 ${whiteList[type].join(' / ')} 的文件`)
        return false
      }
    },
    handleSuccess(res, file, fileList, type) {
      console.log(res)
      if (res.code === 20000) {
        if (type == 'img') {
          this.form.thumbnail = res.data.path
        } else if (type == 'model') {
          this.form.modelUri = res.data
        }
      } else {
        this.$message.error(res.msg)
      }
    },
    handleUploadError(err, file, fileList, type) {
      console.log(err)
      this.$message.error('上传失败')
    },
    handleUploadRemove(file, fileList, type) {
      console.log(file)
      const param = { fileModule: type === 'img' ? 41 : 40, filePath: file.response.data }
      deleteFile(param)
        .then((res) => {
          if (type == 'img') {
            this.form.thumbnail = ''
          } else if ((type = 'model')) {
            this.modelUri = ''
          }
        })
        .catch((err) => {
          console.log(err)
          this.$message.error('删除文件失败')
        })
    },
    handleUploadExceed(file, fileList, type) {
      this.$message.warning('超出限制！只能上传一个文件')
    },
    handleView(data) {
      console.log(data)
      let curImg = this.$refs[`thumbnail${data.id}`][0]
      console.log(this.$refs[`thumbnail${data.id}`][0])
      this.$nextTick(() => {
        curImg.clickHandler()
      })
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}

.info-table {
  ::v-deep .el-input__inner {
    height: 28px !important;
  }
  .slot-header {
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      cursor: pointer;
      font-size: 15px;
      color: royalblue;
    }
  }
  .opt-box {
    i {
      font-size: 15px;
      cursor: pointer;
      margin-left: 3px;
    }
    .icon-edit {
      color: blue;
    }
    .icon-delete {
      color: red;
    }
    .icon-up,
    .icon-down {
      color: darkgoldenrod;
    }
  }
}
.table-opt-box {
  display: flex;
  justify-content: center;
  .slot-btn {
    .el-button {
      margin-left: 0;
      margin-right: 8px;
    }
  }
}
</style>
