<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-item label="接收人" prop="recipient">
              <el-input v-model="queryParams.recipient" placeholder="请输入接收人" clearable />
            </el-form-item>
            <el-form-item label="电话号码" prop="phoneNumber">
              <el-input v-model="queryParams.phoneNumber" placeholder="请输入电话号码" clearable />
            </el-form-item>
            <el-form-item label="发送时间" prop="dateValue">
              <el-date-picker
                v-model="dateValue"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="批次ID" prop="batchId">
              <el-input v-model="queryParams.batchId" placeholder="请输入申请批次ID" clearable />
            </el-form-item>
            <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="actualCount">
              <el-input v-model="queryParams.actualCount" placeholder="请输入实际发送条数" clearable />
            </el-form-item>
            <el-form-item label="短信名称" prop="smsName">
              <el-input v-model="queryParams.smsName" placeholder="请输入短信名称" clearable />
            </el-form-item>
            <el-form-item label="短信分类" prop="smsType">
              <el-select v-model="queryParams.smsType" placeholder="请选择短信分类" style="width: 240px" clearable>
                <el-option v-for="dict in sms_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="业务渠道" prop="businessChannel">
              <el-cascader
                v-model="queryParams.businessChannel"
                :options="moduleTreeOptions"
                :props="moduleProps"
                :show-all-levels="false"
                placeholder="请选择渠道"
                clearable
                filterable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="保单号" prop="policyNumber">
              <el-input v-model="queryParams.policyNumber" placeholder="请输入保单号" clearable />
            </el-form-item>
            <el-form-item label="业务号" prop="businessNumber">
              <el-input v-model="queryParams.businessNumber" placeholder="请输入业务号" clearable />
            </el-form-item>
            <el-form-item label="销售渠道" prop="salesChannel">
              <el-select v-model="queryParams.salesChannel" placeholder="请选择销售渠道" style="width: 240px" 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>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="smssendList">
        <el-table-column label="保单号" align="center" prop="policyNumber" width="180" />
        <el-table-column label="业务号" align="center" prop="businessNumber" width="180" />
        <el-table-column label="销售渠道" align="center" prop="salesChannel" width="180">
          <template #default="scope">
            <dict-tag :options="sales_channel" :value="scope.row.salesChannel" />
          </template>
        </el-table-column>
        <el-table-column label="电话号码" align="center" prop="phoneNumber" width="180" />
        <el-table-column label="短信内容" align="center" prop="smsContent" width="380" show-overflow-tooltip />
        <el-table-column label="发送时间" align="center" prop="sendTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发送状态" align="center" prop="sendStatus">
          <template #default="scope">
            <dict-tag :options="send_status" :value="scope.row.sendStatus" />
          </template>
        </el-table-column>
        <el-table-column label="使用厂商" align="center" prop="providerId">
          <template #default="scope">
            {{ getProviderName(scope.row.providerId) }}
          </template>
        </el-table-column>
        <el-table-column label="实际发送条数" align="center" prop="actualCount" />
      </el-table>

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

<script setup name="Smssend" lang="ts">
import { listSmssend } from '@/api/msg/smssend';
import { SmssendVO, SmssendQuery, SmssendForm } from '@/api/msg/smssend/types';
import { getAllSmsManualChannelConfig } from '@/api/msg/smsServiceConfig';
import { constructModuleEnumTree } from '@/api/msg/mestemp';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { send_status, sms_type, sales_channel } = toRefs<any>(proxy?.useDict('send_status', 'sms_type', 'sales_channel'));

const smssendList = ref<SmssendVO[]>([]);
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 serviceProviderList = ref<any[]>([]);
const moduleTreeOptions = ref<any[]>([]);
const moduleProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true,
  emitPath: false
};

const queryFormRef = ref<ElFormInstance>();
const initFormData: SmssendForm = {
  sendId: undefined,
  templateId: undefined,
  recipient: undefined,
  phoneNumber: undefined,
  smsContent: undefined,
  sendTime: undefined,
  sendStatus: undefined,
  sendType: undefined,
  batchId: undefined,
  requestId: undefined,
  vendor: undefined,
  actualCount: undefined
};
const data = reactive<PageData<SmssendForm, SmssendQuery>>({
  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,
    vendor: undefined,
    actualCount: undefined,
    providerId: undefined,
    smsName: undefined,
    businessChannel: undefined,
    policyNumber: undefined,
    businessNumber: undefined,
    salesChannel: undefined,
    beginDate: undefined,
    endDate: undefined,
    params: {}
  },
  rules: {}
});

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

//查询条件，建立时间的数据
const dateValue = ref<DatePickerValueType | null>(null);
//监听dateValue的值变化
watch(dateValue, (newValue) => {
  if (newValue) {
    queryParams.value.beginDate = newValue[0];
    queryParams.value.endDate = newValue[1];
  } else {
    queryParams.value.beginDate = null;
    queryParams.value.endDate = null;
  }
});

/** 根据providerId获取服务商名称 */
const getProviderName = (providerId: number | string) => {
  if (!providerId) return '-';
  const provider = serviceProviderList.value.find((item) => item.providerId == providerId);
  return provider ? provider.providerName : providerId;
};

/** 查询短信发送记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSmssend(queryParams.value);
  smssendList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 得到所有服务商信息 */
const getAllServiceConfig = async () => {
  try {
    const res = await getAllSmsManualChannelConfig();
    serviceProviderList.value = res || [];
  } catch (error) {
    serviceProviderList.value = [];
  }
};

const getModuleTree = async () => {
  try {
    const res = await constructModuleEnumTree();

    // 如果返回的是字符串，先解析为JSON对象
    const data = typeof res.msg === 'string' ? JSON.parse(res.msg) : res.msg;

    // 处理数据 - 你提供的示例数据已经是正确的树形结构
    moduleTreeOptions.value = Array.isArray(data) ? data : [data];

  } catch (error) {
    moduleTreeOptions.value = [];
  }
};

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