<template>
  <a-space direction="vertical" fill>
    <a-alert
      >配置获取方式请查看公司邮箱提供商说明，例如<a-link
        href="https://work.weixin.qq.com/help?person_id=0&doc_id=431&helpType=exmail"
        target="_blank"
        >查看腾讯企业邮箱</a-link
      ></a-alert
    >
    <div style="text-align: right">
      <a-space>
        <c-pop-confirm
          v-if="userStore.permissions['sys_notify_channel_del'] && !isEdit"
          @ok="handleDel"
        >
          <template #content> 请再次确认是否删除 </template>
          <a-button type="primary" status="danger">删除</a-button>
        </c-pop-confirm>

        <a-button :type="isEdit ? undefined : 'primary'" @click="isEdit = !isEdit">{{
          isEdit ? '取消' : '编辑'
        }}</a-button>
        <c-button type="primary" @click="handleSubmit" v-if="isEdit">保存</c-button></a-space
      >
    </div>
    <c-descriptions v-if="!isEdit" v-model="form" :option="mailOption"></c-descriptions>
    <c-form ref="formRef" v-model="form" v-else :option="mailOption"> </c-form
  ></a-space>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { isUndefined } from 'lodash'
import mailOption from './mail-option'
import { notifyChannelType } from '@/enums/upms/notify-channel-type'
import { SysNotifyChannel } from '@/entity/upms/notify-channel'
import { editConfig } from '@/api/upms/notify-channel'
import { useUserStore } from '@/store/user'

const props = defineProps<{
  type: notifyChannelType
  entity: SysNotifyChannel
}>()

const userStore = useUserStore()

const form = ref({})
const formRef = ref()

watch(
  () => props.entity,
  () => {
    form.value = isUndefined(props.entity) ? {} : props.entity
  }
)

const isEdit = ref(false)

const toEdit = (val: string, done: Function) => {
  editConfig({
    type: props.type,
    config: val
  })
    .then(() => {
      done()
      Message.success(val === '' ? '删除成功' : '保存成功')
      if (val === '') {
        form.value = {}
      }
    })
    .catch(() => {
      done(false)
    })
}
const handleSubmit = (done: Function) => {
  formRef.value
    .submit()
    .then((res: any) => {
      toEdit(JSON.stringify(res.form), (flag: boolean) => {
        done()
        if (flag !== false) {
          form.value = res.form
          isEdit.value = false
        }
        res.done()
      })
    })
    .catch(() => {
      done()
    })
}

const handleDel = (done: Function) => {
  toEdit('', done)
}
</script>
