<!-- 通知配置详情 -->
<template>
  <PageContainer :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <Card>
      <Row>
        <Col :span="10">
          <Form layout="vertical">
            <FormItem label="通知方式" v-bind="validateInfos.type">
              <JSelect
                v-model:value="formData.type"
                placeholder="请选择通知方式"
                :disabled="_disabled"
                @change="handleTypeChange"
              >
                <SelectOption v-for="(item, index) in NOTICE_METHOD" :key="index" :value="item.value">
                  {{ item.label }}
                </SelectOption>
              </JSelect>
            </FormItem>
            <FormItem label="名称" v-bind="validateInfos.name">
              <Input v-model:value="formData.name" placeholder="请输入名称" />
            </FormItem>
            <FormItem label="类型" v-bind="validateInfos.provider" v-if="formData.type !== 'email'">
              <RadioCard :options="msgType" v-model="formData.provider" @change="handleProviderChange" :disabled="flag" />
            </FormItem>
            <!-- 钉钉 -->
            <template v-if="formData.type === 'dingTalk'">
              <template v-if="formData.provider === 'dingTalkMessage'">
                <FormItem label="AppKey" v-bind="validateInfos['configuration.appKey']">
                  <Input v-model:value="formData.configuration.appKey" placeholder="请输入AppKey" />
                </FormItem>
                <FormItem label="AppSecret" v-bind="validateInfos['configuration.appSecret']">
                  <Input v-model:value="formData.configuration.appSecret" placeholder="请输入AppSecret" />
                </FormItem>
              </template>
              <template v-if="formData.provider === 'dingTalkRobotWebHook'">
                <FormItem
                  label="webHook"
                  v-bind="validateInfos['configuration.url']"
                  :rules="[{ max: 64, message: '最多可输入64个字符' }]"
                >
                  <Input v-model:value="formData.configuration.url" placeholder="请输入webHook" />
                </FormItem>
              </template>
            </template>
            <!-- 微信 -->
            <template v-if="formData.type === 'weixin'">
              <FormItem label="corpId" v-bind="validateInfos['configuration.corpId']">
                <Input v-model:value="formData.configuration.corpId" placeholder="请输入corpId" />
              </FormItem>
              <FormItem label="corpSecret" v-bind="validateInfos['configuration.corpSecret']">
                <Input v-model:value="formData.configuration.corpSecret" placeholder="请输入corpSecret" />
              </FormItem>
            </template>
            <!-- 邮件 -->
            <template v-if="formData.type === 'email'">
              <FormItem label="服务器地址" v-bind="validateInfos['configuration.host']">
                <Space>
                  <AutoComplete
                    v-model:value="formData.configuration.host"
                    placeholder="请输入服务器地址"
                    style="width: 180px"
                    :options="[
                      {
                        label: 'smtp.163.com',
                        value: 'smtp.163.com'
                      },
                      {
                        label: 'pop.163.com',
                        value: 'pop.163.com'
                      },
                      {
                        label: 'smtp.exmail.qq.com',
                        value: 'smtp.exmail.qq.com'
                      },
                      {
                        label: 'pop.exmail.qq.com',
                        value: 'pop.exmail.qq.com'
                      },
                      {
                        label: 'smtp.qq.com',
                        value: 'smtp.qq.com'
                      },
                      {
                        label: 'pop.qq.com',
                        value: 'pop.qq.com'
                      },
                      {
                        label: 'smtpdm.aliyun.com',
                        value: 'smtpdm.aliyun.com'
                      },
                      {
                        label: 'smtp.126.com',
                        value: 'smtp.126.com'
                      },
                      {
                        label: 'pop.126.com',
                        value: 'pop.126.com'
                      }
                    ]"
                  />
                  <InputNumber v-model:value="formData.configuration.port" :precision="0" :min="1" :max="65535" />
                  <Checkbox v-model:checked="formData.configuration.ssl" @change="handleSslChange"> 开启SSL </Checkbox>
                </Space>
              </FormItem>
              <FormItem label="发件人" v-bind="validateInfos['configuration.sender']">
                <Input v-model:value="formData.configuration.sender" placeholder="username@domain.com" />
              </FormItem>
              <FormItem label="用户名" v-bind="validateInfos['configuration.username']">
                <Input v-model:value="formData.configuration.username" placeholder="请输入用户名" />
              </FormItem>
              <FormItem label="密码" v-bind="validateInfos['configuration.password']">
                <Input v-model:value="formData.configuration.password" placeholder="请输入密码" />
              </FormItem>
            </template>
            <!-- 语音/短信 -->
            <template v-if="formData.type === 'voice' || formData.type === 'sms'">
              <FormItem label="RegionId" v-bind="validateInfos['configuration.regionId']">
                <Select v-model:value="formData.configuration.regionId" placeholder="请选择RegionId">
                  <SelectOption v-for="(item, index) in regionList" :key="index" :value="item.value">
                    {{ item.label }}
                  </SelectOption>
                </Select>
              </FormItem>
              <FormItem label="AccessKeyId" v-bind="validateInfos['configuration.accessKeyId']">
                <Input v-model:value="formData.configuration.accessKeyId" placeholder="请输入AccessKeyId" />
              </FormItem>
              <FormItem label="Secret" v-bind="validateInfos['configuration.secret']">
                <Input v-model:value="formData.configuration.secret" placeholder="请输入Secret" />
              </FormItem>
            </template>
            <!-- webhook -->
            <template v-if="formData.type === 'webhook'">
              <FormItem label="Webhook" v-bind="validateInfos['configuration.url']">
                <Input v-model:value="formData.configuration.url" placeholder="请输入Webhook" />
              </FormItem>
              <FormItem label="请求头">
                <EditTable ref="editTable" :headers="formData.configuration.headers" />
              </FormItem>
            </template>
            <FormItem label="说明">
              <Textarea
                v-model:value="formData.description"
                show-count
                :maxlength="200"
                :rows="5"
                placeholder="请输入说明"
              />
            </FormItem>
            <FormItem>
              <Space>
                <JButton @click="close"> 取消 </JButton>
                <JButton type="primary" @click="handleSubmit" :loading="btnLoading"> 保存 </JButton>
              </Space>
            </FormItem>
          </Form>
        </Col>
        <Col :span="12" :push="2">
          <Doc :docData="formData" />
        </Col>
      </Row>
    </Card>
  </PageContainer>
