<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true"></el-form>
        </el-card>
      </div>
    </transition>

    <el-form ref="smsServiceConfigFormRef" :model="form" :rules="rules" :inline="true" label-width="100px">
      <el-row>
        <el-form-item label="服务商名称" prop="providerName">
          <el-input v-model="form.providerName" placeholder="请输入服务商名称" disabled />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item v-if="false" label="API 地址" prop="apiAddress">
          <el-input v-model="form.apiAddress" placeholder="请输入API 地址" style="width: 500px" disabled />
        </el-form-item>
      </el-row>
      <el-form-item v-if="false" label="AccessKeyID" prop="accessKeyId">
        <el-input v-model="form.accessKeyId" placeholder="请输入Access Key ID" disabled />
      </el-form-item>
      <el-form-item v-if="false" label="AccessKeySecret" prop="accessKeySecret" disabled>
        <el-input v-model="form.accessKeySecret" placeholder="请输入Access Key Secret" disabled />
      </el-form-item>
      <el-row>
        <el-form-item label="状态" prop="serviceStatus">
          <el-select v-model="form.serviceStatus" placeholder="请选择状态" :disabled="status !== undefined">
            <el-option v-for="item in msg_service_status" :key="item.id" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="前后缀类型" prop="fixType">
          <el-select v-model="form.fixType" placeholder="请选择状态">
            <el-option v-for="item in msg_fix_type" :key="item.id" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.fixType === '2' || form.fixType === '4'" label="前缀" prop="prefix">
          <el-input v-model="form.prefix" placeholder="请输入前缀" />
        </el-form-item>
        <el-form-item v-if="form.fixType === '3' || form.fixType === '4'" label="后缀" prop="suffix">
          <el-input v-model="form.suffix" placeholder="请输入后缀" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="每条短信字数" prop="wordCount">
          <el-input-number v-model="form.wordCount" :precision="0" :step="1" :max="500" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="计费方式" prop="fixType">
          <el-select v-model="form.meterType" placeholder="请选择状态">
            <el-option v-for="item in msg_service_charging" :key="item.id" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.meterType === '1'" label="每条单价（元）" prop="unitPrice">
          <el-input-number v-model="form.unitPrice" :precision="2" :step="0.01" :max="0.5" />
        </el-form-item>

        <el-form-item v-if="form.meterType === '2'" label="每包数量（个）" prop="packageQuantity">
          <el-input-number v-model="form.packageQuantity" :precision="0" :step="1" />
        </el-form-item>

        <el-form-item v-if="form.meterType === '2'" label="每包价格（元）" prop="packagePrice">
          <el-input-number v-model="form.packagePrice" :precision="2" :step="0.01" />
        </el-form-item>
      </el-row>
    </el-form>

    <el-table v-if="form.meterType === '3'" :data="servicePiceList">
      <el-table-column label="起始数量" align="center" prop="tierStart">
        <template #default="scope">
          <el-input v-model="scope.row.tierStart" placeholder="请输入起始数量" />
        </template>
      </el-table-column>
      <el-table-column label="终止数量" align="center" prop="tierEnd">
        <template #default="scope">
          <el-input v-model="scope.row.tierEnd" placeholder="请输入终止数量" />
        </template>
      </el-table-column>
      <el-table-column label="单个价格（元）" align="center" prop="tierPrice">
        <template #default="scope">
          <el-input v-model="scope.row.tierPrice" placeholder="请输入单个价格（元）" />
        </template>
      </el-table-column>
    </el-table>
    <div v-if="form.meterType === '3'" style="margin-top: 10px">
      <el-button type="primary" @click="addListSubRow">+</el-button>
    </div>

    <el-row style="margin-bottom: 20px">
      <el-button
        v-if="status === undefined"
        v-hasPermi="['msg:smsServiceConfig:applay']"
        :loading="saveButtonLoading"
        type="primary"
        style="margin-top: 10px"
        @click="submitForm('save')"
      >
        保存
      </el-button>
    </el-row>

    <!-- 状态停用时的操作选择 -->
    <el-row v-if="smsChannel && smsByChannelList.length > 0">
      <el-col :span="24">
        <el-form-item label="更新方式" prop="updateMethod" label-width="100px">
          <el-select v-model="updateMethod" placeholder="请选择更新方式" style="width: 240px">
            <el-option label="逐条更新" value="single" />
            <el-option label="一键更新" value="batch" />
          </el-select>
        </el-form-item>
        <!-- 一键更新时的通道选择 -->
        <el-form-item v-if="updateMethod === 'batch'" label="发送通道" label-width="100px">
          <el-select v-model="batchChannel" placeholder="请选择通道" style="width: 240px">
            <el-option v-for="dict in availableChannels" :key="dict.providerId" :label="dict.providerName" :value="dict.providerId" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-card v-if="smsChannel && updateMethod === 'single' && smsByChannelList.length > 0" shadow="never">
      <template #header>
        <div class="card-header">
          <span>短信模板</span>
        </div>
      </template>
      <el-table v-loading="applayLoading" :data="smsByChannelList">
        <el-table-column label="短信编码" align="center" prop="templateCode" />
        <el-table-column label="短信名称" align="center" prop="templateName" />
        <el-table-column label="版本" align="center" prop="versionNumber" />
        <el-table-column label="发送通道" align="center" width="200">
          <template #default="scope">
            <el-select v-model="scope.row.selectedChannel" placeholder="请选择通道" clearable>
              <el-option
                v-for="dict in channel.filter((item) => item.providerId !== form.providerId)"
                :key="dict.providerId"
                :label="dict.providerName"
                :value="dict.providerId"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="applayTotal > 0"
        v-model:page="applayParams.pageNum"
        v-model:limit="applayParams.pageSize"
        :total="applayTotal"
        @pagination="getTemplateByChannels"
      />
    </el-card>

    <el-row style="margin-top: 20px">
      <el-button
        v-if="status === undefined || status === '2'"
        v-hasPermi="['msg:smsServiceConfig:applay']"
        :loading="sureButtonLoading"
        type="primary"
        @click="submitForm('sure')"
        >确 定
      </el-button>

      <el-button
        v-if="status === '2'"
        v-hasPermi="['msg:smsServiceConfig:applay']"
        :loading="revokeButtonLoading"
        type="primary"
        @click="revokeApply()"
        >撤 销
      </el-button>

      <el-button
        v-if="status === '0'"
        v-hasPermi="['msg:smsServiceConfigAudit:auditSmsServiceConfig']"
        :loading="passButtonLoading"
        type="primary"
        @click="submitForm('audit', true)"
        >审核通过
      </el-button>
      <el-button
        v-if="status === '0'"
        v-hasPermi="['msg:smsServiceConfigAudit:auditSmsServiceConfig']"
        :loading="notPassButtonLoading"
        type="danger"
        @click="submitForm('audit', false)"
        >审核不通过
      </el-button>
    </el-row>
  </div>
