<script setup lang='ts'>
import { useRouter, RouteLocationRaw } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { Grade, Subject } from '~/store/info'
import user from '~/store/user'
const token = user.token

import type { UploadProps, UploadUserFile } from 'element-plus'

const router = useRouter()
function routerPush(_route: RouteLocationRaw) {
  router.push(_route)
}

const UploadAction = window.GLOBAL_CONFIG.oss + '/upload/main/file'
function handleUploadSuccess(res: any, file: UploadUserFile, fileList: UploadUserFile[]) {
  file.p_url = '/' + res.data.url
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  dc_title: '',
  dc_grade_id: '',
  dc_subject_id: '',
  dc_keyword: '',
  dc_content: '',
  dc_files: [],
})

const rules = reactive<FormRules>({
  dc_title: [{ required: true, message: '标题不能为空', trigger: 'blur', }],
  dc_grade_id: [{ required: true, message: '年级不能为空', trigger: 'blur', }],
  dc_subject_id: [{ required: true, message: '科目不能为空', trigger: 'blur', }],
  dc_keyword: [{ required: true, message: '关键字不能为空', trigger: 'blur', }],
})

const submit_loading = ref(false)
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log('ruleForm : ', ruleForm)
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      submit_loading.value = true
      console.log('submit!')
      const dyaw_ctfx = Object.assign({}, ruleForm, {
        dc_grade_name: Grade.find((item) => item.grade_id === ruleForm.dc_grade_id)?.grade_name,
        dc_subject_name: Subject.find((item) => item.subject_id === ruleForm.dc_subject_id)?.subject_name,
        dc_files: ruleForm.dc_files.map((item) => item.p_url).join(';'),
        create_user_realname: user.user_realname,
      })

      request({
        url: '/dyaw/ctfx/add',
        data: {
          dyaw_ctfx,
        },
      }).then(
        res => {
          if (res.code === '1') {
            ElMessage.success('添加成功')
            router.back()
          } else {
            ElMessage.error(res.msg)
          }
        }
      ).catch(
        err => {
          ElMessage.error(err)
        }
      ).finally(
        () => {
          submit_loading.value = false
        }
      )
    } else {
      console.log('error submit!')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// TODO: 临时处理
function translateString(str: string) {
  return str.split('\n').map((item) => `<p>${item}</p>`).join('')
}
</script>

<template>
  <div class="w-1400px h-640px flex flex-col">
    <div class="flex justify-between">
      <div class="space-x-2 text-blue-700 flex items-center">
        <i:cil:home />
        <span>首页</span>
        <span>/</span>
        <span>错题分析</span>
        <span>/</span>
        <span>上传错题</span>
        <span>/</span>
        <span class="text-gray-600">新建</span>
      </div>
      <el-button type="primary" @click="router.back()">返回</el-button>
    </div>


    <el-form class="mt-8" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" size="large" status-icon>
      <el-form-item label="标题" prop="dc_title">
        <el-input v-model="ruleForm.dc_title" maxlength="20" show-word-limit />
      </el-form-item>
      <el-form-item label="年级" prop="dc_grade_id">
        <el-select clearable v-model="ruleForm.dc_grade_id">
          <el-option v-for="({ grade_id, grade_name }) in Grade" :key="grade_id" :label="grade_name" :value="grade_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="科目" prop="dc_subject_id">
        <el-select clearable v-model="ruleForm.dc_subject_id">
          <el-option v-for="({ subject_id, subject_name }) in Subject" :key="subject_id" :label="subject_name"
            :value="subject_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="关键字" prop="dc_keyword">
        <el-input v-model="ruleForm.dc_keyword" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="内容" prop="dc_content">
        <el-input v-model="ruleForm.dc_content" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" />
      </el-form-item>
      <el-form-item label="图片" prop="dc_files">
        <el-upload v-model:file-list="ruleForm.dc_files" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :action="UploadAction" name="filedata" :data="{ token, site: 'dyaw', }" :on-success="handleUploadSuccess">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="submit_loading" >
          完成
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
