<!-- 资源详情 -->
<template>
  <div class="book-vocab">
    <div class="book-vocab-content">
      <el-form ref="searchForm" :model="searchForm" :rules="courseListRules" size="mini">
        <el-form-item label="资源键值" label-width="90px" prop="resource_key">
          <el-input
            v-model="searchForm.resource_key"
            autocomplete="off"
            placeholder="请输入资源键值"
          ></el-input>
        </el-form-item>
        <el-form-item label="资源名称" label-width="90px" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入资源名称"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="90px" prop="memo">
          <el-input
            v-model="searchForm.memo"
            placeholder="请输入资源备注"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传资源" label-width="90px" prop="fileList">
          <el-upload
            action="url"
            :limit="uploadType === 'edit' ? 0 : 1"
            :on-exceed="handleExceed"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :http-request="upload"
            :file-list="fileList"
            accept="*"
            class="upload-demo"
            list-type="picture"
          >
            <el-button size="mini" type="success">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-button
        v-if="resourceKey === ''"
        class="submitBtn"
        size="mini"
        type="primary"
        @click="saveWord"
      >
        保存资源
      </el-button>
    </div>

    <div v-if="uploadType === 'edit'" class="book-vocab-footer">
      <el-button type="primary" size="mini" @click="saveWord">修改</el-button>
    </div>
  </div>
</template>

<script>
import { validNull } from '@/utils/validate';
import { getContent } from '@/api/ajax';
import { fileUpload } from '@/api/app';

export default {
  props: {
    resourceKey: {
      default: '',
      type: String
    },
    uploadType: {
      default: 'add',
      type: String
    }
  },
  data() {
    const validateNull = (rule, value, callback) => {
      if (!validNull(value)) {
        callback(new Error('请输入相应内容'));
      } else {
        callback();
      }
    };
    return {
      isData: false,
      isSaving: false,
      searchForm: {
        resource_key: '',
        memo: '',
        name: ''
      },
      fileList: [], // 上传图片数组
      courseListRules: {
        // 填写规则
        resource_key: [{ required: true, trigger: 'blur', validator: validateNull }],
        name: [{ required: true, trigger: 'blur', validator: validateNull }],
        memo: [{ required: true, trigger: 'blur', validator: validateNull }]
        // price: [
        //     { required: true, },
        // ],
      }
    };
  },
  watch: {
    resourceKey: {
      handler: function (val) {
        this.$refs.searchForm.resetFields();
        if (val) {
          this.searchForm.resource_key = val;
          if (val !== '') {
            this.getDetail();
          }
        } else {
          this.searchForm.name = '';
          this.searchForm.resource_key = '';
          this.searchForm.memo = '';
          this.fileList = [];
        }
      }
    }
  },
  created() {
    this.searchForm.resource_key = this.resourceKey;
    if (this.resourceKey !== '') {
      this.getDetail();
    } else {
      this.searchForm.name = '';
      this.searchForm.resource_key = '';
      this.searchForm.memo = '';
      this.fileList = [];
    }
  },
  // 方法集合
  methods: {
    saveWord() {
      this.$refs.searchForm.validate(valid => {
        if (valid) {
          this.isSaving = true;
          let MethodName = 'file_resource_manager-InputFileResource';
          const data_list = [];
          this.fileList.forEach((item, index) => {
            if (item.file_id) {
              let obj = {
                resource_key: this.searchForm.resource_key.trim(),
                file_id: item.file_id,
                memo: this.searchForm.memo.trim(),
                name: this.searchForm.name.trim()
              };
              data_list.push(obj);
            }
          });
          let data = {
            file_list: data_list
          };
          getContent(MethodName, data)
            .then(res => {
              this.$message.success('保存成功');
              this.$emit('closeDialog');
            })
            .catch(() => {
              this.isSaving = false;
            });
        }
      });
    },
    upload(file) {
      if (this.uploadType === 'edit') {
        this.fileList = [];
      }
      fileUpload('Open', file).then(response => {
        if (response.status === 1) {
          response.file_info_list.forEach((item, index) => {
            if (item.file_url) {
              let obj = {
                name: item.file_name,
                url: item.file_url,
                file_id: item.file_id
              };
              this.fileList.push(obj);
            }
          });
          this.$message.success('上传成功');
        } else {
          this.$message.warning(response.error);
        }
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    handlePreview(file) {
      console.log(file);
    },
    // 如果传参不为空 查询详情
    getDetail() {
      let MethodName = 'file_resource_manager-GetFileResource';
      let data_list = [];
      data_list.push(this.resourceKey);
      let data = {
        resource_key_list: data_list
      };
      getContent(MethodName, data)
        .then(res => {
          this.fileList = [];
          res.file_list.forEach((item, index) => {
            this.searchForm = item;
            if (item.file_url) {
              let obj = {
                name: '',
                url: item.file_url
              };
              this.fileList.push(obj);
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.book-vocab {
  width: 100%;
  overflow: hidden;

  &-content {
    width: 100%;
    margin: 0 auto;
    padding: 20px 0;
  }

  .submitBtn {
    margin-left: 90px;
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
