<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="channelName">
              <el-input v-model="queryParams.channelName" placeholder="请输入渠道名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="渠道类型" prop="channelType">
              <el-select v-model="queryParams.channelType" placeholder="渠道类型" clearable style="width: 140px">
                <el-option v-for="opt in channelTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="推荐人" prop="referrer">
              <el-input v-model="queryParams.referrer" placeholder="请输入推荐人" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 120px">
                <el-option v-for="opt in channelStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <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-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5"><el-button v-hasPermi="['edu:channel:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button></el-col>
          <el-col :span="1.5"><el-button v-hasPermi="['edu:channel:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button></el-col>
          <el-col :span="1.5"><el-button v-hasPermi="['edu:channel:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button></el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="渠道名称" align="center" prop="channelName" width="150" show-overflow-tooltip />
        <el-table-column label="渠道类型" align="center" prop="channelType" width="100">
          <template #default="scope">
            <span>{{ getChannelTypeLabel(scope.row.channelType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐人" align="center" prop="referrer" width="100" show-overflow-tooltip />
        <el-table-column label="联系电话" align="center" prop="contactPhone" width="130" />
        <el-table-column label="佣金比例(%)" align="center" prop="commissionRate" width="110" />
        <el-table-column label="佣金金额" align="center" prop="commissionAmount" width="110" />
        <el-table-column label="推荐学生数" align="center" prop="studentCount" width="100" />
        <el-table-column label="转化学生数" align="center" prop="convertedCount" width="100" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)" size="small">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="140" show-overflow-tooltip />
        <el-table-column label="操作" width="140" align="center" fixed="right">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top"><el-button v-hasPermi="['edu:channel:edit']" link type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button></el-tooltip>
            <el-tooltip content="删除" placement="top"><el-button v-hasPermi="['edu:channel:remove']" link type="primary" icon="Delete" @click="handleDelete(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="640px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input v-model="form.channelName" placeholder="请输入渠道名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道类型" prop="channelType">
              <el-select v-model="form.channelType" placeholder="请选择渠道类型" style="width: 100%">
                <el-option v-for="opt in channelTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="推荐人" prop="referrer">
              <el-input v-model="form.referrer" placeholder="请输入推荐人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="佣金比例(%)">
              <el-input-number v-model="form.commissionRate" :precision="2" :min="0" :max="100" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="佣金金额">
              <el-input-number v-model="form.commissionAmount" :precision="2" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="推荐学生数">
              <el-input-number v-model="form.studentCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转化学生数">
              <el-input-number v-model="form.convertedCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option v-for="opt in channelStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduChannel" lang="ts">
import { listChannel, getChannel, addChannel, updateChannel, delChannel } from '@/api/edu/channel';
import { ChannelQuery, ChannelVO, ChannelForm, channelTypeOptions, channelStatusOptions } from '@/api/edu/channel/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dataList = ref<ChannelVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();
const dialog = reactive<{ visible: boolean; title: string }>({ visible: false, title: '' });

const data = reactive<PageData<ChannelForm, ChannelQuery>>({
  form: { status: '0', studentCount: 0, convertedCount: 0 },
  queryParams: { pageNum: 1, pageSize: 10, channelName: '', channelType: '', referrer: '', status: '' },
  rules: {
    channelName: [{ required: true, message: '渠道名称不能为空', trigger: 'blur' }],
    channelType: [{ required: true, message: '渠道类型不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);

const getChannelTypeLabel = (v: string) => channelTypeOptions.find((o) => o.value === v)?.label || v;
const getStatusLabel = (v: string) => channelStatusOptions.find((o) => o.value === v)?.label || v;
const getStatusTag = (v: string) => channelStatusOptions.find((o) => o.value === v)?.elTagType || 'info';
const getList = async () => { loading.value = true; const res = await listChannel(queryParams.value); dataList.value = res.rows; total.value = res.total; loading.value = false; };
const handleQuery = () => { queryParams.value.pageNum = 1; getList(); };
const resetQuery = () => { queryFormRef.value?.resetFields(); handleQuery(); };
const handleSelectionChange = (selection: ChannelVO[]) => { ids.value = selection.map((item) => item.id); single.value = selection.length != 1; multiple.value = !selection.length; };
const reset = () => { form.value = { status: '0', studentCount: 0, convertedCount: 0 }; formRef.value?.resetFields(); };
const handleAdd = () => { reset(); dialog.title = '新增渠道'; dialog.visible = true; };
const handleEdit = async (row: ChannelVO) => { reset(); const res = await getChannel(row.id); Object.assign(form.value, res.data); dialog.title = '编辑渠道'; dialog.visible = true; };

const submitForm = async () => {
  await formRef.value?.validate();
  if (form.value.id) { await updateChannel(form.value); proxy?.$modal.msgSuccess('修改成功'); }
  else { await addChannel(form.value); proxy?.$modal.msgSuccess('新增成功'); }
  dialog.visible = false; await getList();
};
const handleDelete = async (row?: ChannelVO) => { const delIds = row?.id || ids.value; await proxy?.$modal.confirm('是否确认删除？'); await delChannel(delIds); proxy?.$modal.msgSuccess('删除成功'); await getList(); };
const handleExport = () => { proxy?.download('edu/channel/export', { ...queryParams.value }, `channel_${new Date().getTime()}.xlsx`); };

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