</template>

<script setup lang="ts">
  import { getImage, onlyMessage } from '@jdlinker/utils';
  // @ts-ignore
  import {
    Card,
    Form,
    PageContainer,
    Select as JSelect,
    Row,
    Col,
    FormItem,
    SelectOption,
    Space,
    Button as JButton,
    Textarea,
    AutoComplete,
    InputNumber,
    Checkbox,
    Input
  } from 'linker-ui-components';
  import type { ConfigFormData } from '../types';
  import { NOTICE_METHOD, CONFIG_FIELD_MAP, MSG_TYPE } from '../../const';
  import regionList from './regionId';
  import EditTable from './components/EditTable.vue';
  import configApi from '../../../../api/notice/config';
  import Doc from './doc/index';
  import { ref, computed, watch, watchEffect } from 'vue';
  import { RadioCard } from '@jdlinker/ui';

  const emit = defineEmits(['close']);
  const useForm = Form.useForm;
  const flag = ref<boolean>(false);
  const editTable = ref();

  // 消息类型
  const msgType = ref([
    {
      label: '钉钉消息',
      value: 'dingTalkMessage',
      logo: getImage('/notice/dingtalk.png')
    },
    {
      label: '群机器人消息',
      value: 'dingTalkRobotWebHook',
      logo: getImage('/notice/dingTalk-rebot.png')
    }
  ]);

  // 表单数据
  const formData = ref<ConfigFormData>({
    configuration: {
      host: '',
      port: 25,
      ssl: false,
      sender: '',
      username: '',
      password: ''
    },
    description: '',
    name: '',
    provider: 'embedded',
    type: 'email'
  });

  const props = defineProps({
    id: {
      type: String,
      defult: ''
    },
    notifyType: {
      type: String,
      defult: ''
    }
  });

  // 根据通知方式展示对应的字段
  watch(
    () => formData.value.type,
    (val) => {
      msgType.value = MSG_TYPE[val];

      formData.value.provider = props.id ? formData.value.provider : msgType.value[0].value;
    }
  );

  // 验证规则
  const formRules = ref({
    type: [{ required: true, message: '请选择通知方式' }],
    name: [
      { required: true, message: '请输入名称' },
      { max: 64, message: '最多可输入64个字符' }
    ],
    provider: [{ required: true, message: '请选择类型' }],
    // 钉钉
    'configuration.appKey': [
      { required: true, message: '请输入AppKey', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符', trigger: 'change' }
    ],
    'configuration.appSecret': [
      { required: true, message: '请输入AppSecret', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符', trigger: 'change' }
    ],
    // 'configuration.url': [{ required: true, message: '请输入WebHook' }],
    // 微信
    'configuration.corpId': [
      { required: true, message: '请输入corpId', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符' }
    ],
    'configuration.corpSecret': [
      { required: true, message: '请输入corpSecret', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符' }
    ],
    // 阿里云语音/短信
    'configuration.regionId': [
      { required: true, message: '请输入RegionId', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符' }
    ],
    'configuration.accessKeyId': [
      { required: true, message: '请输入AccessKeyId', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符' }
    ],
    'configuration.secret': [
      { required: true, message: '请输入Secret', trigger: 'blur' },
      { max: 64, message: '最多可输入64个字符' }
    ],
    // 邮件
    // 'configuration.host': [{ required: true, message: '请输入服务器地址', trigger: 'blur' }],
    // 'configuration.sender': [
    //   { required: true, message: '请输入发件人', trigger: 'blur' },
    //   // { max: 64, message: '最多可输入64个字符' },
    //   {
    //     pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
    //     message: '请输入正确的邮箱',
    //   },
    // ],
    // 'configuration.username': [
    //   { required: true, message: '请输入用户名', trigger: 'blur' },
    //   { max: 64, message: '最多可输入64个字符' },
    // ],
    // 'configuration.password': [
    //   { required: true, message: '请输入密码', trigger: 'blur' },
    //   { max: 64, message: '最多可输入64个字符' },
    // ],
    // webhook
    'configuration.url': [
      { required: true, message: '请输入Webhook', trigger: 'blur' }
      // {
      //     pattern:
      //         /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[j-z]{2,6}\/?/,
      //     message: 'Webhook需要是一个合法的URL',
      // },
    ],
    description: [{ max: 200, message: '最多可输入200个字符' }]
  });

  const { validate, validateInfos } = useForm(formData.value, formRules.value);

  const getDetail = async () => {
    if (!props.id) return;
    const res = await configApi.detail(props.id as string);
    Object.assign(formData.value, res.result);
  };
  getDetail();

  /**
   * 通知方式改变
   */
  const handleTypeChange = () => {
    setTimeout(() => {
      formData.value.configuration = CONFIG_FIELD_MAP[formData.value.type][formData.value.provider];
      resetPublicFiles();
    }, 0);
  };

  const _disabled = computed(() => {
    return !!formData.value?.id || props.notifyType;
  });

  /**
   * 通知类型改变
   */
  const handleProviderChange = () => {
    formData.value.configuration = CONFIG_FIELD_MAP[formData.value.type][formData.value.provider];
    resetPublicFiles();
  };

  const handleSslChange = () => {
    formData.value.configuration.port = formData.value.configuration.ssl ? 465 : 25;
  };

  /**
   * 重置字段值
   */
  const resetPublicFiles = () => {
    switch (formData.value.provider) {
      case 'dingTalkMessage':
        formData.value.configuration.appKey = undefined;
        formData.value.configuration.appSecret = undefined;
        break;
      case 'dingTalkRobotWebHook':
        formData.value.configuration.url = undefined;
        break;
      case 'corpMessage':
        formData.value.configuration.corpId = undefined;
        formData.value.configuration.corpSecret = undefined;
        break;
      case 'embedded':
        formData.value.configuration.host = undefined;
        formData.value.configuration.port = 25;
        formData.value.configuration.ssl = false;
        formData.value.configuration.sender = undefined;
        formData.value.configuration.username = undefined;
        formData.value.configuration.password = undefined;
        break;
      case 'aliyun':
        formData.value.configuration.regionId = undefined;
        formData.value.configuration.accessKeyId = undefined;
        formData.value.configuration.secret = undefined;
        break;
      case 'aliyunSms':
        formData.value.configuration.regionId = undefined;
        formData.value.configuration.accessKeyId = undefined;
        formData.value.configuration.secret = undefined;
        break;
      case 'http':
        formData.value.configuration.url = undefined;
        formData.value.configuration.headers = [];
        break;
    }
  };

  /**
   * 表单提交
   */
  const btnLoading = ref<boolean>(false);
  const handleSubmit = () => {
    if (formData.value.type === 'webhook') {
      Promise.all([editTable.value.validate(), validate()])
        .then(async (result: any) => {
          formData.value.configuration.headers = result[0];
          btnLoading.value = true;
          let res;
          if (!formData.value.id) {
            res = await configApi.save(formData.value);
          } else {
            res = await configApi.update(formData.value);
          }
          if (res?.success) {
            onlyMessage('保存成功');
            close();
            // if (route.query?.notifyType) {
            //   // @ts-ignore
            //   if ((window as any).onTabSaveSuccess) {
            //     (window as any).onTabSaveSuccess(res.result);
            //     setTimeout(() => window.close(), 300);
            //   }
            // } else {
            //   router.back();
            // }
          }
        })
        .catch((err: any) => {
          console.log('err: ', err);
        })
        .finally(() => {
          btnLoading.value = false;
        });
    } else {
      validate()
        .then(async () => {
          btnLoading.value = true;
          let res;
          if (!formData.value.id) {
            res = await configApi.save(formData.value);
          } else {
            res = await configApi.update(formData.value);
          }
          if (res?.success) {
            onlyMessage('保存成功');
            close();
            // if (route.query?.notifyType) {
            //   // @ts-ignore
            //   if ((window as any).onTabSaveSuccess) {
            //     (window as any).onTabSaveSuccess(res.result);
            //     setTimeout(() => window.close(), 300);
            //   }
            // } else {
            //   router.back();
            // }
          }
        })
        .catch((err: any) => {
          console.log('err: ', err);
        })
        .finally(() => {
          btnLoading.value = false;
        });
    }
  };

  watchEffect(() => {
    if (props.notifyType) {
      formData.value.type = props.notifyType as string;
      if (props.notifyType === 'dingTalk') {
        formData.value.provider = 'dingTalkMessage';
        flag.value = true;
      } else {
        flag.value = false;
      }
      handleTypeChange();
    }
  });
  const close = () => {
    emit('close');
  };
</script>
