<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="packageCode">
              <el-input v-model="queryParams.packageCode" placeholder="请输入编码" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="课包名称" prop="packageName">
              <el-input v-model="queryParams.packageName" placeholder="请输入名称" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="packageType">
              <el-select v-model="queryParams.packageType" placeholder="课包类型" clearable style="width: 160px">
                <el-option v-for="opt in packageTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="学科" prop="subject">
              <el-input v-model="queryParams.subject" 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: 140px">
                <el-option v-for="opt in packageStatusOptions" :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:package:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:package:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:package:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:package: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="packageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编码" align="center" prop="packageCode" width="140" />
        <el-table-column label="课包名称" align="center" prop="packageName" show-overflow-tooltip />
        <el-table-column label="类型" align="center" prop="packageType" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.packageType)">{{ getTypeLabel(scope.row.packageType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学科" align="center" prop="subject" width="90" />
        <el-table-column label="总课时" align="center" prop="totalHours" width="90" />
        <el-table-column label="课次" align="center" prop="lessonCount" width="80" />
        <el-table-column label="挂牌价" align="center" prop="listPrice" width="100" />
        <el-table-column label="销售价" align="center" prop="salePrice" width="100" />
        <el-table-column label="热门" align="center" prop="isHot" width="70">
          <template #default="scope">
            <el-tag v-if="scope.row.isHot === 'Y'" type="danger">热</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="90">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['edu:package:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="scope.row.status === '0' ? '下架' : '上架'" placement="top">
              <el-button
                v-hasPermi="['edu:package:onSale']"
                link
                :type="scope.row.status === '0' ? 'warning' : 'success'"
                :icon="scope.row.status === '0' ? 'Sell' : 'ShoppingCart'"
                @click="handleToggleStatus(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:package: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="920px" append-to-body>
      <el-form ref="packageFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="课包名称" prop="packageName">
              <el-input v-model="form.packageName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课包编码" prop="packageCode">
              <el-input v-model="form.packageCode" placeholder="留空自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课包类型" prop="packageType">
              <el-select v-model="form.packageType" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in packageTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学科" prop="subject">
              <el-input v-model="form.subject" placeholder="如: 数学" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用年级" prop="grade">
              <el-input v-model="form.grade" placeholder="如: 高三" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效期(天)" prop="validDays">
              <el-input-number v-model="form.validDays" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="总课时" prop="totalHours">
              <el-input-number v-model="form.totalHours" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总课次" prop="lessonCount">
              <el-input-number v-model="form.lessonCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单次人数" prop="maxStudents">
              <el-input-number v-model="form.maxStudents" :min="1" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="挂牌价" prop="listPrice">
              <el-input-number v-model="form.listPrice" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售价" prop="salePrice">
              <el-input-number v-model="form.salePrice" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成本价" prop="costPrice">
              <el-input-number v-model="form.costPrice" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="赠送课时" prop="giftHours">
              <el-input-number v-model="form.giftHours" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="每课时时长" prop="hoursPerLesson">
              <el-input-number v-model="form.hoursPerLesson" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="opt in packageStatusOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="计费方式" prop="billingType">
          <el-radio-group v-model="form.billingType">
            <el-radio v-for="opt in billingTypeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.packageType === 'SERVICE'" label="升学类别" prop="serviceCategory">
          <el-select v-model="form.serviceCategory" placeholder="请选择升学服务类别" style="width: 280px">
            <el-option v-for="opt in serviceCategoryOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="课包说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入课包说明" />
        </el-form-item>

        <!-- 价格策略子表 -->
        <el-divider content-position="left">价格策略</el-divider>
        <el-table border :data="form.strategies" size="small">
          <el-table-column label="策略名" min-width="120" align="center">
            <template #default="{ row }">
              <el-input v-model="row.strategyName" placeholder="策略名" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120" align="center">
            <template #default="{ row }">
              <el-select v-model="row.strategyType" placeholder="类型" size="small">
                <el-option v-for="opt in strategyTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="折扣率" width="120" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.discountRate" :min="0" :max="1" :step="0.1" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="减现" width="120" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.reduceAmount" :min="0" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="优先级" width="100" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.priority" :min="0" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" icon="Delete" @click="form.strategies.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-2" type="primary" plain icon="Plus" size="small" @click="addStrategy">添加策略</el-button>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduPackage" lang="ts">
import { listPackage, getPackage, addPackage, updatePackage, delPackage, changePackageStatus } from '@/api/edu/package';
import {
  PackageForm,
  PackageQuery,
  PackageVO,
  packageTypeOptions,
  packageStatusOptions,
  strategyTypeOptions,
  StrategyForm
} from '@/api/edu/package/types';
import { billingTypeOptions, serviceCategoryOptions } from '@/api/edu/milestone/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const packageList = ref<PackageVO[]>([]);
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 packageFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

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

const initFormData: PackageForm = {
  id: undefined,
  packageCode: '',
  packageName: '',
  packageType: 'PACKAGE',
  subject: '',
  grade: '',
  totalHours: 0,
  lessonCount: 0,
  validDays: 365,
  maxStudents: 1,
  listPrice: 0,
  salePrice: 0,
  costPrice: 0,
  giftHours: 0,
  hoursPerLesson: 1,
  description: '',
  coverUrl: '',
  isHot: 'N',
  isGift: 'N',
  billingType: 'HOURS',
  serviceCategory: '',
  status: '0',
  saleStartAt: '',
  saleEndAt: '',
  remark: '',
  strategies: []
};

const data = reactive<PageData<PackageForm, PackageQuery>>({
  form: { ...initFormData, strategies: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    packageCode: '',
    packageName: '',
    packageType: '',
    subject: '',
    grade: '',
    status: '',
    isHot: ''
  },
  rules: {
    packageName: [{ required: true, message: '课包名称不能为空', trigger: 'blur' }],
    packageType: [{ required: true, message: '课包类型不能为空', trigger: 'change' }],
    totalHours: [{ required: true, message: '总课时不能为空', trigger: 'blur' }],
    listPrice: [{ required: true, message: '挂牌价不能为空', trigger: 'blur' }],
    salePrice: [{ required: true, message: '销售价不能为空', trigger: 'blur' }]
  }
});

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

const getTypeLabel = (val: string) => packageTypeOptions.find((o) => o.value === val)?.label || val;
const getTypeTag = (val: string) => packageTypeOptions.find((o) => o.value === val)?.elTagType || 'info';
const getStatusLabel = (val: string) => packageStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => packageStatusOptions.find((o) => o.value === val)?.elTagType || 'info';

const getList = async () => {
  loading.value = true;
  const res = await listPackage(queryParams.value);
  packageList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData, strategies: [] };
  packageFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: PackageVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增课包';
};

