<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">服务管理 (列表)</span>
          </div>
          <div class="header-right">
            <el-select v-model="queryParams.classificationId" placeholder="全部分类" clearable @change="handleQuery"
              style="width: 180px; margin-right: 12px;">
              <el-option label="全部" :value="undefined" />
              <el-option v-for="item in classificationList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['service:list:add']">新增服务</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="serviceList" style="width: 100%"
        :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
        <el-table-column label="排序权重" align="center" prop="sort" width="100" />
        <el-table-column label="服务名称" prop="name" min-width="150">
          <template #default="scope">
            <span class="service-name-text">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务图标" align="center" width="120">
          <template #default="scope">
            <div class="icon-wrapper">
              <image-preview :src="scope.row.iconUrl" :width="40" :height="40" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属分类" align="center" width="120">
          <template #default="scope">
            <span>{{ getClassificationName(scope.row.classificationId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务模式" align="center" width="150">
          <template #default="scope">
            <el-tag :type="getModeTagType(scope.row.mode)" size="small" effect="light" class="mode-tag">
              {{ getModeLabel(scope.row.mode) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单服务费" align="center" width="120">
          <template #default="scope">
            <span class="price-text">¥{{ formatPrice(scope.row.price) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注说明" prop="remark" min-width="250" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" width="180">
          <template #default="scope">
            <span class="time-text">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" width="140" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                v-hasPermi="['service:list:edit']">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)"
                v-hasPermi="['service:list:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改服务项目对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body class="service-dialog">
      <el-form ref="serviceFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务图标" prop="icon">
          <image-upload v-model="form.icon" :limit="1" />
        </el-form-item>
        <el-form-item label="服务模式" prop="mode">
          <el-radio-group v-model="form.mode">
            <el-radio v-for="mode in modeList" :key="mode.id" :label="mode.value">
              {{ mode.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属分类" prop="classificationId">
          <el-select v-model="form.classificationId" placeholder="请选择所属分类" clearable style="width: 100%">
            <el-option v-for="item in classificationList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序权重" prop="sort">
          <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="订单服务费" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.01" controls-position="right"
            style="width: 100%">
            <template #prefix>¥</template>
          </el-input-number>
          <div style="color: #909399; font-size: 12px; margin-top: 4px;">单位:元</div>
        </el-form-item>
        <el-form-item label="服务介绍" prop="introduction">
          <editor v-model="form.introduction" :min-height="200" />
        </el-form-item>
        <el-form-item label="下单须知" prop="orderInstruction">
          <editor v-model="form.orderInstruction" :min-height="200" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注说明" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="打卡备注" prop="clockInRemark">
          <div class="w-full">
            <el-card v-for="(item, index) in clockInRemarkList" :key="index" class="step-card" shadow="never">
              <template #header>
                <div class="step-header">
                  <span>步骤 {{ index + 1 }}</span>
                </div>
              </template>
              <el-form-item label="步骤标题" label-width="80px" class="inner-form-item" required>
                <el-input v-model="item.title" placeholder="请输入步骤标题" />
              </el-form-item>
              <el-form-item label="打卡备注" label-width="80px" class="inner-form-item last" required>
                <el-input v-model="item.remark" type="textarea" placeholder="请输入当前步骤打卡备注" />
              </el-form-item>
            </el-card>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm()">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Service" lang="ts">
/**
 * @Author: Antigravity
 */

import { listService, getService, delService, addService, updateService } from '@/api/service/list';
import { ServiceVO, ServiceQuery, ServiceForm } from '@/api/service/list/types';
import { list as listMode } from '@/api/service/mode';
import { SysServiceModeVo } from '@/api/service/mode/types';
import { listAllClassification } from '@/api/service/classification';
import { ClassificationVO } from '@/api/service/classification/types';

interface ClockInRemarkItem {
  step: number;
  title: string;
  remark: string;
}

const clockInRemarkList = ref<ClockInRemarkItem[]>([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const serviceList = ref<ServiceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const total = ref(0);
const modeList = ref<SysServiceModeVo[]>([]);
const classificationList = ref<ClassificationVO[]>([]);

const serviceFormRef = ref<ElFormInstance>();

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

const initFormData: ServiceForm = {
  id: undefined,
  name: undefined,
  icon: undefined,
  mode: undefined,
  sort: undefined,
  remark: undefined,
  clockInRemark: undefined,
  introduction: undefined,
  orderInstruction: undefined,
  classificationId: undefined,
  price: undefined,
  tenantId: undefined
};

const data = reactive<PageData<ServiceForm, ServiceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    classificationId: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '服务名称不能为空', trigger: 'blur' }],
    icon: [{ required: true, message: '服务图标不能为空', trigger: 'blur' }],
    mode: [{ required: true, message: '服务模式不能为空', trigger: 'change' }],
    classificationId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
    sort: [{ required: true, message: '排序权重不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '订单服务费不能为空', trigger: 'blur' }],
    introduction: [{ required: true, message: '服务介绍不能为空', trigger: 'blur' }],
    orderInstruction: [{ required: true, message: '下单须知不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注说明不能为空', trigger: 'blur' }]
  }
});

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

/** 查询服务项目列表 */
const getList = async () => {
  loading.value = true;
  const res = await listService(queryParams.value);
  serviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 获取服务模式列表 */
const getModeList = async () => {
  try {
    const res = await listMode();
    modeList.value = res.data || res;
  } catch (error) {
    console.error('获取服务模式列表失败:', error);
  }
};

/** 获取分类列表 */
const getClassificationList = async () => {
  try {
    const res = await listAllClassification();
    classificationList.value = res.data || [];
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

/** 根据服务模式获取 Tag 类型 */
const getModeTagType = (value: any) => {
  const map: any = { 'round': 'primary', 'one-way': 'info' };
  return map[value] || 'primary';
};

/** 根据服务模式value获取label */
const getModeLabel = (value: any): string => {
  const mode = modeList.value.find((item) => item.value === value);
  return mode ? mode.label : value;
};

/** 根据分类ID获取分类名称 */
const getClassificationName = (classificationId: number): string => {
  if (!classificationId) return '-';
  const classification = classificationList.value.find((item) => item.id === classificationId);
  return classification ? classification.name : '-';
};

/** 格式化价格(分转元) */
const formatPrice = (price: number): string => {
  if (price === undefined || price === null) return '0.00';
  return (price / 100).toFixed(2);
};

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

/** 初始打卡备注三步骤 */
const getInitialClockInRemarks = (): ClockInRemarkItem[] => {
  return Array.from({ length: 3 }, (_, i) => ({
    step: i + 1,
    title: '',
    remark: ''
  }));
};

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: ServiceVO) => {
  reset();
  const res = await getService(row.id);
  Object.assign(form.value, res.data);

  if (form.value.price !== undefined && form.value.price !== null) {
    form.value.price = form.value.price / 100;
  }


  if (form.value.clockInRemark) {
    try {
      const parsed = JSON.parse(form.value.clockInRemark);
      if (Array.isArray(parsed)) {
        clockInRemarkList.value = getInitialClockInRemarks().map((item, index) => {
          return parsed[index] ? { ...item, ...parsed[index] } : item;
        });
      }
    } catch (e) {
      clockInRemarkList.value = getInitialClockInRemarks();
    }
  }
  dialog.visible = true;
  dialog.title = '修改服务项目';
};

/** 提交按钮 */
const submitForm = () => {
  serviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      for (let i = 0; i < clockInRemarkList.value.length; i++) {
        const item = clockInRemarkList.value[i];
        if (!item.title) {
          proxy?.$modal.msgError(`请填写步骤 ${i + 1} 的标题`);
          return;
        }
        if (!item.remark) {
          proxy?.$modal.msgError(`请填写步骤 ${i + 1} 的备注`);
          return;
        }
      }

      form.value.clockInRemark = clockInRemarkList.value.length > 0 ? JSON.stringify(clockInRemarkList.value) : undefined;

      // 编码富文本字段为BASE64
      const submitData = { ...form.value };
      if (submitData.introduction) {
        submitData.introduction = btoa(unescape(encodeURIComponent(submitData.introduction)));
      }
      if (submitData.orderInstruction) {
        submitData.orderInstruction = btoa(unescape(encodeURIComponent(submitData.orderInstruction)));
      }

      if (submitData.price !== undefined && submitData.price !== null) {
        submitData.price = Math.round(submitData.price * 100);
      }

      buttonLoading.value = true;
      if (submitData.id) {
        await updateService(submitData).finally(() => (buttonLoading.value = false));
      } else {
        await addService(submitData).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: ServiceVO) => {
  await proxy?.$modal.confirm(`是否确认删除服务项目"${row.name}"？`);
  loading.value = true;
  await delService(row.id).finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background-color: #f5f7f9;
  min-height: 100%;
}

.table-card {
  border: none;
  border-radius: 8px;

  :deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.service-name-text {
  font-weight: 600;
  color: #333;
}

.icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.mode-tag {
  border: none;
  font-weight: 500;
}

.time-text {
  color: #909399;
  font-size: 13px;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.step-card {
  margin-bottom: 16px;
  border-radius: 8px;
  background-color: #fcfdfe;
  border: 1px dashed #dcdfe6;
  transition: all 0.3s;

  &:hover {
    border-style: solid;
    border-color: var(--el-color-primary);
  }

  .step-header {
    font-size: 13px;
    font-weight: 600;
    color: #606266;
  }

  .inner-form-item {
    margin-bottom: 12px;

    &.last {
      margin-bottom: 0;
    }
  }

  :deep(.el-card__header) {
    padding: 8px 16px;
    background-color: #f0f2f5;
  }
}

:deep(.el-table) {
  --el-table-border-color: #f0f0f0;

  th.el-table__cell {
    font-weight: 600;
  }

  td.el-table__cell {
    padding: 12px 0;
  }
}

/* 优化富文本编辑器容器样式 */
:deep(.editor-container) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: #fff;
  display: flex;
  flex-direction: column;

  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
  }

  .w-e-toolbar {
    border-bottom: 1px solid #f2f6fc !important;
    background-color: #fafafa !important;
    padding: 2px 4px !important;
    border-top: none !important;
    border-left: none !important;
    border-right: none !important;
  }

  .w-e-text-container {
    background-color: #fff !important;
    border: none !important;

    .w-e-text {
      padding: 16px !important;
      line-height: 1.6 !important;
      font-size: 14px;
      color: #333;
    }
  }
}

/* 优化弹窗内部布局 */
.service-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
    max-height: 65vh;
    overflow-y: auto;
  }
}

/* 优化表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 22px;
  
  .el-form-item__label {
    font-weight: 500;
  }
}
</style>
