<template>
  <div>
    <el-form ref="form" v-loading="loading" :model="form" :rules="fileAddRules" label-width="120px">
      <el-form-item label="标题：" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item v-if="type === 3" label="文件路径：" prop="archiveFiles">
        <file-upload
          :limit="20"
          :is-check="false"
          :list="fileList"
          :accept="'.docx,.pptx,.pdf'"
          :tip="'支持上传pdf、docx、pptx文件格式'"
          @change-loading="() => (loading = !loading)"
          @success="UploadSuccess($event)"
          @remove="HandleRemove($event)"
        />
      </el-form-item>
      <el-form-item v-if="type === 2" label="视频路径：" prop="archiveFiles">
        <file-upload
          :limit="20"
          :is-check="false"
          :list="fileList"
          :accept="'.mp4'"
          :tip="'支持上传.mp4文件格式'"
          @change-loading="() => (loading = !loading)"
          @success="UploadSuccess($event)"
          @remove="HandleRemove($event)"
        />
      </el-form-item>
      <el-form-item v-if="type === 1" label="图片路径：" prop="archiveFiles">
        <image-upload
          :limit="6"
          :image-list="fileList"
          @success="handleImageSuccess($event, 'textRelateds')"
          @remove="handleImageRemove($event, 'textRelateds')"
        />
      </el-form-item>
      <el-form-item v-if="type === 4" label="文本内容：" prop="content">
        <editor-input v-model="form.content" />
      </el-form-item>
      <el-form-item v-if="type === 5" label="话术内容：" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item label="用户阶段：" prop="stageStatus">
        <el-select v-model="form.stageStatus" placeholder="用户阶段">
          <el-option
            v-for="(i, index) in userClass"
            :key="index"
            :label="i.value"
            :value="i.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签：" prop="labelIds">
        <data-select :label-ids="labelIds" @handle-emit="handleSelect" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">提交</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import ImageUpload from '@/components/UploadImage/index.vue'
import FileUpload from '../../components/UploadFile.vue'
import databaseMixin from '../../mixins/index'
import EditorInput from '@/components/Editor/index.vue'
import dataSelect from '../../components/data-select.vue'
import { addContext, getContextDetail } from '@/api/contentLibrary/context'

export default {
  components: {
    ImageUpload,
    FileUpload,
    EditorInput,
    dataSelect
  },
  mixins: [databaseMixin],
  data() {
    return {
      form: {
        stageStatus: '',
        productArchiveId: 0,
        archiveFiles: [],
        labelIds: '123'
      },
      fileList: [],
      labelIds: [],
      loading: false,
      fileAddRules: {
        stageStatus: [
          {
            required: true,
            message: '选择用户阶段',
            trigger: 'blur'
          }
        ],
        archiveFiles: [
          {
            required: true,
            message: '请上传文件',
            trigger: 'change'
          }
        ],
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }
        ],
        labelIds: [
          {
            required: true,
            message: '请选择标签',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted() {
    if (this.tId) {
      this.getContextDetail()
    }
  },
  methods: {
    async getContextDetail() {
      const { data } = await getContextDetail({ id: this.tId })
      this.form = data
      const isArray = (a) => a?.indexOf(',') !== -1
      const k = isArray(data.keywords) ? data.keywords?.split(',') : [data.keywords]
      const v = isArray(data.labelIds) ? data.labelIds?.split(',') : [data.labelIds]
      this.labelIds = k?.map((e, i) => ({
        id: v[i],
        keyword: e
      }))
      this.fileList = data.type !== '1' ? data.archiveFiles : data.archiveFiles.map(e => ({
        uid: e.id,
        url: e.ossUrl,
        name: e.id,
        response: {
          data: e.ossUrl
        }
      }))
      console.log(this.labelIds)
    },
    HandleRemove(file) {
      console.log(file)
      this.form.archiveFiles = file.fileList
    },
    UploadSuccess(file) {
      console.log(file)
      this.form.archiveFiles = file.fileList
    },
    handleImageSuccess(file) {
      console.log(file)
      this.form.archiveFiles = file.fileList.map(e => ({
        ossUrl: e.response.data,
        fileName: e.name,
        ossName: e.name
      }))
    },
    handleImageRemove(file) {
      this.form.archiveFiles = file.fileList.map(e => ({
        ossUrl: e.response.data,
        fileName: e.name,
        ossName: e.name
      }))
    },
    submitForm(form) {
      this.$refs[form].validate(async valid => {
        if (valid) {
          try {
            console.log(this.form.content)
            const form = {
              stageStatus: this.form.stageStatus.toString(),
              type: this.type.toString(),
              archiveFiles: this.form.archiveFiles || [],
              productArchiveId: this.id,
              labelIds: this.form.labelIds,
              createBy: this.fullName,
              title: this.form.title,
              id: this.form.id || '',
              content: this.form.content || ''
            }
            const data = await addContext(form)
            if (data.code === 0) {
              this.$router.back()
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          } catch (error) {
            console.error(error)
          }
        }
      })
    },
    handleSelect(val) {
      console.log(val, '标签')
      this.form.labelIds = val.map(e => e.id).join(',')
      console.log(this.form.labelIds)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input,
::v-deep .el-textarea__inner {
  width: 500px;
}
::v-deep .el-form {
  width: 650px;
  margin: 20px auto;
}
</style>
