<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-row>
              <el-form-item label="使用厂商" prop="vendor">
                <el-select v-model="queryParams.providerId" placeholder="请选择使用厂商" clearable>
                  <el-option
                    v-for="provider in serviceProviderList"
                    :key="provider.providerId"
                    :label="provider.providerName"
                    :value="provider.providerId"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="归属系统" prop="system">
                <el-select v-model="queryParams.system" placeholder="请选择所属系统" clearable>
                  <el-option v-for="dict in msg_system" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="销售渠道" prop="salesChannel">
                <el-select v-model="queryParams.salesChannel" placeholder="请选择销售渠道" clearable>
                  <el-option v-for="dict in sales_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>

            </el-row>
            <!--            <el-form-item label="短信来源" prop="smsSource">-->
            <!--              <el-select v-model="queryParams.smsSource" placeholder="请选择短信来源" clearable>-->
            <!--                <el-option v-for="dict in sms_source" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <!--            &lt;!&ndash;-->

            <!--            &ndash;&gt;-->

            <el-row>
              <el-form-item  label="业务渠道" prop="businessChannel">
                <el-select v-model="queryParams.businessChannel" placeholder="请选择业务渠道" clearable>
                  <el-option v-for="dict in business_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="短信名称" prop="smsName">
                <el-input v-model="queryParams.smsName" placeholder="请输入短信名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="发送方式" prop="sendType">
                <el-select v-model="queryParams.sendType" placeholder="请选择短信分类" clearable>
                  <el-option v-for="dict in send_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item label="开始日期" prop="beginDate">
              <el-date-picker v-model="queryParams.beginDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择开始日期" />
            </el-form-item>

            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="queryParams.endDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束日期" />
            </el-form-item>
            <el-form-item style="width: 100%">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['msg:settlement:export']">导出</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Document" @click="handleExportDetail" v-hasPermi="['msg:smscount:export']">导出明细</el-button>-->
