<template>
  <div class="add-kb-file-dialog">
    <el-dialog v-model="dialogVisible" title="知识库" width="1000px" align-center :show-close="false"
      @closed="() => { emit('update:modelValue', false) }">
      <el-form ref="formRef" style="max-width: 100%" :model="formData" label-width="auto" class="demo-dynamic">
        <el-form-item prop="name" label="知识库名称：">
          {{ formData.name }}
        </el-form-item>
        <el-form-item prop="description" label="知识库备注：">
          {{ formData.description }}
        </el-form-item>

        <el-form-item v-if="false" prop="" label="导入方式：">
          <div class="import-method">
            <el-radio-group v-model="formData.importMethod">
              <el-radio-button label="按文件类型导入" value="file" />
              <el-radio-button label="按模板导入" value="template" />
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item v-if="false" prop="" label="选择文件类型：" required>
          <div class="file-type">
            <div :class="formData.fileType === 'document' ? 'file-type-box active' : 'file-type-box'"
              @click="handleSelectFileType('document')">
              <div class="title"><el-icon size="24">
                  <Tickets />
                </el-icon>
                <i class="name" style="margin-left: 8px;">导入文本文档数据</i>
              </div>
              <div>根据上传的文本文件直接进行切分处理</div>
            </div>
            <div :class="formData.fileType === 'table' ? 'file-type-box active' : 'file-type-box'"
              @click="handleSelectFileType('table')">
              <div class="title">
                <i class="moxing1-icon"></i>
                <i class="name" style="margin-left: 10px;">导入表格型知识数据</i>
              </div>
              <div>
                读取表格中的文本信息，按行构建知识切片。更适用于含有长文的表格（表
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="fileList" label="上传文档：" required>
          <div class="file-upload">
            <el-upload ref="fileUploadRef" v-model:file-list="formData.fileList" class="upload-demo" :limit="100"
              :headers="{ Authorization: 'Beaver ' + getSessionVar('username') + ' ' + getSessionVar('session_id') }"
              :accept="formData.accept" drag :on-exceed="handleExceed" :on-preview="handlePreview"
              :before-upload="handleBeforeUpload" :on-error="handleUploadError" :on-remove="handleRemove"
              :before-remove="beforeRemove" :on-success="handleSuccess"
              :action="api.knowledgeBase + `${formData.id}/files/`" multiple name="files">
              <el-icon size="64" color="#2468F2"><upload-filled /></el-icon>
              <div class="el-upload__text">
                <p>将文档拖到此处，或<i style="color:#2468F2">点击上传</i></p>
                <p>
                  单次上传文档数量为100个；支持.doc/.txt/docx/.pdf/ppt/pptx/.md七种格式；.txt/.md文件不能超过
                  10MB，.pdf文件不能超过500MB且不能超过3000页，其他类型文件不能超过50MB且不能超过1000页
                </p>
              </div>
              <!-- <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500kb
                </div>
              </template> -->
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item prop="fileTableData" v-show="formData.fileTableData.length > 0">
          <div class="file-table" v-if="formData.fileTableData.length > 0">
            <el-table :data="formData.fileTableData" border table-layout="fixed"
              style="max-width: 100%;box-sizing: border-box;min-width: 0px;">
              <el-table-column label="导入文件标题" prop="file_name">
                <template #default="{ row, $index }">
                  <p :contenteditable="true" class="input-box" @blur="updateInputBox($event, $index, 'file_name')">{{
                    row.file_name }}</p>
                </template>
              </el-table-column>
              <el-table-column label="知识类型" prop="knowledge_type" width="210">
                <template #default="{ row }">
                  <!-- <p>{{ row.knowledge_type }}</p> -->
                  <el-select v-model="row.knowledge_type" placeholder="Select" style="width: 180px">
                    <el-option v-for="item in formData.knowledgeTypeOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="版本号" prop="version">
                <template #default="{ row, $index }">
                  <p :contenteditable="true" class="input-box" @blur="updateInputBox($event, $index, 'version')">{{
                    row.version }}</p>
                </template>
              </el-table-column>
              <el-table-column label="作者（主编）" prop="author">
                <template #default="{ row, $index }">
                  <p :contenteditable="true" class="input-box" @blur="updateInputBox($event, $index, 'author')">{{
                    row.author }}</p>
                </template>
              </el-table-column>

              <el-table-column label="年份" prop="year" width="80">
                <template #default="{ row, $index }">
                  <p :contenteditable="true" class="input-box" @blur="updateInputBox($event, $index, 'year', 'number')">
                    {{ row.year }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="100">
                <template #default>
                  <el-button link type="primary">
                    修改
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="formData.fileTableData.length === 0" @click="handleConfirm">
            确认
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { cloneDeep } from "lodash"
import { ref, watch, getCurrentInstance, toRaw } from "vue"
import { api } from "@/utils/config"
import { ElMessage } from 'element-plus'
import { getSessionVar, deleteSessionVar } from "@/utils/session";
const { proxy } = getCurrentInstance()

const props = defineProps({ modelValue: Boolean, knowledgeBase: Object })
const emit = defineEmits(['update:modelValue', 'updateFiles'])
const formData = ref({
  id: null, name: "",
  description: "",
  importMethod: 'file',
  fileType: 'document',//table,
  accept: ".doc,.txt,.docx,.pdf,.ppt,.pptx,.md",
  fileList: [],
  fileTableData: [],
  knowledgeTypeOptions: [
    { value: "中华医学会诊疗指南", label: "中华医学会诊疗指南" },
    { value: "规培十四五教材", label: "规培十四五教材" },
    { value: "临床路径", label: "临床路径" },
  ]
})
let dialogVisible = ref(false)
const handleCancel = () => {
  emit('update:modelValue', false)
}

const handleConfirm = () => {
  updateFiles()
}
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
}, { immediate: true })
watch(() => props.knowledgeBase, (newVal) => {
  // formData.value = cloneDeep(newVal) || {}
  Object.assign(formData.value, cloneDeep(newVal))
}, { immediate: true, deep: true })