</template>

<script setup name="SmsServiceConfig" lang="ts">
import {
  listSmsServiceConfig,
  getSmsServiceConfig,
  delSmsServiceConfig,
  addSmsServiceConfig,
  listSmsServiceApplay,
  getTemplateByChannel,
  getApplaySmsServiceConfig,
  updateSmsSendChannel,
  getTemplateConfigCasual,
  auditSmsServiceConfig
} from '@/api/msg/smsServiceConfig';
import { SmsServiceConfigVO, SmsServiceConfigQuery, SmsServiceConfigForm } from '@/api/msg/smsServiceConfig/types';
import { getServiceConfig } from '@/api/msg/smsmanual/manual';
import { status } from 'nprogress';
import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { msg_service_status } = toRefs<any>(proxy?.useDict('msg_service_status'));
const { msg_service_charging } = toRefs<any>(proxy?.useDict('msg_service_charging'));
const { msg_fix_type } = toRefs<any>(proxy?.useDict('msg_fix_type'));

const smsServiceConfigList = ref<SmsServiceConfigVO[]>([]);
const buttonLoading = ref(false);
const saveButtonLoading = ref(false);
const sureButtonLoading = ref(false);
const revokeButtonLoading = ref(false);
const passButtonLoading = ref(false);
const notPassButtonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const smsChannel = ref(false);
const ids = ref<Array<string | number>>([]);
const total = ref(0);
const servicePiceList = ref([]);
const channel = ref([]);
const status = ref();
const definitionId = ref();
const sign = ref();

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

