<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { Plus, CircleCloseFilled } from '@element-plus/icons-vue'
import { useFileDialog } from '@vueuse/core'
import { upload } from '@/utils/upload'
import { getExcelTotalLine, checkAutoGenerateData } from '../../api'
import { useAppConfig } from '@/composables/useAppConfig'
import { useEvent } from '../../composables/useQuestion'
const appConfig = useAppConfig()

defineEmits(['remove'])

const route = useRoute()

const modelValue: any = defineModel()

const formRef = ref<FormInstance>()
const form = reactive({
  questions: modelValue,
})

const { eventList } = useEvent(route.query.id as string)

const { files, open, reset } = useFileDialog({
  accept:
    '.csv, .xls, .xlsx, text/csv, application/csv,text/comma-separated-values, application/csv, application/excel,application/vnd.msexcel, text/anytext, application/vnd. ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  multiple: false,
})

let currentItem: any = null
function handleUpload(item: any) {
  currentItem = item
  open()
}

watchEffect(async () => {
  if (!files.value?.length) return
  const [file] = files.value
  const url = await upload(file)
  const res = await getExcelTotalLine({ file })
  const total = res.data.row_count || 0
  if (currentItem) {
    currentItem.answer.data.file = {
      name: file.name,
      size: file.size,
      type: file.type,
      is_download: false,
      total,
      url,
    }
  }
  reset()
})

const href = computed(() => {
  const dmlURL = appConfig.dmlURL || import.meta.env.VITE_DML_URL
  return `${dmlURL}/connect?experiment_id=${route.query.id}`
})

async function handleEventChange(item: any) {
  if (item.answer.data.type != 2) return
  const res = await checkAutoGenerateData({ experiment_id: route.query.id as string, event_id: item.answer.choose })
  item.answer.data.exists = res.data.exists
}

function handleDataTypeChange(item: any) {
  item.answer.rule.type = item.answer.data.type == 2 ? '3' : '1'
}

defineExpose({ formRef })
</script>

<template>
  <el-form ref="formRef" label-width="120px" :model="form" scroll-to-error>
    <el-card shadow="hover" :id="`site-card${index}`" class="box-card" v-for="(item, index) in modelValue" :key="item">
      <el-icon @click="$emit('remove', index)" v-if="modelValue.length > 1" class="close" size="28" color="#c01c40"
        ><CircleCloseFilled
      /></el-icon>
      <div class="head-box">
        <el-form-item
          label="本题分值"
          class="head-r"
          :prop="`questions.${index}.score`"
          :rules="{ required: true, message: '请输入' }">
          <el-input-number v-model="item.score" :min="0" :max="100" controls-position="right" />
        </el-form-item>
      </div>
      <el-form-item label="题目标题" :prop="`questions.${index}.title`" :rules="{ required: true, message: '请输入' }">
        <el-input v-model="item.title" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="题干内容">
        <el-input v-model="item.content" :rows="5" type="textarea" placeholder="请输入" />
      </el-form-item>
      <el-form-item
        label="选择事件"
        :prop="`questions.${index}.answer.choose`"
        :rules="{ required: true, message: '请输入' }">
        <el-select v-model="item.answer.choose" @change="handleEventChange(item)">
          <el-option v-for="item in eventList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件数据集">
        <div>
          <el-radio-group v-model="item.answer.data.type" @change="handleDataTypeChange(item)">
            <el-radio label="1">指定文件</el-radio>
            <el-radio label="2">自动生成</el-radio>
          </el-radio-group>
          <div class="form-item-box">
            <template v-if="item.answer.data.type == 1">
              <el-button :icon="Plus" size="large" @click="handleUpload(item)"></el-button>
              <template v-if="item.answer.data.file.url">
                <div class="file-info">
                  <p>{{ item.answer.data.file.name }}</p>
                  <p>总数据量：{{ item.answer.data.file.total }}条</p>
                </div>
                <el-button type="primary" plain @click="item.answer.data.file = {}">删除数据集</el-button>
              </template>
            </template>
            <template v-else>
              <a :href="href" target="_blank">
                <el-button type="primary">查看自动生成规则</el-button>
              </a>
              <el-alert
                title="该事件尚未维护自动生成数据规则，请维护！"
                type="info"
                style="margin-left: 40px"
                v-if="!item.answer.data.exists" />
            </template>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="评分规则">
        <el-radio-group v-model="item.answer.rule.type">
          <template v-if="item.answer.data.type == 1">
            <el-radio label="1">上传成功+数据量匹配</el-radio>
            <el-radio label="2">仅上传成功</el-radio>
          </template>
          <el-radio label="3">仅数据量匹配</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="答案解析" v-if="false">
        <el-input v-model="item.answer_analysis" :rows="5" type="textarea" placeholder="请输入" />
      </el-form-item>
    </el-card>
  </el-form>
</template>
<style lang="scss" scoped>
.close {
  position: absolute;
  top: -10px;
  right: -10px;
  cursor: pointer;
}
.box-card {
  padding-top: 20px;
  position: relative;
  margin-bottom: 30px;
  overflow: visible;
}
.head-box {
  display: flex;
  margin-bottom: 30px;
  .head-r {
    margin-left: auto;
  }
}

.form-item-box {
  display: flex;
  align-items: center;
  p {
    font-size: 13px;
    margin: 0 20px 0 10px;
    line-height: 1.4;
  }
}
</style>