<!--          </el-col>-->
        </el-row>
      </template>
      <el-table v-loading="loading" :data="smscountList" @selection-change="handleSelectionChange">
        <!-- 使用厂商 -->
        <el-table-column label="使用厂商" align="center">
          <template #default="scope">
            {{ getProviderName(scope.row.providerId) }}
          </template>
        </el-table-column>

        <!-- 归属系统 -->
        <el-table-column label="归属系统" align="center">
          <template #default="scope">
            <dict-tag v-if="scope.row.system" :options="msg_system" :value="scope.row.system" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 短信数量合计 -->
        <el-table-column label="短信数量合计" align="center">
          <template #default="scope">
            {{ scope.row.totalCount || 0 }}
          </template>
        </el-table-column>

        <!-- 短信成功条数 -->
        <el-table-column label="短信成功条数" align="center" prop="successCount">
          <template #default="scope">
            {{ scope.row.successCount || 0 }}
          </template>
        </el-table-column>

        <!-- 短信失败条数 -->
        <el-table-column label="短信失败条数" align="center" prop="failCount">
          <template #default="scope">
            {{ scope.row.failCount || 0 }}
          </template>
        </el-table-column>

        <!-- 实际发送条数合计 -->
        <el-table-column label="实际发送条数合计" align="center">
          <template #default="scope">
            {{ scope.row.actualTotalCount || 0 }}
          </template>
        </el-table-column>


        <!-- 实际发送成功条数 -->
        <el-table-column label="实际发送成功条数" align="center" prop="actualSuccessCount">
          <template #default="scope">
            {{ scope.row.actualSuccessCount || 0 }}
          </template>
        </el-table-column>

        <!-- 实际发送失败条数 -->
        <el-table-column label="实际发送失败条数" align="center" prop="actualFailCount">
          <template #default="scope">
            {{ scope.row.actualFailCount || 0 }}
          </template>
        </el-table-column>

        <!-- 单价 -->
        <el-table-column label="单价" align="center" prop="unitPrice">
          <template #default="scope">
            {{ scope.row.unitPrice ? '¥' + scope.row.unitPrice.toFixed(3) : '-' }}
          </template>
        </el-table-column>

        <!-- 实际发送成功费用合计 -->
        <el-table-column label="实际发送成功费用合计" align="center" prop="totalCost">
          <template #default="scope">
            {{ scope.row.totalCost ? '¥' + scope.row.totalCost.toFixed(3) : '-' }}
          </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-dialog v-model="dialog.visible" :title="dialog.title" append-to-body>
      <el-form ref="smscountFormRef" :model="form" disabled>
        <el-form-item label="模板唯一标识" prop="templateId">
          <el-input v-model="form.templateId" placeholder="模板唯一标识" />
        </el-form-item>
        <el-form-item label="接收人" prop="recipient" label-width="90px">
          <el-input v-model="form.recipient" placeholder="接收人" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber" label-width="90px">
          <el-input v-model="form.phoneNumber" placeholder="电话号码" />
        </el-form-item>
        <el-form-item label="短信内容">
          <editor v-model="form.smsContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime" label-width="90px">
          <el-date-picker v-model="form.sendTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="发送时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发送状态" prop="sendStatus" label-width="90px">
          <el-select v-model="form.sendStatus" placeholder="发送状态">
            <el-option v-for="dict in send_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送类型" prop="sendType" label-width="90px">
          <el-select v-model="form.sendType" placeholder="发送类型">
            <el-option v-for="dict in send_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请批次ID" prop="batchId" label-width="90px">
          <el-input v-model="form.batchId" placeholder="申请批次ID" />
        </el-form-item>
        <el-form-item label="请求报文ID" prop="requestId" label-width="90px">
          <el-input v-model="form.requestId" placeholder="请求报文ID" />
        </el-form-item>
        <el-form-item label="使用厂商" prop="vendor" label-width="90px">
          <el-input v-model="form.vendor" placeholder="使用厂商" />
        </el-form-item>
        <el-form-item label="实际发送条数" prop="actualCount" label-width="90px">
          <el-input v-model="form.actualCount" placeholder="实际发送条数" />
        </el-form-item>
        <el-form-item label="业务渠道" prop="businessChannel" label-width="90px">
          <el-select v-model="form.businessChannel" placeholder="业务渠道">
            <el-option v-for="dict in business_channel" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信来源" prop="smsSource" label-width="90px">
          <el-select v-model="form.smsSource" placeholder="短信来源">
            <el-option v-for="dict in sms_source" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信名称" prop="smsName" label-width="90px">
          <el-input v-model="form.smsName" placeholder="短信名称" />
        </el-form-item>
        <el-form-item label="短信分类" prop="smsType" label-width="90px">
          <el-select v-model="form.smsType" placeholder="短信分类">
            <el-option v-for="dict in sms_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!--<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancel">返 回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Smscount" lang="ts">
import {
  listSmscount,
  getSmscount,
  delSmscount,
  addSmscount,
  updateSmscount,
  getSettlement,
  postSettlement
} from '@/api/msg/smscount';
import { SmscountVO, SmscountQuery, SmscountForm } from '@/api/msg/smscount/types';
import { queryMSMTemplateList } from '@/api/msg/mestemp';
import { parseTime } from '@/utils/ruoyi';
import { getAllSmsManualChannelConfig } from '@/api/msg/smsServiceConfig';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { send_type, sms_type, sms_source, business_channel, send_status, msg_system, sales_channel } = toRefs<any>(
  proxy?.useDict('send_type', 'sms_type', 'sms_source', 'business_channel', 'send_status', 'msg_system', 'sales_channel')
);

const serviceProviderList = ref<any[]>([]);
const likeName = ref('');
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);

const smscountList = ref<SmscountVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

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

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

