<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-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>服务商信息列表</span>
        </div>
      </template>
      <el-table v-loading="loading" :data="smsServiceConfigList">
        <el-table-column v-if="false" label="" align="center" prop="providerId" />
        <el-table-column label="服务商名称" align="center" prop="providerName" />
        <el-table-column label="服务商状态" align="center" prop="serviceStatus">
          <template #default="scope">
            <dict-tag :options="msg_service_status" :value="scope.row.serviceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="计费方式" align="center" prop="meterType">
          <template #default="scope">
            <dict-tag :options="msg_service_charging" :value="scope.row.meterType" />
          </template>
        </el-table-column>
        <el-table-column label="前后缀方式" align="center" prop="fixType">
          <template #default="scope">
            <dict-tag :options="msg_fix_type" :value="scope.row.fixType" />
          </template>
        </el-table-column>
        <el-table-column label="前缀" align="center" prop="prefix" />
        <el-table-column label="后缀" align="center" prop="suffix" />
        <el-table-column label="每条短信字数" align="center" prop="wordCount" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="信息变更" placement="top">
              <el-button
                v-hasPermi="['msg:smsServiceConfig:applay']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row, 'Info')"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>服务商变更申请列表</span>
        </div>
      </template>
      <el-table v-loading="applayLoading" :data="smsServiceConfigApplayList">
        <el-table-column v-if="false" label="" align="center" prop="providerId" />
        <el-table-column label="服务商名称" align="center" prop="providerName" />
        <el-table-column label="服务商状态" align="center" prop="serviceStatus">
          <template #default="scope">
            <dict-tag :options="msg_service_status" :value="scope.row.serviceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="计费方式" align="center" prop="meterType">
          <template #default="scope">
            <dict-tag :options="msg_service_charging" :value="scope.row.meterType" />
          </template>
        </el-table-column>
        <el-table-column label="前后缀方式" align="center" prop="fixType">
          <template #default="scope">
            <dict-tag :options="msg_fix_type" :value="scope.row.fixType" />
          </template>
        </el-table-column>
        <el-table-column label="前缀" align="center" prop="prefix" />
        <el-table-column label="后缀" align="center" prop="suffix" />
        <el-table-column label="每条短信字数" align="center" prop="wordCount" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="msg_service_apply" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="applicant" />
        <el-table-column label="申请时间" align="center" prop="applyDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核人" align="center" prop="auditor" />
        <el-table-column label="审核时间" align="center" prop="auditDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="信息变更" placement="top">
              <el-button v-hasPermi="['msg:smsServiceConfig:applaydetail']" link type="primary" icon="Edit" @click="handleUpdate(scope.row, 'Apply')">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改短信服务商配置对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="80%" append-to-body>
      <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 label="API 地址" prop="apiAddress">
            <el-input v-model="form.apiAddress" placeholder="请输入API 地址" style="width: 500px" disabled />
          </el-form-item>
        </el-row>
        <el-form-item label="AccessKeyID" prop="accessKeyId">
          <el-input v-model="form.accessKeyId" placeholder="请输入Access Key ID" disabled />
        </el-form-item>
        <el-form-item 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="请选择状态">
              <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>

      <!-- 修改对话框footer部分 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!isFromApplayList"
            v-hasPermi="['msg:smsServiceConfig:applay']"
            :loading="buttonLoading"
            type="primary"
            @click="submitForm"
          >
            确 定
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SmsServiceConfig" lang="ts">
import {
  listSmsServiceConfig,
  getSmsServiceConfig,
  delSmsServiceConfig,
  addSmsServiceConfig,
  updateSmsServiceConfig,
  listSmsServiceApplay
} from '@/api/msg/smsServiceConfig';
import { SmsServiceConfigVO, SmsServiceConfigQuery, SmsServiceConfigForm } from '@/api/msg/smsServiceConfig/types';
import { SmsServicePriceVO } from '@/api/msg/smsServiceConfig/servicePiceTypes';

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, msg_service_apply } = toRefs<any>(proxy?.useDict('msg_fix_type', 'msg_service_apply'));

const smsServiceConfigList = ref<SmsServiceConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);
const servicePiceList = ref([]);

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

const applayLoading = ref(false);
const applayTotal = ref(0);
const smsServiceConfigApplayList = ref([]);
const isFromApplayList = ref(false);
const applayParams = {
  pageNum: 1,
  pageSize: 10,
  params: {}
};

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 handleUpdate = async (row, sign) => {
  // reset();
  // isFromApplayList.value = isFromApplay; // 设置来源状态
  // const _providerId = row?.providerId || ids.value[0];
  // const res = await getSmsServiceConfig(_providerId);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = '修改短信服务商配置';
  //  console.log(row);
  proxy.$router.push({
    path: `/msg/service/smsServiceConfig`,
    query: {
      providerId: row.providerId,
      definitionId: row.definitionId,
      status: row.status,
      sign: sign
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  smsServiceConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addSmsServiceConfig(form.value, servicePiceList.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
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();
};

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

onMounted(() => {
  getList();
});
</script>
