<template>
  <DialogBox :title="dialogTitle" v-model="dialogVisible" width="600" :before-close="closeConfirm">
    <el-form
      ref="FormRef"
      :rules="rules"
      :model="formModel"
      label-position="top"
      require-asterisk-position="right"
    >
      <el-form-item label="">
        <el-input
          v-model="formModel.name"
          placeholder="请输入审核方案名称"
          :rows="8"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button @click.prevent="closeConfirm" :loading="loading"> 取消 </el-button>
        <el-button type="primary" @click="submitHandle" :loading="loading"> 确定 </el-button>
      </span>
    </template>
  </DialogBox>
</template>
<script setup lang="ts">
import { isFunction } from 'lodash-es'
import { ref, watch, reactive } from 'vue'
import { MsgSuccess, MsgError } from '@/utils/message'
import { saveReviewPlan, updateReviewPlan } from '@/api/review'

const emit = defineEmits(['refresh'])

const FormRef = ref()
const loading = ref(false)
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref('新建审核方案')
const formModel = ref<any>({
  name: ''
})
const item = ref<any>(null)

const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入审核方案名称',
      trigger: 'blur'
    }
  ]
})

watch(dialogVisible, (bool) => {
  if (!bool) {
    formModel.value = {
      name: ''
    }
    FormRef.value?.clearValidate()
    dialogVisible.value = false
    item.value = null
  }
})

const open = async (row?: any) => {
  if (row) {
    dialogTitle.value = '编辑审核方案'
    formModel.value.name = row.name
    item.value = row
  } else {
    dialogTitle.value = '新建审核方案'
  }
  dialogVisible.value = true
}

const submitHandle = async () => {
  try {
    const valid = await FormRef.value.validate()
    if (!valid) return false
    loading.value = true
    let res: any = null
    if (item.value && item.value.id) {
      res = await updateReviewPlan(item.value.id, { name: formModel.value.name })
    } else {
      res = await saveReviewPlan({ name: formModel.value.name })
    }
    if (res.status === '0') {
      MsgSuccess(item.value && item.value.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      emit('refresh')
    }
  } catch (e: any) {
    const msg: string = (e.response?.data?.detail) || (item.value && item.value.id ? '更新失败' : '创建失败')
    MsgError(msg)
  } finally {
    loading.value = false
  }
}

function closeConfirm(done: () => void) {
  return close(done)
}

function close(done: () => void) {
  isFunction(done) && done()
  dialogVisible.value = false
}

defineExpose({ open })
</script>
<style lang="scss" scope></style>