const initFormData: SmscountForm = {
  sendId: undefined,
  templateId: undefined,
  recipient: undefined,
  phoneNumber: undefined,
  smsContent: undefined,
  sendTime: undefined,
  sendStatus: undefined,
  sendType: undefined,
  batchId: undefined,
  requestId: undefined,
  vendor: undefined,
  actualCount: undefined,
  businessChannel: undefined,
  smsSource: undefined,
  smsName: undefined,
  smsType: undefined
};
const data = reactive<PageData<SmscountForm, SmscountQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateId: undefined,
    recipient: undefined,
    phoneNumber: undefined,
    smsContent: undefined,
    sendTime: undefined,
    sendStatus: undefined,
    sendType: undefined,
    batchId: undefined,
    requestId: undefined,
    providerId: undefined,
    actualCount: undefined,
    businessChannel: undefined,
    smsSource: undefined,
    smsName: undefined,
    smsType: undefined,
    templateCode: undefined,
    system: undefined,
    salesChannel: undefined,
    beginDate: undefined,
    endDate: undefined,
    params: {}
  },
  rules: {
    sendId: [{ required: true, message: '发送记录唯一标识不能为空', trigger: 'blur' }],
    templateId: [{ required: true, message: '模板唯一标识不能为空', trigger: 'blur' }],
    recipient: [{ required: true, message: '接收人不能为空', trigger: 'blur' }],
    phoneNumber: [{ required: true, message: '电话号码不能为空', trigger: 'blur' }],
    smsContent: [{ required: true, message: '短信内容不能为空', trigger: 'blur' }],
    sendTime: [{ required: true, message: '发送时间不能为空', trigger: 'blur' }],
    sendStatus: [{ required: true, message: '发送状态不能为空', trigger: 'change' }],
    sendType: [{ required: true, message: '发送类型不能为空', trigger: 'change' }],
    batchId: [{ required: true, message: '申请批次ID不能为空', trigger: 'blur' }],
    requestId: [{ required: true, message: '请求报文ID不能为空', trigger: 'blur' }],
    vendor: [{ required: true, message: '使用厂商不能为空', trigger: 'blur' }],
    actualCount: [{ required: true, message: '实际发送条数不能为空', trigger: 'blur' }],
    businessChannel: [{ required: true, message: '业务渠道不能为空', trigger: 'change' }],
    smsSource: [{ required: true, message: '短信来源不能为空', trigger: 'change' }],
    smsName: [{ required: true, message: '短信名称不能为空', trigger: 'blur' }],
    smsType: [{ required: true, message: '短信分类不能为空', trigger: 'change' }]
  }
});
// 厂商选择相关方法
const getProviderName = (providerId: number | string) => {
  if (!providerId) return '-';
  const provider = serviceProviderList.value.find((item) => item.providerId == providerId);
  return provider ? provider.providerName : providerId;
};
const getAllServiceConfig = async () => {
  try {
    const res = await getAllSmsManualChannelConfig();
    serviceProviderList.value = res || [];
  } catch (error) {

    serviceProviderList.value = [];
  }
};

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

/** 短信费用统计查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    // 直接传递所有查询参数，包括分页参数
    const res = await getSettlement(queryParams.value);

    // 处理响应数据
    smscountList.value = res.rows;
    total.value = res.total;
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
/** 分页事件处理 */
const handlePagination = (pagination: any) => {
  queryParams.value.pageNum = pagination.page;
  queryParams.value.pageSize = pagination.limit;
  getList();
};
// 格式化金额显示
const formatCurrency = (amount) => {
  if (amount === undefined || amount === null) return '-';
  if (typeof amount === 'number') {
    return '¥' + amount.toFixed(3); // 保留3位小数
  }
  return amount;
};