const applayLoading = ref(false);
const applayTotal = ref(0);
const smsByChannelList = ref([]);
const updateMethod = ref<'single' | 'batch'>('single'); // 更新方式
const batchChannel = ref('');
const applayParams = {
  pageNum: 1,
  pageSize: 10
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SmsServiceConfigForm = {
  providerId: undefined,
  providerName: undefined,
  apiAddress: undefined,
  requestMethod: undefined,
  authenticationMethod: undefined,
  signatureMethod: undefined,
  accessKeyId: undefined,
  accessKeySecret: undefined,
  accountId: undefined,
  subAccountInfo: undefined,
  signatureId: undefined,
  signatureContent: undefined,
  signatureStatus: undefined,
  callbackAddress: undefined,
  callbackDataFormat: undefined,
  receivingNumberLimit: undefined,
  serviceStatus: undefined,
  meterType: undefined,
  fixType: undefined,
  prefix: undefined,
  suffix: undefined,
  wordCount: undefined,
  unitPrice: undefined,
  packagePrice: undefined,
  packageQuantity: undefined
};
const data = reactive<PageData<SmsServiceConfigForm, SmsServiceConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {}
  },
  rules: {
    prefix: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if ((form.value.fixType === '2' || form.value.fixType === '4') && !value) {
            callback(new Error('前缀不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    suffix: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if ((form.value.fixType === '3' || form.value.fixType === '4') && !value) {
            callback(new Error('后缀不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    unitPrice: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.value.meterType === '1' && !value) {
            callback(new Error('每条单价不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    packageQuantity: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.value.meterType === '2' && !value) {
            callback(new Error('每包数量不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    packagePrice: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.value.meterType === '2' && !value) {
            callback(new Error('每包价格不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});

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

/** 查询短信服务商配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSmsServiceConfig(queryParams.value);
  smsServiceConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  applayLoading.value = true;
  const resApplay = await listSmsServiceApplay(applayParams);
  smsServiceConfigApplayList.value = resApplay.rows;
  applayTotal.value = resApplay.total;
  applayLoading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  smsServiceConfigFormRef.value?.resetFields();
};

const availableChannels = computed(() => channel.value.filter((item) => item.providerId !== form.value.providerId));

//根据传来的参数查询不同数据
const handleUpdate = async (providerId, definitionId1, status, sign) => {
  //从服务商信息列表点进来，查询服务商配置表
  if (sign === 'Info') {
    const res = await getSmsServiceConfig(providerId);
    Object.assign(form.value, res.data);
  }
  //从服务商变更申请列表点进来，查询服务商申请表
  if (sign === 'Apply' || sign === 'audit') {
    definitionId.value = definitionId1;
    const res = await getApplaySmsServiceConfig(definitionId1);
    Object.assign(form.value, res.data.configDefinition);
    servicePiceList.value = res.data.priceDefinitionList;
    if (res.data.updateMethod === 'single') {
      await getTemplateByChannels();
      updateMethod.value = res.data.updateMethod;
      smsChannel.value = smsByChannelList.value.length > 0;
    } else {
      updateMethod.value = res.data.updateMethod;
      batchChannel.value = res.data.batchChannel;
    }
  }
};

const validateChannels = () => {
  const invalidTemplates = smsByChannelList.value.filter((item) => !item.selectedChannel);
  return invalidTemplates.length === 0;
};

/** 提交按钮 */
const submitForm = (sign, isPass) => {
  smsServiceConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (sign === 'save') {
        saveButtonLoading.value = true;
        const res = await addSmsServiceConfig(form.value, servicePiceList.value);
        definitionId.value = res.data.definitionId;
        //  console.log(form.value);
        proxy?.$modal.msgSuccess('保存成功');
        saveButtonLoading.value = false;
        if (res.data.message) {
          proxy?.$modal.alert('主题为' + res.data.message + '手工短信将不会再发送');
        }
      }
      if (sign === 'sure') {
        // 逐条更新时验证通道选择
        if (updateMethod.value === 'single' && !validateChannels()) {
          proxy?.$modal.msgError('请为所有模板选择发送通道');
          return;
        }

        // 一键更新时验证通道选择
        if (updateMethod.value === 'batch' && !batchChannel.value) {
          proxy?.$modal.msgError('请选择一键更新的通道');
          return;
        }

        //先点保存
        if (!definitionId.value) {
          proxy?.$modal.msgError('请选择先点击保存');
          return;
        }
        //将短信模板信息和申请表id保存到临时表中，一键更新还是逐条更新
        const baseData = {
          definitionId: definitionId.value,
          updateMethod: updateMethod.value,
          smsSendChannel: batchChannel.value,
          casuals: smsByChannelList.value.map((item) => ({
            definitionId: definitionId.value,
            templateId: item.templateId,
            templateCode: item.templateCode,
            templateName: item.templateName,
            versionNumber: item.versionNumber,
            updateMethod: updateMethod.value,
            smsSendChannel: item.selectedChannel
          }))
        };
        //  console.log(baseData);
        sureButtonLoading.value = true;
        await updateSmsSendChannel(baseData);
        proxy?.$modal.msgSuccess('保存成功');
        sureButtonLoading.value = false;
        openIndex();
      }

      if (sign === 'audit') {
        if (isPass) {
          passButtonLoading.value = true;
        } else {
          notPassButtonLoading.value = true;
        }
        //  console.log(definitionId.value);
        await auditSmsServiceConfig(definitionId.value, isPass);
        proxy?.$modal.msgSuccess('操作成功');
        passButtonLoading.value = false;
        notPassButtonLoading.value = true;
        openAudit();
      }
    }
  });
};

const openIndex = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/msg/channel/smsServiceConfig'
  };
  proxy?.$tab.closeOpenPage(obj);
};

const openAudit = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/msg/channel/smsServiceConfigAudit'
  };
  proxy?.$tab.closeOpenPage(obj);
};

//撤销申请
const revokeApply = async () => {
  revokeButtonLoading.value = true;
  //  console.log(definitionId.value);
  await auditSmsServiceConfig(definitionId.value, false);
  proxy?.$modal.msgSuccess('撤销成功');
  revokeButtonLoading.value = false;
  openIndex();
};

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

// 添加watch监听状态变化
watch(
  () => form.value.serviceStatus,
  (newVal, oldVal) => {
    if ((oldVal === '1' && newVal === '2') || status.value === '2') {
      getTemplateByChannels();
      smsChannel.value = true;
      updateMethod.value = 'single'; // 默认逐条更新
    } else {
      smsChannel.value = false;
      smsByChannelList.value = [];
    }
  }
);

watch(
  () => form.value.fixType,
  (newVal) => {
    if (newVal === '1') {
      form.value.prefix = '';
      form.value.suffix = '';
    } else if (newVal === '2') {
      form.value.suffix = '';
    } else if (newVal === '3') {
      form.value.prefix = '';
    }
  }
);

const getTemplateByChannels = async () => {
  if (status.value === '2') {
    sign.value = 'Info';
  }
  if (sign.value === 'Info') {
    try {
      loading.value = true;
      const { createTime, updateTime, ...formWithoutTimestamps } = form.value; // 排除时间字段
      const params = {
        ...formWithoutTimestamps, // 只包含非时间字段
        pageNum: applayParams.pageNum,
        pageSize: applayParams.pageSize
      };
      //  console.log(form.value);
      const response = await getTemplateByChannel(params);
      //  console.log(response.rows);
      smsByChannelList.value = response.rows;
      applayTotal.value = response.total;
      smsChannel.value = smsByChannelList.value.length > 0;
    } catch (error) {

      smsChannel.value = false;
    } finally {
      loading.value = false;
    }
  } else {
    try {
      loading.value = true;
      const params = {
        definitionId: route.query.definitionId,
        pageNum: applayParams.pageNum,
        pageSize: applayParams.pageSize
      };
      const response = await getTemplateConfigCasual(params);
      //  console.log(response.rows);
      smsByChannelList.value = (response.rows || []).map((item) => ({
        ...item,
        selectedChannel: item.smsSendChannel
      }));
      applayTotal.value = response.total;
    } catch (error) {

    } finally {
      loading.value = false;
    }
  }
};

/** 增加行 */
const addListSubRow = () => {
  const newRow = { tierStart: '', tierEnd: '', unitPrice: '' };
  servicePiceList.value.push(newRow);
};

const getSmsSendChannel = async () => {
  const res = await getServiceConfig();
  channel.value = res.data;
};

const route = useRoute();
onMounted(() => {
  handleUpdate(route.query.providerId, route.query.definitionId, route.query.status, route.query.sign);
  status.value = route.query.status;
  sign.value = route.query.sign;
  getSmsSendChannel();
});
</script>