const updateFiles = async () => {
  try {
    const data = await proxy.$http.put(api.batchUpdate, {
      files: formData.value.fileTableData
    })
    formData.value.fileTableData.slice(0, formData.value.fileTableData.length)
    proxy.$refs['formRef'].resetFields()
    proxy.$refs['fileUploadRef'].clearFiles()
    // console.log(formData.value.fileList, formData.value.fileTableData)
    emit('updateFiles')
    emit('update:modelValue', false)
  } catch (e) {
    console.log(e)
  }
}
function handleBeforeUpload(rawFile) {
  const size = rawFile.size / 1024 / 1024
  const nameList = rawFile.name.split('.')
  const type = nameList[nameList.length - 1]
  // console.log(size, type, rawFile)
  if (type === 'txt' || type === 'md') {
    if (size > 10) {
      ElMessage({
        message: `文件“${rawFile.name}”大于10MB`,
        type: 'warning',
      })
      return false
    }
  } else if (type === 'pdf') {

    if (size > 500) {
      ElMessage({
        message: `文件“${rawFile.name}”大于500MB`,
        type: 'warning',
      })
      return false
    }
  } else {
    if (size > 50) {
      ElMessage({
        message: `文件“${rawFile.name}”大于50MB`,
        type: 'warning',
      })
      return false
    }
  }
  // console.log(rawFile)
  return true
}
function handleUploadError(error, uploadFile, uploadFiles) {
  // console.log(error, uploadFile, uploadFiles)
  ElMessage.error(`文件"${uploadFile.name}"上传失败！`)
}
function updateInputBox(e, index, key, valueType = 'string') {
  let value = e.target.innerText || ""

  if (valueType === 'number') {
    value = Number(value)
  }
  // console.log(formData.value.fileTableData[index][key], e.target.innerText)
  formData.value.fileTableData[index][key] = value
}
const handleSelectFileType = (ftype) => {
  formData.value.fileType = ftype
}
const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}
const handleSuccess = (response, uploadFile, uploadFiles) => {
  const { data, message, code } = response
  if (code === 200) {
    formData.value.fileTableData.push(data[0])
    console.log("handleSuccess")
    emit('updateFiles')
  }
}
const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 100, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove = (uploadFile, uploadFiles) => {
  // return ElMessageBox.confirm(
  //   `Cancel the transfer of ${uploadFile.name} ?`
  // ).then(
  //   () => true,
  //   () => false
  // )
}
</script>

<style lang="less" scoped>
.add-kb-file-dialog {
  /deep/ .el-dialog {
    label {
      margin: 20px 0px 10px;
      display: block;
    }

    .dialog-footer {
      text-align: center;
      // gap: 40px;

      .el-button {
        padding: 19px 50px;
        margin-left: 50px;

        &:first-child {
          margin-left: 0px;
        }
      }
    }
  }

  /deep/ .el-form {
    .input-box {
      &:focus {
        outline: none;
      }
    }

    .el-textarea__inner,
    .el-input__wrapper {
      background-color: #F1F3F6;
    }

    .import-method {
      .el-radio-button {
        // margin: 10px 0px;
        padding: 2px;
        background: #E3E8F0;

        &:is(.is-active) {
          .el-radio-button__inner {
            background-color: white;
            color: #306FF3;
          }
        }

        &:first-child {
          border-radius: 10px 0px 0px 10px;
        }

        &:last-child {
          border-radius: 0px 10px 10px 0px;
        }

        .el-radio-button__inner {
          color: #859299;
          border-radius: 10px;
          background-color: transparent;
          border: none;
          padding: 10px 30px;
          box-shadow: none;
        }
      }
    }

    .file-type {
      display: flex;
      gap: 10px;

      .file-type-box {
        width: 250px;
        border: 1px solid #EDEDEF;
        padding: 10px;
        border-radius: 10px;

        &:is(.active) {
          border-color: #4B73F2;
          background-color: #EEF3FE;

          .title {
            .name {
              color: #4B73F2;
            }


          }
        }

        .title {
          display: flex;
          align-items: center;

          .name {
            color: #000;
          }
        }
      }
    }

    .file-table {
      flex: 1 1 auto;
    }
  }

  .moxing1-icon {
    width: 24px;
    height: 24px;
  }
}
</style>