// // 格式化成功率显示
// const formatSuccessRate = (rate) => {
//   if (rate === undefined || rate === null) return '-';
//   if (typeof rate === 'number') {
//     return rate.toFixed(2) + '%';
//   }
//   return rate;
// };
//
// // 获取模板名称
// const getTemplateName = (templateCode) => {
//   if (!templateCode) return '-';
//   const template = templateList.value.find(t => t.templateCode === templateCode);
//   return template ? template.templateName : templateCode;
// };
// /** 取消按钮 */
// const cancel = () => {
//   reset();
//   dialog.visible = false;
// };

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

/** 搜索按钮操作 */
const handleQuery = () => {
  if (queryParams.value.beginDate) {
    queryParams.value.beginDate = parseTime(queryParams.value.beginDate, '{y}-{m}-{d}');
  }
  if (queryParams.value.endDate) {
    queryParams.value.endDate = parseTime(queryParams.value.endDate, '{y}-{m}-{d}');
  }
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.templateCode = undefined;
  queryParams.value.system = undefined;
  queryParams.value.salesChannel = undefined;
  queryParams.value.beginDate = undefined;
  queryParams.value.endDate = undefined;
  queryParams.value.providerId = undefined;
  queryParams.value.pageNum = 1;
  likeName.value = '';
  filteredList.value = templateList.value;
  getList();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SmscountVO[]) => {
  ids.value = selection.map((item) => item.sendId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

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

// /** 修改按钮操作 */
// const handleUpdate = async (row?: SmscountVO) => {
//   reset();
//   const _sendId = row?.sendId || ids.value[0];
//   const res = await getSmscount(_sendId);
//   Object.assign(form.value, res.data);
//   dialog.visible = true;
//   dialog.title = '修改短信统计查询';
// };

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

// /** 删除按钮操作 */
// const handleDelete = async (row?: SmscountVO) => {
//   const _sendIds = row?.sendId || ids.value;
//   await proxy?.$modal.confirm('是否确认删除短信统计查询编号为"' + _sendIds + '"的数据项？').finally(() => (loading.value = false));
//   await delSmscount(_sendIds);
//   proxy?.$modal.msgSuccess('删除成功');
//   await getList();
// };

/** 导出按钮操作 */
const handleExport = () => {
  // 创建导出参数对象，确保销售渠道值正确映射
  const exportParams = {
    ...queryParams.value,


    salesChannel: queryParams.value.salesChannel ?
      getSalesChannelValue(queryParams.value.salesChannel) :
      undefined,
    system: queryParams.value.system ?
      getDictValue(msg_system.value, queryParams.value.system) :
      undefined,
    businessChannel: queryParams.value.businessChannel ?
      getDictValue(business_channel.value, queryParams.value.businessChannel) :
      undefined
  };

  // 移除分页参数，确保导出所有数据
  delete exportParams.pageNum;
  delete exportParams.pageSize;

  proxy?.download(
    'msg/settlement/export',
    exportParams,
    `费用结算统计_${new Date().getTime()}.xlsx`
  );
};
const getDictValue = (dictList, label) => {
  const item = dictList.find(d => d.label === label);
  return item ? item.value : label;
};
/** 导出明细按钮操作 */
const handleExportDetail = () => {
  // 创建导出参数对象，确保销售渠道值正确映射
  const exportParams = {
    ...queryParams.value,
    // 确保销售渠道值正确映射
    salesChannel: queryParams.value.salesChannel ?
      getSalesChannelValue(queryParams.value.salesChannel) :
      undefined
  };

  // 移除分页参数，确保导出所有数据
  delete exportParams.pageNum;
  delete exportParams.pageSize;

  proxy?.download(
    'msg/smscount/exportdetail',
    exportParams,
    `短信统计明细_${new Date().getTime()}.xlsx`
  );
};
/** 获取销售渠道对应的值 */
const getSalesChannelValue = (label: string) => {
  const channel = sales_channel.value.find(item => item.label === label);
  return channel ? channel.value : label;
};
onMounted(() => {
  getList();
  getAllServiceConfig();
});
</script>
