<script setup lang='ts'>
import { showFailToast, showSuccessToast } from 'vant'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Grade, Subject } from '~/store/info'
import { REQUEST } from '~/utils/request'

const props = defineProps<{
  id: string
}>()




const router = useRouter()


const ruleForm = reactive({
  dc_title: '',
  dc_grade_id: '',
  dc_subject_id: '',
  dc_keyword: '',
  dc_content: '',
  dc_files: '',
  //
  dc_grade_name: '',
  dc_subject_name: '',
})

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

const submit_loading = ref(false)

const submitForm = async () => {
  submit_loading.value = true
  console.log('submit!')
  const dyaw_ctfx = Object.assign({}, ruleForm, {
    dc_files: fileList.value?.map(item => `${item.res.origin}`).join(';'),
    dc_check: '0',
    dc_check_desc: ''
  })

  request({
    url: '/dyaw/ctfx/edit',
    data: {
      dc_id: props.id,
      dyaw_ctfx,
    },
  }).then(
    res => {
      if (res.code === '1') {
        showSuccessToast('编辑成功')
        router.back()
      } else {
        showFailToast(res.msg)
      }
    }
  ).catch(
    err => {
      showFailToast(err)
    }
  ).finally(
    () => {
      submit_loading.value = false
    }
  )
}


function onClickLeft() {
  router.back()
}

const showGradePicker = ref(false)
const showSubjectPicker = ref(false)

function onGradeConfirm({ selectedOptions }: {
  selectedOptions: {
    grade_id: string;
    grade_name: string;
  }[]
}) {
  ruleForm.dc_grade_id = selectedOptions[0]?.grade_id
  ruleForm.dc_grade_name = selectedOptions[0]?.grade_name
  showGradePicker.value = false
}

function onSubjectConfirm({ selectedOptions }: {
  selectedOptions: {
    subject_id: string;
    subject_name: string;
  }[]
}) {
  ruleForm.dc_subject_id = selectedOptions[0]?.subject_id
  ruleForm.dc_subject_name = selectedOptions[0]?.subject_name
  showSubjectPicker.value = false
}


const fileList = ref<unknown[]>([])
const afterRead = (fileProxy: any) => {
  fileProxy.status = 'uploading'
  fileProxy.message = '上传中...'
  const { file } = fileProxy
  REQUEST.upload({
    url: '/upload/main/file',
    data: { filedata: file },
  }).then((res) => {
    if (res?.code === '1') {
      // fileList.value.push(res.data)
      fileProxy.url = `${window.GLOBAL_CONFIG.oss}/${res.data.url}`
      fileProxy.res = {
        name: res.data.file_name,
        url: fileProxy.url,
        origin: res.data.url,
      }
      fileProxy.status = 'done'
      fileProxy.message = ''

    }
    else {
      fileProxy.status = 'failed'
      fileProxy.message = '上传失败'
    }
  }).catch((err) => {
    console.error(err)
    fileProxy.status = 'failed'
    fileProxy.message = '上传失败'
  })
}


await request({
  url: '/dyaw/ctfx/detail',
  data: {
    dc_id: props.id
  }
}).then(
  res => {
    if (res.code === "1") {
      const detail = res.data.one_info
      const keys = (Object.keys(ruleForm) as Array<keyof typeof ruleForm>)
      keys.forEach((key) => {
        if (key === 'dc_files') {
          fileList.value = !detail[key] ? [] : detail[key].split(';').map((p_url: string) => {
            return {
              url: window.GLOBAL_CONFIG.oss + p_url,
              res: {
                origin: p_url,
              }
            }
          })
        }
        ruleForm[key] = detail[key]
      })
    }
  }
)

</script>

<template>
  <div class="w-full h-full flex flex-col">
    <van-nav-bar title="错题详情" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-form class="px-2" @submit="submitForm">
      <van-cell-group inset>
        <van-field label="标题" prop="dc_title" v-model="ruleForm.dc_title" maxlength="20" show-word-limit
          :rules="rules.dc_title" required>
        </van-field>
        <van-field label="年级" prop="dc_grade_id" v-model="ruleForm.dc_grade_name" is-link readonly
          @click="showGradePicker = true" :rules="rules.dc_grade_id" required></van-field>
        <van-popup v-model:show="showGradePicker" position="bottom">
          <van-picker :columns="Grade"
            :columns-field-names="{ text: 'grade_name', value: 'grade_id', children: 'children' }"
            @confirm="onGradeConfirm" @cancel="showGradePicker = false" />
        </van-popup>
        <van-field label="科目" prop="dc_subject_id" v-model="ruleForm.dc_subject_name" is-link readonly
          @click="showSubjectPicker = true" :rules="rules.dc_subject_id" required></van-field>
        <van-popup v-model:show="showSubjectPicker" position="bottom">
          <van-picker :columns="Subject"
            :columns-field-names="{ text: 'subject_name', value: 'subject_id', children: 'children' }"
            @confirm="onSubjectConfirm" @cancel="showSubjectPicker = false" />
        </van-popup>
        <van-field label="关键字" prop="dc_keyword" v-model="ruleForm.dc_keyword" maxlength="10" show-word-limit
          :rules="rules.dc_keyword" required>
        </van-field>
        <van-field label="内容" prop="dc_content" v-model="ruleForm.dc_content" rows="3" autosize type="textarea">
        </van-field>
        <van-field label="图片" prop="dc_files">
          <template #input>
            <van-uploader v-model="fileList" multiple :after-read="afterRead">
            </van-uploader>
          </template>
        </van-field>
      </van-cell-group>
      <div class="mt-8">
        <van-button round block type="primary" native-type="submit" :loading="submit_loading">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
