<script setup lang="ts">
import { saveReference } from '@/api/review'
import router from '@/router'
import { MsgError, MsgSuccess } from '@/utils/message'
import { AiEditor } from 'aieditor'
import { ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { onMounted, ref } from 'vue'
import 'aieditor/dist/style.css'
import RuleItem from './components/RuleItem.vue'
import AuditLoading from './components/AuditLoading.vue'
import { useRoute } from 'vue-router'
import { defaultRuleItem } from '@/views/smart/review/extraction/config'


import useStore from '@/stores'

const { docs } = useStore()
const { query } = useRoute()

let aiEditor
const pageTitle = ref('')
const editorRef: any = ref(null)
const loading = ref<boolean>(false)

onMounted(() => {
  aiEditor = new AiEditor({
    element: editorRef.value as Element,
    placeholder: '在左侧使用AI生成文章或直接输入文字',
    toolbarKeys: [
      'undo',
      'redo',
      'eraser',
      'heading',
      'font-size',
      'bold',
      'italic',
      'strike',
      'underline',
      'font-family',
      'font-color',
      'align',
      'bullet-list',
      'ordered-list',
      'indent-decrease',
      'indent-increase'
    ]
  })
})

const back = () => {
  router.go(-1)
}
const download = () => {
  router.go(-1)
}
const saveDocument = () => {
  router.go(-1)
}

// true 显示配置 false 显示结果
const activeTab = ref<number>(0)

const fileList = ref<any[]>([])

/**
 * 上传文件方法
 * @param file 上传的文件
 * @param files 文件列表
 */
const uploadFile = async (file: any, files: any[]) => {
  // 检查文件数量
  if (files.length > 10) {
    ElMessage.error('一次最多上传10个文件')
    return false
  }

  // 检查文件类型
  const allowedTypes = ['doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx']
  const invalidFiles = files.filter((f) => {
    const ext = f.name.split('.').pop()?.toLowerCase()
    return !allowedTypes.includes(ext)
  })

  if (invalidFiles.length > 0) {
    ElMessage.error(`不支持的文件类型: ${invalidFiles.map((f) => f.name).join(', ')}`)
    return false
  }

  // 检查文件大小（50M = 50 * 1024 * 1024 字节）
  const maxSize = 50 * 1024 * 1024
  const oversizedFiles = files.filter((f) => f.size > maxSize)

  if (oversizedFiles.length > 0) {
    ElMessage.error(`文件大小超过限制: ${oversizedFiles.map((f) => f.name).join(', ')}`)
    return false
  }

  fileList.value = files.map((f) => ({
    ...f,
    loading: true
  }))

  try {
    const formData = new FormData()
    files.forEach((f) => {
      formData.append('files[]', f.raw)
      formData.append('file_names[]', f.name)
    })

    const result = await saveReference(formData)
    MsgSuccess(`成功上传${files.length}个文件`)
    fileList.value = files.map((f, i) => ({
      ...f,
      ...result.data[i],
      loading: false
    }))
  } catch (e) {
    MsgError('上传失败')
    console.error(e)
  }
  return false
}
// 重新上传
const refreshFile = (item: any) => {}
// 删除文档
const deleteFile = (item: any) => {}
const result: any = ref({
  documentId: '',
  rules: [],
})

// 切换结果页面文档id
const handleChangeDocument = () => {

}
// 开始审核
const handleCreate = () => {
  docs.setAuditLoadingStatus('')
  docs.setAuditLoadingText('AI正在审核中')
  setTimeout(() => {
    docs.setAuditLoadingText('')
    activeTab.value = 1;
    result.value.rules = cloneDeep(formData.value.rules)
  }, 2000)
}

const formData = ref({
  extractionScheme: 0,
  history: null,
  name: '',
  sceneText: '',
  rules: [
    {
      name: '',
      description: ''
    }
  ]
})
// 根据描述生成规则
const handleCreateRule = (i: number) => {
}
// 添加规则
const handleAddRule = (type: any) => {
  if (type === 0) {
    formData.value.rules.push(defaultRuleItem)
    return;
  }
  result.value.rules.push(defaultRuleItem)
}
// 删除规则
const handleDeleteRule = (i: number, type: number) => {
  if (type === 0) {
    formData.value.rules.splice(i, 1)
    return;
  }
  result.value.rules.splice(i, 1)
}

</script>

<template>
  <div class="extraction-container">
    <div class="header">
      <div class="left-action">
        <el-icon @click="back" class="pointer" style="margin-right: 12px">
          <ArrowLeftBold />
        </el-icon>
        <span>{{ pageTitle }}</span>
      </div>
      <el-space :size="20">
        <el-button type="primary" style="width: 80px" @click="download">下载</el-button>
        <el-button type="primary" style="width: 80px" @click="saveDocument">导入规则库</el-button>
      </el-space>
    </div>
    <section class="container">
      <div class="editor container-left editor-content" ref="editorRef" style="height: 100%" />
      <div class="container-right">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="抽取配置" :name="0"></el-tab-pane>
          <el-tab-pane label="结果预览" :name="1"></el-tab-pane>
        </el-tabs>
        <div class="container-right-content" v-show="activeTab === 0">
          <el-form :model="formData" label-position="top">
            <el-form-item label="上传文档">
              <el-upload
                style="width: 100%; height: 100%"
                action="#"
                :auto-upload="false"
                :multiple="true"
                :show-file-list="false"
                :on-change="uploadFile"
                :before-upload="() => false"
                accept=".doc,.docx,.txt,.pdf,.xls,.xlsx,.ppt,.pptx"
                :limit="10"
                :on-exceed="() => ElMessage.error('最多上传10个文件')"
                :disabled="fileList.some((f) => f.loading)"
              >
                <div class="container-right-content-upload">
                  <el-space class="container-right-content-upload-button">
                    <img src="@/assets/webapp/upload.svg" alt="" />
                    上传
                  </el-space>
                </div>
              </el-upload>
            </el-form-item>
            <div
              style="
                font-weight: 400;
                font-size: 12px;
                color: #999999;
                line-height: 20px;
                margin-bottom: 20px;
              "
            >
              * 上传文件支持word、pdf，大小不超过50M，一次至多上传10个文件
            </div>
            <div class="file-list">
              <div class="file-list-item" v-for="(v, i) in fileList" :key="i">
                <div class="file-list-item-top">
                  <div class="file-list-item-top-left">
                    <el-icon><Document /></el-icon>
                    {{ v.name }}
                  </div>
                  <div class="file-list-item-top-right">
                    <el-icon @click="refreshFile(v)"><RefreshRight /></el-icon>
                    <el-icon @click="deleteFile(v)"><CloseBold /></el-icon>
                  </div>
                </div>
                <div class="file-list-item-bottom">
                  <el-progress
                    indeterminate
                    :percentage="50"
                    :stroke-width="2"
                    :show-text="false"
                  />
                </div>
              </div>
            </div>
            <el-form-item label="抽取方案">
              <el-radio-group v-model="formData.extractionScheme">
                <el-radio :value="0">智能生成</el-radio>
                <el-radio :value="1">自定义</el-radio>
                <el-radio :value="2">选择历史方案</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="历史方案" v-if="formData.extractionScheme === 2">
              <el-select placeholder="请输入" v-model="formData.history">
                <el-option value="1">建筑施工审查抽取方案</el-option>
                <el-option value="2">建筑施工审查抽取方案1</el-option>
                <el-option value="3">建筑施工审查抽取方案2</el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="抽取方案名称">
              <el-input v-model="formData.name" placeholder="请输入抽取方案名称" />
            </el-form-item>
            <el-form-item>
              <template #label>
                <el-row>
                  <el-col :span="12">
                    <span style="color: red">*</span>
                    抽取场景
                  </el-col>
                  <el-col :span="12" class="pointer" @click="handleCreateRule" style="color: #3067ef; text-align: right">
                    生成抽取规则
                  </el-col>
                </el-row>
              </template>
              <el-input
                v-model="formData.sceneText"
                type="textarea"
                :rows="7"
                show-word-limit
                maxlength="1000"
              />
            </el-form-item>
            <el-form-item>
              <template #label>
                抽取规则
                <span style="color: red">*</span>
              </template>
              <RuleItem
                v-for="(v, i) in formData.rules"
                :key="i"
                v-model:name="v.name"
                v-model:description="v.description"
                :index="i"
                @del="() => handleDeleteRule(i, 0)"
              />
              <div class="add-rules pointer" @click="handleAddRule(0)">
                <el-icon style="margin-right: 4px"><Plus /></el-icon>
                添加规则
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="container-right-content" v-show="activeTab === 1">
          <el-select placeholder="请选择" style="width: 100%; margin-bottom: 20px; margin-top: 8px" v-model="result.documentId" @click="handleChangeDocument">
            <el-option :value="0">全部文档</el-option>
            <el-option :value="1">文档1</el-option>
            <el-option :value="2">文档2</el-option>
            <el-option :value="3">文档3</el-option>
            <el-option :value="4">文档4</el-option>
            <el-option :value="5">文档5</el-option>
            <el-option :value="6">文档6</el-option>
            <el-option :value="7">文档7</el-option>
            <el-option :value="8">文档8</el-option>
            <el-option :value="9">文档9</el-option>
            <el-option :value="10">文档10</el-option>
          </el-select>
          <div class="container-right-content-list">
            <RuleItem
              v-for="(v, i) in result.rules"
              :key="i"
              v-model:name="v.name"
              v-model:description="v.description"
              :index="i"
              @del="() => handleDeleteRule(i, 1)"
            />
            <div class="add-rules pointer" @click="handleAddRule(1)">
              <el-icon style="margin-right: 4px"><Plus /></el-icon>
              添加规则
            </div>
          </div>
        </div>
        <div style="width: 100%; text-align: right; display: flex; gap: 5px" v-if="activeTab === 0">
          <el-button style="flex: 1" @click="handleCreate">保存配置</el-button>
          <el-button style="flex: 1" type="primary" @click="handleCreate">开始审核</el-button>
        </div>
      </div>
    </section>
    <AuditLoading @refresh="handleCreate" />
  </div>
</template>

<style scoped lang="scss">
.extraction-container {
  width: 100%;
  height: 100vh;
  background: #f4f8ff;
  position: relative;

  .header {
    height: 60px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    border-radius: 24px 24px 0 0;
    padding-left: 32px;
    padding-right: 28px;

    .left-action {
      font-size: 18px;
      font-weight: bold;
      width: 70%;
      align-items: center;
      display: flex;
    }
  }

  .container {
    padding-top: 20px;
    padding-bottom: 20px;
    padding-left: 20px;
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    &-left {
      width: 70%;
      // todo 暂时使用  后期去除
      .aie-container {
        border-radius: 20px;
        position: relative;

        .text-count {
          width: calc(100% - 20px);
          height: 50px;
          line-height: 50px;
          background: #fff;
          position: absolute;
          left: 10px;
          bottom: 0;
          font-weight: 400;
          font-size: 14px;
          color: #999999;
          z-index: 100;
        }

        .editor-result-status {
          position: absolute;
          z-index: 1000;
          width: calc(100% - 120px);
          left: 55px;
          background: #fff;
        }

        .mask {
          position: absolute;
          width: 100%;
          height: 100%;
          z-index: 100;
        }
      }
    }

    &-right {
      width: 30%;
      padding: 20px 20px 0 20px;
      display: flex;
      flex-direction: column;

      &-title {
        font-weight: 600;
        font-size: 16px;
        color: #333333;

        margin-bottom: 21px;
        .desc {
          font-weight: 400;
          font-size: 12px;
          color: #666666;
          padding-bottom: 8px;
          border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }
      }

      &-content {
        flex: 1;
        overflow: auto;
        &-upload,
        .audit-config {
          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;
          &-button {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 400;
            font-size: 12px;
            color: #3067ef;
          }
          .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;
          }
        }
        .audit-config {
          padding-left: 12px;
        }
        &-list {
          display: flex;
          flex-direction: column;
          height: calc(100% - 51px);
          overflow-y: auto;
          box-sizing: border-box;
          & > .rule-item {
            width: auto;
          }
        }
        .add-rules {
          width: 100%;
          margin-top: 10px;
          height: 24px;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #3067ef;
        }
        .file-list {
          margin-bottom: 36px;
          &-item {
            margin-bottom: 16px;
            &-top {
              display: flex;
              flex-direction: row;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 4px;
              &-left {
                flex: 2;
                font-weight: 400;
                font-size: 12px;
                color: #666666;
                .el-icon {
                  position: relative;
                  top: 2px;
                  margin-right: 4px;
                }
              }
              &-right {
                text-align: right;
                .el-icon {
                  font-size: 14px;
                  color: #8c8c8c;
                }
                .el-icon:first-child {
                  margin-right: 13px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.extraction-container {
  .pointer {
    cursor: pointer;
  }
  .el-upload {
    width: 100% !important;
  }
}
</style>
