<template>
  <el-dialog
    :title="`更新${fieldObj[field]}`"
    :visible="visible"
    :width="dialogWidth"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <template v-if="['name', 'editor', 'category', 'language', 'topic', 'reader', 'publisher'].includes(field)">
      <el-input v-model="stringValue" type="text" />
    </template>

    <div v-if="field === 'cover_image_file_url'" class="upload-image">
      <el-upload
        class="avatar-uploader"
        action="no"
        :http-request="upload"
        :before-upload="beforeUpload"
        accept="image/*"
        :show-file-list="false"
      >
        <img v-if="stringValue" :src="stringValue" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>

    <template v-if="['content_intro', 'background', 'author_intro'].includes(field)">
      <el-input v-model="stringValue" type="textarea" :autosize="{ minRows: 4 }" maxlength="1500" show-word-limit />
    </template>

    <template v-if="field === 'plan_publish_date'">
      <el-date-picker
        v-model="stringValue"
        type="date"
        placeholder="选择日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      />
    </template>

    <template v-if="['content_count_YG', 'word_count_YG'].includes(field)">
      <el-input v-model="stringValue" type="number" />
    </template>

    <div v-if="field === 'label_list'" class="label-input-content">
      <el-input v-model="labelInput" placeholder="请输入标签" @keyup.enter.native="labelChange" />
      <div class="label-list">
        <el-tag v-for="(tag, index) in arrayValue" :key="index" closable @close="arrayValue.splice(index, 1)">
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fileUpload } from '@/api/app';

export default {
  name: 'UpdateProjectField',
  props: {
    field: {
      type: String,
      required: true,
    },
    value: {
      type: [String, Number, Array, Object],
      required: true,
    },
    projectId: {
      type: String,
      required: true,
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      fieldObj: {
        // 单行文本
        name: '项目名称',
        category: '项目分类',
        language: '语种',
        topic: '所属课题',
        editor: '作者',
        reader: '读者对象',
        publisher: '出版单位',
        // 多行文本
        content_intro: '内容简介',
        background: '选题背景',
        author_intro: '作者简介',
        // 上传图片
        cover_image_file_url: '封面图片',
        // 日期
        plan_publish_date: '计划出版日期',
        // 数字
        content_count_YG: '预计容量（课数）',
        word_count_YG: '预计字数',
        // 对象
        label_list: '作品标签',
      },
      stringValue: this.value,
      arrayValue: [],
      imageId: '',
      labelInput: '',
    };
  },
  computed: {
    dialogWidth() {
      if (['content_count_YG', 'word_count_YG', 'plan_publish_date'].includes(this.field)) {
        return '260px';
      }
      if (this.field === 'label_list') {
        return '460px';
      }
      return '550px';
    },
  },
  watch: {
    value(newVal) {
      this.stringValue = newVal;

      if (this.field === 'label_list' && Array.isArray(newVal)) {
        this.arrayValue = [...newVal];
      }
    },
  },
  methods: {
    // 处理标签输入
    labelChange() {
      if (this.labelInput.trim() !== '') {
        this.arrayValue.push(this.labelInput.trim());
        this.labelInput = '';
      }
    },
    beforeUpload(file) {
      const isImage = /^image/.test(file.type);
      if (!isImage) {
        this.$message.error('上传的文件不是图片，请重新上传！');
      }
      return isImage;
    },
    upload(file) {
      if (file.file.size / 1048576 > 2) {
        return this.$message.warning(`${file.file.name}文件大小超出限制`);
      }
      fileUpload('Open', file, { isGlobalprogress: true }).then(({ file_info_list }) => {
        if (file_info_list.length > 0) {
          const { file_url, file_id } = file_info_list[0];
          this.stringValue = file_url;
          this.imageId = file_id;
        }
      });
    },
    handleClose() {
      this.$emit('update:visible', false);
    },
    confirm() {
      if (
        [
          'name',
          'editor',
          'category',
          'language',
          'topic',
          'reader',
          'publisher',
          'content_intro',
          'background',
          'author_intro',
          'content_count_YG',
          'word_count_YG',
          'plan_publish_date',
        ].includes(this.field)
      ) {
        this.$emit('updateProjectFieldValue', this.field, this.stringValue);
      }
      if (this.field === 'cover_image_file_url') {
        this.$emit('updateProjectFieldValue', 'cover_image_file_id', this.imageId);
      }
      if (this.field === 'label_list') {
        this.$emit('updateProjectFieldValue', this.field, this.arrayValue);
      }
      this.handleClose();
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-image {
  .avatar-uploader {
    :deep .el-upload {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 418px;
      height: 280px;
      margin: 0 auto;
      overflow: hidden;
      cursor: pointer;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;

      &:hover {
        border-color: #409eff;
      }
    }

    &-icon {
      width: 418px;
      height: 280px;
      font-size: 28px;
      line-height: 280px;
      color: #8c939d;
      text-align: center;
    }

    .avatar {
      display: block;
      max-width: 418px;
      max-height: 280px;
    }
  }
}

.label-input-content {
  display: flex;
  flex-direction: column;
  width: 420px;

  .label-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    padding: 12px 8px;
  }

  .el-input {
    flex: 1;
    min-width: 120px;
    margin-left: 6px;
  }
}
</style>
