<template>
  <a-form :model="formState" name="basic" layout="vertical" autocomplete="off" ref="FormRef">
    <NodeHead nodeName="基础信息" class="basic-title" />
    <div class="flex-center">
      <a-form-item
        label="模板编号"
        name="code"
        :rules="[{ required: true, message: '请填写模板编号!' }]"
      >
        <a-input v-model:value="formState.code" placeholder="请填写" />
      </a-form-item>

      <a-form-item
        label="模板名称"
        name="name"
        :rules="[{ required: true, message: '请填写模板名称!' }]"
      >
        <a-input v-model:value="formState.name" placeholder="请填写" />
      </a-form-item>
    </div>
    <div class="flex-center">
      <a-form-item
        label="模板类型"
        name="templateType"
        :rules="[{ required: true, message: '请填写模板类型!' }]"
      >
        <a-select
          :value="formState.templateType"
          style="width: 100%"
          :options="templateTypeOptions"
          @change="changeTemplateTypeOptions"
        />
      </a-form-item>

      <a-form-item
        label="消息类型"
        name="messageType"
        :rules="[{ required: true, message: '请填写消息类型!' }]"
      >
        <a-select
          :value="formState.messageType"
          style="width: 100%"
          :options="messageTypeOptions"
          @change="changeMessageTypeOptions"
        />
      </a-form-item>
    </div>
    <div class="flex-center">
      <a-form-item label="状态" name="enabledMark">
        <a-switch v-model:checked="formState.enabledMark" :checkedValue="1" />
      </a-form-item>

      <a-form-item label="排序" name="sortCode">
        <a-input v-model:value="formState.sortCode" placeholder="请填写" />
      </a-form-item>
    </div>
    <a-form-item label="备注" name="remark" :rules="[{ required: true, message: '请填写备注!' }]">
      <a-textarea v-model:value="formState.remark" placeholder="请填写备注" />
    </a-form-item>
  </a-form>
  <div class="config-box">
    <div class="config-item mr-4">
      <NodeHead nodeName="参数配置" class="basic-title" />
      <div class="config-content">
        <div :class="prefixCls">
          <a-table
            :dataSource="configure.data"
            :columns="configure.columns"
            :pagination="false"
            size="middle"
          >
            <template #headerCell="{ column }">
              <div class="header-cell__custom-title">{{ column.title }}</div>
            </template>
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'name'">
                <a-input
                  v-model:value="record.name"
                  :placeholder="t('参数名称')"
                  @blur="handleBlurField(record, 'name')"
                />
              </template>
              <template v-if="column.key === 'description'">
                <a-input v-model:value="record.description" :placeholder="t('参数描述')" />
              </template>
              <template v-if="column.key === 'operation'">
                <a-popconfirm @confirm="deleteItem(index)">
                  <template #title>
                    <p>{{ t('删除参数') }}</p>
                  </template>
                  <div class="text-[#FF5461]">删除</div>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
          <div class="new-button" @click="addItem">新增</div>
        </div>
      </div>
    </div>
    <div class="config-item ml-4">
      <NodeHead nodeName="消息内容配置" class="basic-title" />
      <div class="config-content">
        <a-form
          :model="messageContent"
          name="messageContent"
          :label-col="{ style: { width: '80px' } }"
          labelAlign="left"
          :wrapper-col="{ style: { width: 'calc(100% - 80px)' } }"
          autocomplete="off"
          ref="MessageContentFormRef"
        >
          <!-- 短信配置 -->
          <div v-if="formState.messageType == MessageType.SMS">
            <a-form-item
              label="模板编号"
              name="templateCode"
              :rules="[{ required: true, message: '请填写模板编号!' }]"
            >
              <a-input v-model:value="messageContent.templateCode" placeholder="请填写模板编号" />
            </a-form-item>
          </div>
          <!-- 微信公众号 -->
          <div v-else-if="formState.messageType == MessageType.WE_CHAT">
            <a-form-item
              label="模板编号"
              name="templateCode"
              :rules="[{ required: true, message: '请填写模板编号!' }]"
            >
              <a-input v-model:value="messageContent.templateCode" placeholder="请填写模板编号" />
            </a-form-item>
            <a-form-item
              label="小程序ID"
              name="appKey"
              :rules="[{ required: true, message: '请填写小程序ID!' }]"
            >
              <a-input v-model:value="messageContent.appKey" placeholder="请填写小程序ID" />
            </a-form-item>
          </div>
          <!-- 系统消息 -->
          <div v-else-if="formState.messageType == MessageType.SYSTEM">
            <a-textarea
              v-model:value="messageContent.content"
              :auto-size="{ minRows: 8, maxRows: 10 }"
              placeholder="请输入消息内容，参数用{}进行使用，例如：{CompanyName}有一条新的通知，请注意查看。"
            />
          </div>
          <!-- 其他 -->
          <div v-else>
            <a-form-item
              label="消息标题"
              name="title"
              :rules="[{ required: true, message: '请填写消息标题!' }]"
            >
              <a-input v-model:value="messageContent.title" placeholder="请填写消息标题" />
            </a-form-item>
            <a-form-item
              label="消息内容"
              name="content"
              :rules="[{ required: true, message: '请填写消息内容!' }]"
            >
              <a-textarea
                v-model:value="messageContent.content"
                :auto-size="{ minRows: 8, maxRows: 10 }"
                placeholder="请输入消息内容，参数用{}进行使用，例如：{CompanyName}有一条新的通知，请注意查看。"
              />
            </a-form-item>
          </div>
        </a-form>
        <div
          :class="prefixCls"
          v-if="
            formState.messageType == MessageType.SMS || formState.messageType == MessageType.WE_CHAT
          "
        >
          <a-table
            :dataSource="messageContent.configs"
            :columns="messageContentConfigColumns"
            :pagination="false"
            size="middle"
          >
            <template #headerCell="{ column }">
              <div class="header-cell__custom-title">{{ column.title }}</div>
            </template>
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'variable'">
                <a-input
                  style="width: 120px"
                  v-model:value="record.variable"
                  :placeholder="t('变量')"
                  @blur="handleBlurField(record, 'variable')"
                />
              </template>
              <template v-if="column.key === 'parameter'">
                <a-select
                  v-model:value="record.parameter"
                  :options="configure.data"
                  style="width: 120px"
                  :field-names="{ label: 'name', value: 'name', options: 'children' }"
                  :placeholder="t('消息参数')"
                />
              </template>
              <template v-if="column.key === 'operation'">
                <a-popconfirm @confirm="deleteConfigItem(index)">
                  <template #title>
                    <p>{{ t('删除参数') }}</p>
                  </template>
                  <div class="text-[#FF5461]">删除</div>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
          <div class="new-button" @click="addConfigItem">新增</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { useI18n } from '/@/hooks/web/useI18n';
  import { MessageType } from '/@/enums/messageTemplate';
  import { ColumnProps } from 'ant-design-vue/lib/table/Column';
  import { getDicDetailList } from '/@/api/system/dic';
  import { MessageTemplateCategory } from '/@/enums/messageTemplateEnum';
  import { onMounted, reactive, ref } from 'vue';
  import {
    ConfigureItem,
    MessageContent,
    MessageTemplateForm,
  } from '/@/model/generator/messageTemplate';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getInfo } from '/@/api/system/generator/messageTemplate';
  import { cloneDeep } from 'lodash-es';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useDesign } from '/@/hooks/web/useDesign';
  const { prefixCls } = useDesign('basic-table');
  const { t } = useI18n();
  const { notification } = useMessage();
  const FormRef = ref();
  const MessageContentFormRef = ref();
  const props = withDefaults(
    defineProps<{
      editId: string;
    }>(),
    {
      editId: '',
    },
  );
  let templateTypeOptions = ref<
    Array<{
      value: string;
      label: string;
    }>
  >([]);
  const formState = reactive<MessageTemplateForm>({
    id: '',
    code: '',
    name: '',
    templateType: '',
    messageType: MessageType.SMS,
    enabledMark: 1,
    sortCode: 1,
    remark: '',
    messageConfig: '',
  });
  const configure = reactive({
    data: [] as Array<ConfigureItem>,
    columns: [
      {
        title: t('序号'),
        align: 'center',
        customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
        width: 80,
      },
      {
        title: t('参数名称'),
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: t('参数描述'),
        dataIndex: 'description',
        key: 'description',
        align: 'center',
      },
      {
        title: t('操作'),
        dataIndex: 'operation',
        key: 'operation',
        width: 80,
        align: 'center',
      },
    ] as ColumnProps[],
  });
  let messageContent: MessageContent = reactive({
    title: '', // 消息标题
    content: '', //消息内容
    templateCode: '', //模板编号
    appKey: '', //小程序
    configs: [], //短信配置 公众号配置
  });
  onMounted(async () => {
    await getCategoryTree();
    formState.id = '';
    if (props.editId) {
      let res = await getInfo(props.editId);
      formState.id = props.editId;
      if (res.code) formState.code = res.code;
      if (res.name) formState.name = res.name;
      formState.templateType = res.templateType;
      formState.messageType = res.messageType;
      formState.enabledMark = res.enabledMark;
      formState.sortCode = res.sortCode;
      formState.remark = res.remark;
      if (res.messageConfig) {
        let messageConfigObj = JSON.parse(res.messageConfig);
        if (messageConfigObj.messageContent) {
          if (messageConfigObj.messageContent.title)
            messageContent.title = messageConfigObj.messageContent.title;
          if (messageConfigObj.messageContent.content)
            messageContent.content = messageConfigObj.messageContent.content;
          if (messageConfigObj.messageContent.templateCode)
            messageContent.templateCode = messageConfigObj.messageContent.templateCode;
          if (messageConfigObj.messageContent.appKey)
            messageContent.appKey = messageConfigObj.messageContent.appKey;
        }
        if (messageConfigObj.messageContent.configs) {
          messageContent.configs = cloneDeep(messageConfigObj.messageContent.configs);
          messageContent.configs?.forEach((o) => {
            handleBlurField(o, 'variable');
          });
        }
        if (messageConfigObj.configureData) {
          configure.data = cloneDeep(messageConfigObj.configureData);
          configure.data?.forEach((o) => {
            handleBlurField(o, 'name');
          });
        }
      }
    }
  });
  const messageTypeOptions = [
    {
      value: MessageType.DING_DING,
      label: t('钉钉'),
    },
    {
      value: MessageType.EMAIL,
      label: t('邮箱'),
    },
    {
      value: MessageType.WEB_HOOK,
      label: t('WebHook'),
    },
    {
      value: MessageType.WE_CHAT,
      label: t('微信公众号'),
    },
    {
      value: MessageType.SMS,
      label: t('短信'),
    },
    {
      value: MessageType.WE_COM,
      label: t('企业微信'),
    },
    {
      value: MessageType.SYSTEM,
      label: t('系统消息'),
    },
  ];

  const messageContentConfigColumns = [
    {
      title: t('序号'),
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 80,
    },
    {
      title: t('变量'),
      dataIndex: 'variable',
      align: 'center',
      key: 'variable',
    },
    {
      title: t('消息参数'),
      dataIndex: 'parameter',
      align: 'center',
      key: 'parameter',
    },
    {
      title: t('操作'),
      dataIndex: 'operation',
      key: 'operation',
      align: 'center',
      width: 80,
    },
  ] as ColumnProps[];
  function addItem() {
    configure.data.push({
      name: '',
      description: '',
    });
  }
  function deleteItem(index) {
    configure.data.splice(index, 1);
  }
  function addConfigItem() {
    messageContent.configs.push({
      variable: '',
      parameter: '',
    });
  }
  function deleteConfigItem(index) {
    messageContent.configs.splice(index, 1);
  }
  async function getCategoryTree() {
    let res = await getDicDetailList({
      itemId: MessageTemplateCategory.ID,
    });
    templateTypeOptions.value = res.map((ele) => {
      return {
        value: ele.id,
        label: ele.name,
      };
    });
  }
  function changeMessageTypeOptions(val) {
    formState.messageType = val;
  }
  function changeTemplateTypeOptions(val) {
    formState.templateType = val;
  }
  function isEmptyConfigure(elem) {
    return elem.name != '' && elem.description != '';
  }
  function handleBlurField(record, field) {
    record[field] = record[field].replace(/[^a-zA-Z]/g, '');
  }
  async function handleSubmit() {
    try {
      await FormRef.value.validate();
      await MessageContentFormRef.value.validate();
      if (
        formState.messageType == MessageType.SMS ||
        formState.messageType == MessageType.WE_CHAT
      ) {
        if (messageContent.configs.length == 0) {
          notification.error({
            message: t('提示'),
            description: t('你需要填写消息内容配置表'),
          }); //提示消息
          return false;
        }
      }
      if (configure.data.length > 0) {
        let hasData = configure.data.every(isEmptyConfigure);
        if (hasData == false) {
          notification.error({
            message: t('提示'),
            description: t('参数配置的名称和描述不能为空'),
          }); //提示消息
          return false;
        }
      }
      formState.messageConfig = JSON.stringify({ messageContent, configureData: configure.data });

      return formState;
    } catch (error) {
      return false;
    }
  }
  defineExpose({
    handleSubmit,
  });
</script>

<style lang="less" scoped>
  .ant-row {
    margin-bottom: 15px;

    .state {
      font-size: 16px;
    }
  }

  .config-box {
    display: flex;

    .config-item {
      flex: 1;
    }

    .config-content {
      min-height: 400px;
    }
  }

  .new-button {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 30px;
    line-height: 30px;
    color: #6b656b;
    border: 1px dotted #d9d9d9;
    margin-top: 10px;
  }

  .delete-icon {
    color: @clear-color;
  }

  .basic-title {
    margin: 0 0 16px;
  }

  .flex-center {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .flex-center .ant-form-item:first-child {
    flex-basis: 50%;
    margin-right: 32px;
  }

  .flex-center .ant-form-item:nth-child(2) {
    flex-basis: 50%;
  }
</style>
