<template>
  <div class="pages-bos">
    <el-tabs v-model="setType" class="demo-tabs" @tab-click="handleClick" style="padding: 30px; width: 65%">
      <el-tab-pane label="短信配置" name="0">
        <el-form ref="messageSettingFormRef" :model="form" :rules="rules" label-width="160px">
          <!-- 短信设置说明 -->
          <div class="notice-box">
            <p>1.短信目前仅支持这3家,绑定哪一家后要将模板提交到对方平台审核回填模板ID,模板中的变量请按照对应平台的标准更改</p>
          </div>

          <!-- 短信设置选择 -->
          <el-form-item label="短信设置" prop="msgSetting">
            <el-radio-group v-model="form.msgSetting" @change="msgSettingChange">
              <el-radio v-for="dict in msg_setting_type" :key="dict.value" :value="dict.value" :disabled="editBtn">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 验证码模板ID -->
          <el-form-item label="验证码模板ID：" prop="codeId">
            <div class="code-id-container">
              <el-input v-model="form.codeId" placeholder="请输入在对应平台申请的验证码短信模板ID" class="input-width" :disabled="editBtn" />
              <div class="hint-text">请复制短信模板去申请: 尊敬的用户您的短信验证码是${code},10分钟内有效!</div>
            </div>
          </el-form-item>
          <div v-if="form.msgSetting == '0'">
            <!-- 企业ID -->
            <el-form-item label="企业ID：" prop="enterpriseId">
              <el-input v-model="enterpriseId" placeholder="企业ID" class="input-width" :disabled="editBtn" />
            </el-form-item>

            <!-- 登录账号 -->
            <el-form-item label="登录账号：" prop="loginAccount">
              <el-input v-model="loginAccount" placeholder="登录账号" class="input-width" :disabled="editBtn" />
            </el-form-item>

            <!-- 登录密码 -->
            <el-form-item label="登录密码：" prop="loginPassword">
              <el-input v-model="loginPassword" placeholder="登录密码" class="input-width" :disabled="editBtn" />
            </el-form-item>

            <!-- 请求地址 -->
            <el-form-item label="请求地址：" prop="requestUrl">
              <el-input v-model="requestUrl" placeholder="请求地址" class="input-width" :disabled="editBtn" />
            </el-form-item>
          </div>
          <div v-if="form.msgSetting == '1'">
            <!-- ak -->
            <el-form-item label="AK：" prop="keyAk">
              <el-input v-model="keyAk" placeholder="七牛云的秘钥ak" class="input-width" :disabled="editBtn" />
            </el-form-item>

            <!-- sk -->
            <el-form-item label="SK：" prop="keySk">
              <el-input v-model="keySk" placeholder="七牛云的秘钥sk" class="input-width" :disabled="editBtn" />
            </el-form-item>
          </div>
          <div v-if="form.msgSetting == '2'">
            <!-- AccessKey_id -->
            <el-form-item label="AccessKey_Id：" prop="accessKeyId">
              <el-input v-model="accessKeyId" placeholder="阿里云的秘钥AccessKey_id" class="input-width" :disabled="editBtn" />
            </el-form-item>

            <!-- AccessKey_Secret -->
            <el-form-item label="AccessKey_Secret：" prop="accessKeySecret">
              <el-input v-model="accessKeySecret" placeholder="阿里云的秘钥AccessKey_Secret" class="input-width" :disabled="editBtn" />
            </el-form-item>
            <!-- 短信签名 -->
            <el-form-item label="短信签名：" prop="aliMsgSignature">
              <el-input v-model="aliMsgSignature" placeholder="阿里云的短信签名" class="input-width" :disabled="editBtn" />
            </el-form-item>
          </div>
          <div v-if="form.msgSetting == '3'">
            <!-- 应用ID -->
            <el-form-item label="应用ID：" prop="appId">
              <el-input v-model="appId" placeholder="腾讯云的安全秘钥对应的应用ID" class="input-width" :disabled="editBtn" />
            </el-form-item>

            <!-- AccessKey_Secret -->
            <el-form-item label="SecretId：" prop="secretId">
              <el-input v-model="secretId" placeholder="腾讯云的安全秘钥SecretId" class="input-width" :disabled="editBtn" />
            </el-form-item>
            <!-- SecretKey -->
            <el-form-item label="SecretKey：" prop="secretKey">
              <el-input v-model="secretKey" placeholder="腾讯云的安全秘钥SecretKey" class="input-width" :disabled="editBtn" />
            </el-form-item>
            <!-- 短信签名 -->
            <el-form-item label="短信签名：" prop="msgSignature">
              <el-input v-model="msgSignature" placeholder="腾讯云的短信签名" class="input-width" :disabled="editBtn" />
            </el-form-item>
          </div>

          <!-- 短信在线充值及赠送设置 -->
          <!-- <div class="notice-box">
            <p>2.短信在线充值及赠送设置</p>
          </div> -->

          <!-- 赠送短信条数 -->
          <!-- <el-form-item label="赠送短信数" prop="giveNum">
            <el-input-number v-model="form.giveNum" :min="0" placeholder="0" style="width: 200px" /> 条
          </el-form-item> -->

          <!-- 短信购买价格 -->
          <!-- <el-form-item label="短信购买价格" prop="buyPrice">
            <div class="price-table">
              <table>
                <thead>
                  <tr>
                    <th>数量(条)</th>
                    <th>价格(元)</th>
                    <th><el-button type="primary" size="small" @click="addPackage">+ 新增套餐</el-button></th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in form.buyPackages" :key="index">
                    <td>
                      <el-input-number v-model="item.quantity" :min="0" style="width: 100%" />
                    </td>
                    <td>
                      <el-input-number v-model="item.price" :min="0" style="width: 100%" />
                    </td>
                    <td>
                      <el-button type="danger" size="small" @click="removePackage(index)">删除</el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </el-form-item> -->

          <!-- 保存按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm" v-hasPermi="['system:messageSetting:add']" v-if="!editBtn">
              &nbsp;&nbsp;&nbsp;保存设置&nbsp;&nbsp;&nbsp;
            </el-button>
            <el-button type="primary" @click="editBtn = false" v-hasPermi="['system:messageSetting:add']" v-if="editBtn">
              &nbsp;&nbsp;&nbsp;编辑设置&nbsp;&nbsp;&nbsp;
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="模板配置" name="1">
        <TemplateSetting />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="MessageSetting" lang="ts">
