<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" label-width="100px" :inline="true">
            <el-form-item label="服务类型" prop="serviceType">
              <el-select v-model="queryParams.serviceType" placeholder="请选择服务类型" clearable>
                <el-option v-for="dict in service_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="服务商" prop="vendorName">
              <el-input v-model="queryParams.vendorName" placeholder="请输入服务商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发送通道号" prop="sendChannelNumber">
              <el-input v-model="queryParams.sendChannelNumber" placeholder="请输入发送通道号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="启用日期" prop="startDate" >
              <el-date-picker v-model="queryParams.startDate" 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">
      <el-table v-loading="loading" :data="vendorconfigList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!--<el-table-column v-if="true" label="服务商唯一标识" align="center" prop="vendorId" /> -->
        <el-table-column label="服务类型" align="center" prop="serviceType">
          <template #default="scope">
            <dict-tag :options="service_type" :value="scope.row.serviceType" />
          </template>
        </el-table-column>
        <el-table-column label="服务商名称" align="center" prop="vendorName" />
        <el-table-column label="启用状态" align="center" prop="enableStatus" />
        <el-table-column label="发送比例" align="center" prop="sendRatio" />
        <el-table-column label="是否需要回执" align="center" prop="receiptRequired" />
        <el-table-column label="降级策略" align="center" prop="downgradeStrategy" />
        <el-table-column label="熔断策略" align="center" prop="circuitBreakerStrategy" />
        <el-table-column label="启用日期" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="终止日期" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center" prop="modifyTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</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:vendorconfig:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</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-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="vendorconfigFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="form.serviceType" placeholder="请选择服务类型" disabled>
            <el-option v-for="dict in service_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务商名称" prop="vendorName" readonly>
          <el-input v-model="form.vendorName" placeholder="请输入服务商名称" />
        </el-form-item>
        <el-form-item label="发送比例" prop="sendRatio">
          <el-input v-model="form.sendRatio" placeholder="请输入发送比例" />
        </el-form-item>
        <el-form-item label="是否需要回执" prop="receiptRequired">
          <el-input v-model="form.receiptRequired" placeholder="请输入是否需要回执" />
        </el-form-item>
        <el-form-item label="降级策略" prop="downgradeStrategy">
          <el-input v-model="form.downgradeStrategy" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="熔断策略" prop="circuitBreakerStrategy">
          <el-input v-model="form.circuitBreakerStrategy" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="启用日期" prop="startDate">
          <el-date-picker v-model="form.startDate" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择启用日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止日期" prop="endDate">
          <el-date-picker v-model="form.endDate" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择终止日期">
          </el-date-picker>
        </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="Vendorconfig" lang="ts">
import { listVendorconfig, getVendorconfig, delVendorconfig, addVendorconfig, updateVendorconfig } from '@/api/msg/vendorconfig';
import { VendorconfigVO, VendorconfigQuery, VendorconfigForm } from '@/api/msg/vendorconfig/types';

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

const vendorconfigList = ref<VendorconfigVO[]>([]);
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 vendorconfigFormRef = ref<ElFormInstance>();

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

const initFormData: VendorconfigForm = {
  vendorId: undefined,
  serviceType: undefined,
  vendorName: undefined,
  enableStatus: undefined,
  sendRatio: undefined,
  receiptRequired: undefined,
  downgradeStrategy: undefined,
  circuitBreakerStrategy: undefined,
  startDate: undefined,
  endDate: undefined,
  modifyTime: undefined
};
const data = reactive<PageData<VendorconfigForm, VendorconfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serviceType: undefined,
    vendorName: undefined,
    enableStatus: undefined,
    sendRatio: undefined,
    receiptRequired: undefined,
    downgradeStrategy: undefined,
    circuitBreakerStrategy: undefined,
    startDate: undefined,
    endDate: undefined,
    sendChannelNumber: undefined,
    modifyTime: undefined,
    params: {}
  },
  rules: {
    vendorId: [{ required: true, message: '服务商唯一标识不能为空', trigger: 'blur' }],
    serviceType: [{ required: true, message: '服务类型不能为空', trigger: 'change' }],
    vendorName: [{ required: true, message: '服务商名称不能为空', trigger: 'blur' }],
    enableStatus: [{ required: true, message: '启用状态不能为空', trigger: 'change' }],
    sendRatio: [{ required: true, message: '发送比例不能为空', trigger: 'blur' }],
    receiptRequired: [{ required: true, message: '是否需要回执不能为空', trigger: 'blur' }],
    downgradeStrategy: [{ required: true, message: '降级策略不能为空', trigger: 'blur' }],
    circuitBreakerStrategy: [{ required: true, message: '熔断策略不能为空', trigger: 'blur' }]
  }
});

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

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

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: VendorconfigVO[]) => {
  ids.value = selection.map((item) => item.vendorId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加服务商配置';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: VendorconfigVO) => {
  reset();
  const _vendorId = row?.vendorId || ids.value[0];
  const res = await getVendorconfig(_vendorId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改服务商配置';
};

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

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

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

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