<template>
  <Dialog title="邀约报备" v-model="show" width="600px">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="0">
      <el-form-item prop="remarkContent">
        <el-input
          type="textarea"
          placeholder="请输入报备信息"
          v-model="form.remarkContent"
          :autosize="{ minRows: 10 }"
        />
      </el-form-item>
      <el-form-item prop="groupId">
        <el-select v-model="form.groupId" placeholder="选择群聊发送报备信息并@区域" filterable>
          <el-option
            v-for="item in groupOptions"
            :key="item.groupId"
            :label="item.groupName"
            :value="item.groupId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="handleSave">提 交</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup>
import { getWxGroupSimpleList, getClueRemarkByClueId, reportClue } from '@/api/clue/clueRemark'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const form = ref({
  remarkContent: '',
  groupId: ''
})
const rules = {
  remarkContent: [{ required: true, message: '请输入报备信息', trigger: 'blur' }],
  groupId: [{ required: true, message: '请选择群聊', trigger: 'change' }]
}
const formLoading = ref(false)

const show = ref(false)
async function open(row) {
  show.value = true
  // 查询群聊
  getOptions()

  // 查询报备信息
  const data = await getClueRemarkByClueId({ clueId: row.clueId })
  if (data && data.remarkId) {
    form.value = { ...data }
    return
  }

  form.value.clueId = row.clueId
  let remarkInfo = `学员姓名：${row.name}\n联系方式：${row.phone}\n意向班型：`
  if (row.diyParams?.licenseType) {
    remarkInfo += `${row.diyParams.licenseType}\n`
  } else {
    remarkInfo += `\n`
  }
  const name = userStore.getUser.nickname.substring(0, 1)
  remarkInfo += `意向成交价：\n邀约时间：\n邀约人：${name}教练\n备注：`
  form.value.remarkContent = remarkInfo
}

defineExpose({ open })

const groupOptions = ref([])

function getOptions() {
  getWxGroupSimpleList().then((response) => {
    groupOptions.value = response
  })
}

const formRef = ref(null)
function handleSave() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      formLoading.value = true
      try {
        const data = await reportClue(form.value)
        message.success(data)
      } catch (error) {
        console.error('提交报备信息失败', error)
      } finally {
        formLoading.value = false
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}
</script>

<style lang="scss" scoped></style>