import { delMessageSetting, addMessageSetting, updateMessageSetting, getMsgSettingData } from '@/api/setting/messageSetting/index';
import { MessageSettingVO, MessageSettingQuery, MessageSettingForm } from '@/api/setting/messageSetting/types';
import type { TabsPaneContext } from 'element-plus';
import TemplateSetting from '@/views/setting/messageSetting/templateSetting.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { msg_setting_type } = toRefs<any>(proxy?.useDict('msg_setting_type'));

const buttonLoading = ref(false);
const loading = ref(true);
const editBtn = ref<boolean>(true);
const ids = ref<Array<string | number>>([]);
const setType = ref('0');
// 保存当前选中的短信服务商类型
const currentMsgSetting = ref('');

const queryFormRef = ref<ElFormInstance>();
const messageSettingFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const enterpriseId = ref('');
const loginAccount = ref('');
const loginPassword = ref('');
const requestUrl = ref('');

const keyAk = ref('');
const keySk = ref('');

const accessKeyId = ref('');
const accessKeySecret = ref('');

const msgSignature = ref('');
const aliMsgSignature = ref(''); // 阿里云的短信签名

const appId = ref('');
const secretId = ref('');
const secretKey = ref('');
const savedConfigInfo = ref<Record<string, any>>({});

