<template>
  <el-form-item label="格式参考" label-position="top" style="margin-bottom: 20px">
    <el-upload
      style="width: 100%; height: 100%"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="(file: any, fileList: any) => uploadFile(fileList, '0')"
      accept=".doc,.docx,.txt,.pdf"
      :disabled="currentFile?.material?.loading || currentFile?.material?.name"
    >
      <div class="upload-click">
        <div class="left">
          <span v-if="currentFile?.material?.loading">
            <img src="@/assets/webapp/loading.svg" class="loading-img" alt=""  />
            上传中
          </span>
          <span v-else>
            {{ currentFile?.material?.name || '请上传' }}
          </span>
        </div>
        <div class="right" v-if="currentFile?.material?.name && !currentFile?.material?.loading" @click="handleDelMaterial">删除</div>
        <div class="right" :class="{'disabled': currentFile?.material?.loading}" v-else>上传文档</div>
      </div>
    </el-upload>
  </el-form-item>
  <el-form-item label="内容参考" label-position="top" style="margin-bottom: 20px">
    <el-upload
      style="width: 100%; height: 100%"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="(file: any, fileList: any) => uploadFile(fileList, '1')"
      accept=".doc,.docx,.txt,.pdf"
      :disabled="currentFile?.data?.loading || currentFile?.data?.name"
    >
      <div class="upload-click">
        <div class="left">
          <span v-if="currentFile?.data?.loading">
            <img src="@/assets/webapp/loading.svg" class="loading-img" alt=""  />
            上传中
          </span>
          <span v-else>
            {{ currentFile?.data?.name || '请上传' }}
          </span>
        </div>
        <div class="right" v-if="currentFile?.data?.name && !currentFile?.data?.loading" @click="handleDelData">删除</div>
        <div class="right" :class="{'disabled': currentFile?.data?.loading}" v-else>上传文档</div>
      </div>
    </el-upload>
  </el-form-item>
  <div style="font-weight: 400; font-size: 12px; color: #999999; line-height: 20px">
    * 文件仅支持word、pdf、txt，文件大小最多100M <br />
    * 补充参考文档并关联大纲信息将有助于提升文章质量。您也可以选择跳过，直接点击“生成文档”按钮
  </div>
</template>
<script setup lang="ts">
import { delReference, saveReference } from '@/api/writing'
import { MsgError, MsgSuccess } from '@/utils/message'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'

interface Props {
  value: string
}

const props = withDefaults(defineProps<Props>(), {})
const emit = defineEmits(['update:value'])


const currentFile: any = computed({
  get () {
    return props.value
  },
  set (val) {
    emit('update:value', val)
  }
})
// const material = ref({})
// const data = ref({})


const handleDelMaterial = async (e: any) => {
  try {
    e.stopPropagation()
    await delReference(currentFile.value.material?.id)
    ElMessage.success('删除成功！')
    currentFile.value.material = {};
  } catch (e) {
    ElMessage.error('删除失败！')
  }
}
const handleDelData = async (e: any) => {
  try {
    e.stopPropagation()
    await delReference(currentFile.value.data?.id)
    ElMessage.success('删除成功！')
    currentFile.value.data = {};
  } catch (e) {
    ElMessage.error('删除失败！')
  }
}

/**
 * 上传文件方法
 * @param fileList
 * @param type 文件类型 0 - 参考素材， 1 - 数据参考
 */
const uploadFile = async (fileList: any, type: any) => {
  const file = fileList[fileList.length -1];
  // 检查文件类型
  const allowedTypes = ['doc', 'docx', 'pdf', 'txt'];
  const fileExtension = file.name.split('.').pop()?.toLowerCase();
  if (!allowedTypes.includes(fileExtension)) {
    ElMessage.error('文件类型不支持，仅支持word、pdf、txt格式');
    return;
  }

  // 检查文件大小（100M = 100 * 1024 * 1024 字节）
  const maxSize = 100 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error('文件大小超过限制，最多支持100M');
    return;
  }
  if (type === '0') {
    if (currentFile.value.material?.loading) return;
    currentFile.value.material = {
      ...file,
      loading: true,
    }
  } else {
    if (currentFile.value.data?.loading) return;
    currentFile.value.data = {
      ...file,
      loading: true,
    }
  }
  try {

    const formData = new FormData();
    formData.append('file', file.raw)
    formData.append('file_name', file.name)
    formData.append('file_type', type)
    const result = await saveReference(formData)
    MsgSuccess('上传成功')
    if (type === '0') {
      currentFile.value.material = {
        ...currentFile.value.material,
        ...result.data,
        loading: false,
      }
    } else {
      currentFile.value.data = {
        ...currentFile.value.data,
        ...result.data,
        loading: false,
      }
    }
  } catch (e) {
    MsgError('上传失败')
    console.log(e)
  }
}
</script>
<style scoped lang="scss">
.upload-click {
  width: 100%;
  height: 34px;
  display: flex;
  background: #ffffff;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  align-items: center;
  justify-content: space-between;

  .left {
    margin-left: 12px;
    font-weight: 400;
    font-size: 12px;
    color: #8c8c8c;
    line-height: 20px;
    flex: 2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    .loading-img {
      width: 12px;
      height: 12px;
      position: relative;
      top: 2px;
    }
    @keyframes rotate {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
    .loading-img {
      animation: rotate 2s linear infinite;
    }
  }

  .right {
    margin-right: 12px;
    font-weight: 400;
    font-size: 12px;
    color: #3067ef;
    line-height: 20px;
    cursor: pointer;
  }
  .disabled {
    color: #888C87;
  }
}
</style>