const handleUpdate = async (row?: PackageVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getPackage(id);
  Object.assign(form.value, res.data);
  form.value.strategies = res.data.strategies || [];
  dialog.visible = true;
  dialog.title = '修改课包';
};

const submitForm = () => {
  packageFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await updatePackage(form.value) : await addPackage(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

const handleDelete = async (row?: PackageVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除课包编号为"' + delIds + '"的数据项？');
  await delPackage(delIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const handleExport = () => {
  proxy?.download('edu/package/export', { ...queryParams.value }, `package_${new Date().getTime()}.xlsx`);
};

/** 上下架切换 */
const handleToggleStatus = async (row: PackageVO) => {
  const target = row.status === '0' ? '1' : '0';
  const text = target === '0' ? '上架' : '下架';
  await proxy?.$modal.confirm(`确认${text}课包"${row.packageName}"？`);
  await changePackageStatus(row.id, target);
  proxy?.$modal.msgSuccess(`${text}成功`);
  await getList();
};

/** 添加策略行 */
const addStrategy = () => {
  const item: StrategyForm = {
    strategyName: '',
    strategyType: 'DISCOUNT',
    conditionType: 'NONE',
    conditionValue: 0,
    discountRate: 1,
    reduceAmount: 0,
    giftHours: 0,
    cashbackAmount: 0,
    priority: 0,
    startAt: '',
    endAt: '',
    status: '0',
    remark: ''
  };
  form.value.strategies.push(item);
};

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