const initFormData: MessageSettingForm = {
  id: undefined,
  msgSetting: '0',
  codeId: undefined,
  configInfo: undefined,
  giveNum: undefined,
  buySettingId: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<MessageSettingForm, MessageSettingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    msgSetting: undefined,
    codeId: undefined,
    configInfo: undefined,
    giveNum: undefined,
    buySettingId: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    msgSetting: [{ required: true, message: '短信设置不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const handleClick = (tab: TabsPaneContext) => {
  setType.value = tab.paneName as string;
  // queryParams.value.setType = tab.paneName as string;
  getList();
};

// 根据短信服务商类型回显配置字段的辅助函数
const restoreConfigFieldsByType = (type: string, configInfo: Record<string, any>) => {
  clearAllConfigFields();

  switch (type) {
    case '0': // 首易通信
      enterpriseId.value = configInfo.enterpriseId;
      loginAccount.value = configInfo.loginAccount;
      loginPassword.value = configInfo.loginPassword;
      requestUrl.value = configInfo.requestUrl;
      break;
    case '1': // 七牛云
      keyAk.value = configInfo.keyAk;
      keySk.value = configInfo.keySk;
      break;
    case '2': // 阿里云
      accessKeyId.value = configInfo.accessKeyId;
      accessKeySecret.value = configInfo.accessKeySecret;
      aliMsgSignature.value = configInfo.aliMsgSignature;
      break;
    case '3': // 腾讯云
      appId.value = configInfo.appId;
      secretId.value = configInfo.secretId;
      secretKey.value = configInfo.secretKey;
      msgSignature.value = configInfo.msgSignature;
      break;
  }
};

const msgSettingChange = (val: string) => {
  // 更新form.msgSetting为当前选择的值
  form.value.msgSetting = val;

  // 更新currentMsgSetting
  currentMsgSetting.value = val;

  // 清空所有配置字段
  clearAllConfigFields();

  // 如果savedConfigInfo中有数据，则根据当前选择的选项恢复对应字段
  if (savedConfigInfo.value && Object.keys(savedConfigInfo.value).length > 0) {
    restoreConfigFieldsByType(val, savedConfigInfo.value);
  }
};

// 添加方法
// const addPackage = () => {
//   form.value.buyPackages.push({ quantity: 0, price: 0 });
// };

// const removePackage = (index: number) => {
//   if (form.value.buyPackages.length > 1) {
//     form.value.buyPackages.splice(index, 1);
//   }
// };

/** 查询短信设置列表 */
const getList = async () => {
  loading.value = true;
  const res = await getMsgSettingData();
  if (res.data) {
    // 如果返回的数据与当前选择不一致，需要清空字段
    if (res.data.msgSetting !== currentMsgSetting.value) {
      currentMsgSetting.value = res.data.msgSetting;
      clearAllConfigFields();
    }

    form.value = res.data;
    let configInfo = JSON.parse(res.data.configInfo);
    savedConfigInfo.value = { ...configInfo }; // 保存完整配置信息

    // 根据当前选中的选项回显对应字段
    restoreConfigFieldsByType(form.value.msgSetting, configInfo);
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  messageSettingFormRef.value?.resetFields();
  enterpriseId.value = undefined;
  loginAccount.value = undefined;
  loginPassword.value = undefined;
  requestUrl.value = undefined;

  keyAk.value = undefined;
  keySk.value = undefined;

  accessKeyId.value = undefined;
  accessKeySecret.value = undefined;

  msgSignature.value = undefined;
  aliMsgSignature.value = undefined;

  appId.value = undefined;
  secretId.value = undefined;
  secretKey.value = undefined;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加短信设置';
};

/** 提交按钮 */
const submitForm = () => {
  messageSettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 根据当前选择的短信服务商构建相应的配置信息
      let configInfo: Record<string, any> = {};

      switch (form.value.msgSetting) {
        case '0': // 首易通信
          configInfo = {
            enterpriseId: enterpriseId.value,
            loginAccount: loginAccount.value,
            loginPassword: loginPassword.value,
            requestUrl: requestUrl.value
          };
          break;
        case '1': // 七牛云
          configInfo = {
            keyAk: keyAk.value,
            keySk: keySk.value
          };
          break;
        case '2': // 阿里云
          configInfo = {
            accessKeyId: accessKeyId.value,
            accessKeySecret: accessKeySecret.value,
            aliMsgSignature: aliMsgSignature.value
          };
          break;
        case '3': // 腾讯云
          configInfo = {
            appId: appId.value,
            secretId: secretId.value,
            secretKey: secretKey.value,
            msgSignature: msgSignature.value
          };
          break;
      }

      form.value.configInfo = JSON.stringify(configInfo);
      let res; // 保存响应结果
      if (form.value.id) {
        res = await updateMessageSetting(form.value).finally(() => (buttonLoading.value = false));
      } else {
        res = await addMessageSetting(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');

      // 直接更新表单数据，而不是先清空再重新获取
      if (res && res.data) {
        form.value = res.data;
        // 更新savedConfigInfo
        savedConfigInfo.value = configInfo;
        // 更新显示字段
        switch (form.value.msgSetting) {
          case '0': // 首易通信
            enterpriseId.value = configInfo.enterpriseId;
            loginAccount.value = configInfo.loginAccount;
            loginPassword.value = configInfo.loginPassword;
            requestUrl.value = configInfo.requestUrl;
            break;
          case '1': // 七牛云
            keyAk.value = configInfo.keyAk;
            keySk.value = configInfo.keySk;
            break;
          case '2': // 阿里云
            accessKeyId.value = configInfo.accessKeyId;
            accessKeySecret.value = configInfo.accessKeySecret;
            aliMsgSignature.value = configInfo.aliMsgSignature;
            break;
          case '3': // 腾讯云
            appId.value = configInfo.appId;
            secretId.value = configInfo.secretId;
            secretKey.value = configInfo.secretKey;
            msgSignature.value = configInfo.msgSignature;
            break;
        }
      }

      dialog.visible = false;
      await getList();
    }
  });
};

// 清空所有配置字段的辅助函数
const clearAllConfigFields = () => {
  enterpriseId.value = undefined;
  loginAccount.value = undefined;
  loginPassword.value = undefined;
  requestUrl.value = undefined;

  keyAk.value = undefined;
  keySk.value = undefined;

  accessKeyId.value = undefined;
  accessKeySecret.value = undefined;
  msgSignature.value = undefined;
  aliMsgSignature.value = undefined;

  appId.value = undefined;
  secretId.value = undefined;
  secretKey.value = undefined;
};

/** 删除按钮操作 */
const handleDelete = async (row?: MessageSettingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除短信设置编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMessageSetting(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/messageSetting/export',
    {
      ...queryParams.value
    },
    `messageSetting_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style scoped>
.input-width {
  width: 300px;
}
.notice-box {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 10px;
  margin: 10px 0;
  font-size: 12px;
  color: #4096ee;
}

.code-id-container {
  display: flex;
  flex-direction: column;
}

.hint-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  line-height: 1.4;
}

.price-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.price-table th,
.price-table td {
  padding: 8px;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

.price-table th {
  background-color: #f5f5f5;
}
</style>
