<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="isVerified">
              <el-select v-model="queryParams.isVerified" placeholder="请选择核销状态" clearable>
                <el-option label="未核销" :value="false" />
                <el-option label="已核销" :value="true" />
              </el-select>
            </el-form-item>
            <el-form-item label="服务类型" prop="serviceId">
              <el-select v-model="queryParams.serviceId" placeholder="选项" clearable>
                <el-option v-for="item in itemOptionsType" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户姓名" prop="userRealName">
              <el-input v-model="queryParams.userRealName" placeholder="请输入用户姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="服务名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入服务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属联赛" prop="leagueTournamentId">
              <el-select v-model="queryParams.leagueTournamentId" placeholder="请选择联赛" clearable>
                <el-option v-for="item in leagueTournamentOptions" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单时间">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:serviceOrder:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:serviceOrder:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:serviceOrder:remove']"
              >删除</el-button
            >
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:serviceOrder:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="serviceOrderList">
        <el-table-column label="编号" align="center" prop="id" v-if="true" />
        <el-table-column label="用户昵称" align="center" prop="userNickname" />
        <el-table-column label="用户姓名" align="center" prop="userRealName" />
        <el-table-column label="用户身份证" align="center" prop="userIdCard" width="110" />
        <el-table-column label="账号ID" align="center" prop="userId" />
        <el-table-column label="服务类型" align="center" prop="serviceName" />
        <el-table-column label="服务门店" align="center" prop="storeName" />
        <el-table-column label="服务名称" align="center" prop="productName" />
        <el-table-column label="所属联赛" align="center" prop="leagueName" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="核销状态" align="center" prop="isVerified" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.isVerified ? 'success' : 'info'">
              {{ scope.row.isVerified ? '已核销' : '未核销' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="核销道具" align="center" prop="verifiedItemName" />
        <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="核销时间" align="center" prop="verifyTime" width="180">
          <template #default="scope">
            <span v-if="scope.row.verifyTime">{{ parseTime(scope.row.verifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="截止核销时间" align="center" prop="expireTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</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
                link
                type="success"
                icon="Check"
                @click="handleVerify(scope.row)"
                v-if="!scope.row.isVerified"
                v-hasPermi="['physical:serviceOrder:edit']"
              >
                核销
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改实体服务订单管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="serviceOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="userNickname">
          <el-input v-model="form.userNickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户真实姓名" prop="userRealName">
          <el-input v-model="form.userRealName" placeholder="请输入用户真实姓名" />
        </el-form-item>
        <el-form-item label="用户身份证号" prop="userIdCard">
          <el-input v-model="form.userIdCard" placeholder="请输入用户身份证号" />
        </el-form-item>
        <el-form-item label="用户手机号" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="服务分类ID" prop="serviceId">
          <el-input v-model="form.serviceId" placeholder="请输入服务分类ID" />
        </el-form-item>
        <el-form-item label="服务分类名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务分类名称" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="核销门店ID" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入核销门店ID" />
        </el-form-item>
        <el-form-item label="门店名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="活动名称" prop="leagueName">
          <el-input v-model="form.leagueName" placeholder="请输入活动名称" />
        </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="ServiceOrder" lang="ts">
import {
  listServiceOrder,
  getServiceOrder,
  delServiceOrder,
  addServiceOrder,
  updateServiceOrder,
  verifyOrder
} from '@/api/system/physical/serviceOrder';
import { ServiceOrderVO, ServiceOrderQuery, ServiceOrderForm } from '@/api/system/physical/serviceOrder/types';
import { parseTime } from '@/utils/dateUtils';
import { ElSelect } from 'element-plus';
import { ref } from 'vue';
import { selectAllPhysicalTagsSelList } from '@/api/system/physical/tag';
import { LeagueTournamentVO } from '@/api/system/physical/leagueTournament/types';
import { selectPhysicalLeagueTournamentSelList } from '@/api/system/physical/leagueTournament';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const serviceOrderList = ref<ServiceOrderVO[]>([]);
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 serviceOrderFormRef = ref<ElFormInstance>();

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

const initFormData: ServiceOrderForm = {
  id: undefined,
  userId: undefined,
  userNickname: undefined,
  userRealName: undefined,
  userIdCard: undefined,
  userPhone: undefined,
  orderNo: undefined,
  serviceId: undefined,
  serviceName: undefined,
  productId: undefined,
  productName: undefined,
  storeId: undefined,
  storeName: undefined,
  leagueTournamentId: undefined,
  leagueName: undefined,
  orderTime: undefined,
  verifyTime: undefined,
  expireTime: undefined,
  isVerified: undefined,
  verifiedItemId: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  deletedAt: undefined
};
const data = reactive<PageData<ServiceOrderForm, ServiceOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    userNickname: undefined,
    userRealName: undefined,
    userIdCard: undefined,
    userPhone: undefined,
    orderNo: undefined,
    serviceId: undefined,
    serviceName: undefined,
    productId: undefined,
    productName: undefined,
    storeId: undefined,
    storeName: undefined,
    leagueTournamentId: undefined,
    leagueName: undefined,
    orderTime: undefined,
    verifyTime: undefined,
    expireTime: undefined,
    isVerified: undefined,
    verifiedItemId: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    deletedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    userRealName: [{ required: true, message: '用户真实姓名不能为空', trigger: 'blur' }],
    userIdCard: [{ required: true, message: '用户身份证号不能为空', trigger: 'blur' }],
    orderNo: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
    serviceId: [{ required: true, message: '服务分类ID不能为空', trigger: 'blur' }],
    serviceName: [{ required: true, message: '服务分类名称不能为空', trigger: 'blur' }],
    productId: [{ required: true, message: '产品SKU ID不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    storeId: [{ required: true, message: '核销门店ID不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
    leagueTournamentId: [{ required: true, message: '所属联赛/活动ID不能为空', trigger: 'blur' }],
    orderTime: [{ required: true, message: '下单时间不能为空', trigger: 'blur' }],
    isVerified: [{ required: true, message: '核销状态：0-未核销，1-已核销不能为空', trigger: 'blur' }],
    createdAt: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
    updatedAt: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }]
  }
});

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

/** 查询实体服务订单管理列表 */
const getList = async () => {
  loading.value = true;
  const params = {
    ...queryParams.value,
    startTime: dateRange.value?.[0] || undefined,
    endTime: dateRange.value?.[1] || undefined
  };
  const res = await listServiceOrder(params);
  serviceOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ServiceOrderVO[]) => {
  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?: ServiceOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getServiceOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改';
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: ServiceOrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除实体服务订单管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delServiceOrder(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/serviceOrder/export',
    {
      ...queryParams.value
    },
    `服务订单管理${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
onMounted(() => {
  getList();
  loadItemStructuresOptions();
  loadLeagueTournamentOptions();
});
const handleVerify = async (row: ServiceOrderVO) => {
  await proxy?.$modal.confirm(`确认要核销订单吗？`);

  const updateData: ServiceOrderForm = {
    ...row,
    isVerified: true,
    verifyTime: new Date().toISOString()
  };

  await verifyOrder(updateData);
  proxy?.$modal.msgSuccess('核销成功');
  await getList();
};
const itemOptionsType = ref<{ id: number; label: string }[]>([]);
const loadItemStructuresOptions = () => loadOptions(selectAllPhysicalTagsSelList, itemOptionsType);
const loadOptions = async (apiFunc: () => Promise<any>, targetRef: any, labelKey: string = 'serviceName', extraKeys?: string[]) => {
  try {
    const res = await apiFunc();
    if (res.code === 200) {
      targetRef.value = (res.data as unknown as any[]).map((item) => {
        const result: any = {
          id: item.id,
          label: item[labelKey]
        };
        if (extraKeys) {
          extraKeys.forEach((key) => {
            result[key] = item[key];
          });
        }
        return result;
      });
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
const dateRange = ref<string[]>([]);
const leagueTournamentOptions = ref<LeagueTournamentVO[]>([]);

const loadLeagueTournamentOptions = async () => {
  try {
    const res = await selectPhysicalLeagueTournamentSelList();
    if (res.code === 200 && Array.isArray(res.data)) {
      leagueTournamentOptions.value = res.data;
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
</script>
