<template>
  <div class="page-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">履约者标签管理</span>
          <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['fulfiller:tag:add']">新增标签</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
        <el-table-column prop="name" label="标签名称" width="200">
          <template #default="scope">
            <el-tag :type="scope.row.colorType">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'" size="small">
              {{ scope.row.status === 0 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)" v-hasPermi="['fulfiller:tag:edit']">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['fulfiller:tag:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑标签' : '新增标签'" width="400px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="如：非常有耐心" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="colorType">
          <div class="color-picker-group">
            <span
              v-for="item in colorOptions"
              :key="item.value"
              class="color-dot"
              :class="{ active: form.colorType === item.value }"
              :style="{ backgroundColor: item.color }"
              :title="item.label"
              @click="form.colorType = item.value"
            ></span>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="saveTag">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { listTag, addTag, updateTag, delTag } from '@/api/fulfiller/tag';
import type { FlfTagVO, FlfTagForm, FlfTagQuery } from '@/api/fulfiller/tag/types';

const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const total = ref(0);
const tableData = ref<FlfTagVO[]>([]);

const queryParams = reactive<FlfTagQuery>({
  pageNum: 1,
  pageSize: 10,
  category: 'fulfiller'
});

const form = reactive<FlfTagForm>({
  id: undefined,
  name: '',
  colorType: '',
  category: 'fulfiller',
  description: '',
  status: 0
});

const colorOptions = [
  { value: 'info', label: '信息灰', color: '#909399' },
  { value: '', label: '默认蓝', color: '#409eff' },
  { value: 'success', label: '成功绿', color: '#67c23a' },
  { value: 'warning', label: '警告橙', color: '#e6a23c' },
  { value: 'danger', label: '危险红', color: '#f56c6c' }
];

const rules = reactive<FormRules>({
  name: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }]
});

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTag(queryParams);
    tableData.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

const resetForm = () => {
  Object.assign(form, { id: undefined, name: '', colorType: '', category: 'fulfiller', description: '', status: 0 });
  formRef.value?.resetFields();
};

const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: FlfTagVO) => {
  isEdit.value = true;
  resetForm();
  Object.assign(form, {
    id: row.id,
    name: row.name,
    colorType: row.colorType,
    category: row.category,
    description: row.description,
    status: row.status
  });
  dialogVisible.value = true;
};

const handleDelete = (row: FlfTagVO) => {
  ElMessageBox.confirm('确认删除标签「' + row.name + '」吗？', '提示', { type: 'warning' }).then(async () => {
    await delTag(row.id);
    ElMessage.success('删除成功');
    getList();
  }).catch(() => {});
};

const saveTag = async () => {
  await formRef.value?.validate();
  submitLoading.value = true;
  try {
    if (isEdit.value) {
      await updateTag(form);
    } else {
      await addTag(form);
    }
    ElMessage.success(isEdit.value ? '修改成功' : '新增成功');
    dialogVisible.value = false;
    getList();
  } finally {
    submitLoading.value = false;
  }
};

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

<style scoped>
.page-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  font-weight: bold;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.color-picker-group {
  display: flex;
  align-items: center;
  gap: 12px;
}
.color-dot {
  display: inline-block;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  cursor: pointer;
  border: 3px solid transparent;
  transition: border-color 0.2s, box-shadow 0.2s;
}
.color-dot:hover {
  box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
}
.color-dot.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
}
</style>
