<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="21">
            <span>标签类别信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:customerTag:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="customerTagList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标签名称" align="center" prop="tagName" />
        <el-table-column label="匹配商品标签" align="center" prop="productTagIds">
          <template #default="scope">
            <span v-if="scope.row.productTagIds">
              {{ formatProductTags(scope.row.productTagIds) }}
            </span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['customer:customerTag:edit']">编辑</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['customer:customerTag:remove']"
              >删除</el-button
            >
          </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="600px" append-to-body>
      <el-form ref="customerTagFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="关联产品标签" prop="productTagIds">
          <div class="w-full">
            <!-- 已选择的标签 -->
            <div class="mb-2" v-if="selectedProductTags.length > 0">
              <el-tag v-for="tagId in selectedProductTags" :key="tagId" closable @close="removeTag(tagId)" class="mr-2 mb-2" type="primary">
                {{ getTagName(tagId) }}
              </el-tag>
            </div>
            <!-- 搜索框 -->
            <div class="flex gap-2 mb-2">
              <el-input v-model="searchKeyword" placeholder="请输入关联名称" clearable />
              <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
            <div class="text-sm text-gray-500 mb-2">
              已选择 <span class="text-red-500">{{ selectedProductTags.length }}</span> 条
            </div>
            <!-- 可选标签列表 -->
            <div class="border rounded bg-gray-50" style="min-height: 200px; max-height: 300px; overflow-y: auto">
              <!-- 表头 -->
              <div class="bg-gray-100 px-4 py-3 border-b flex items-center">
                <el-checkbox v-model="selectAll" @change="handleSelectAll" class="mr-3" />
                <span class="font-medium">可选标签</span>
              </div>
              <!-- 内容区 -->
              <div class="p-4">
                <div class="text-center text-gray-400 py-4" v-if="filteredProductTags.length === 0">暂无数据</div>
                <el-checkbox-group v-else v-model="selectedProductTags" @change="handleProductTagChange" class="flex flex-wrap gap-2">
                  <el-checkbox v-for="tag in filteredProductTags" :key="tag.id" :value="tag.id">
                    {{ tag.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in is_enabled" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </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="CustomerTag" lang="ts">
import { listCustomerTag, getCustomerTag, delCustomerTag, addCustomerTag, updateCustomerTag } from '@/api/customer/customerTag';
import { CustomerTagVO, CustomerTagQuery, CustomerTagForm } from '@/api/customer/customerTag/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { is_enabled } = toRefs<any>(proxy?.useDict('is_enabled'));

const customerTagList = ref<CustomerTagVO[]>([]);
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 productTagList = ref([
  { id: 1, name: '热销商品' },
  { id: 2, name: '旅游首选' },
  { id: 3, name: '物美价廉' },
  { id: 4, name: '性价比高' },
  { id: 5, name: '价格便宜' }
]);

const searchKeyword = ref('');
const selectedProductTags = ref<number[]>([]);
const selectAll = ref(false);
const filteredProductTags = computed(() => {
  if (!searchKeyword.value) {
    return productTagList.value;
  }
  return productTagList.value.filter((tag) => tag.name.toLowerCase().includes(searchKeyword.value.toLowerCase()));
});

const queryFormRef = ref<ElFormInstance>();
const customerTagFormRef = ref<ElFormInstance>();

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

const initFormData: CustomerTagForm = {
  id: undefined,
  tagName: undefined,
  productTagIds: undefined,
  status: '0',
  remark: undefined
};
const data = reactive<PageData<CustomerTagForm, CustomerTagQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tagName: undefined,
    productTagIds: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    tagName: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }]
  }
});

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

/** 查询客户标签列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomerTag(queryParams.value);
  customerTagList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  customerTagFormRef.value?.resetFields();
  selectedProductTags.value = [];
  searchKeyword.value = '';
  selectAll.value = false;
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerTagVO[]) => {
  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?: CustomerTagVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCustomerTag(_id);
  Object.assign(form.value, res.data);
  // 回显已选择的商品标签
  if (res.data.productTagIds) {
    selectedProductTags.value = res.data.productTagIds.split(',').map(Number);
  }
  dialog.visible = true;
  dialog.title = '修改客户标签';
};

/** 搜索商品标签 */
const handleSearch = () => {
  // 搜索逻辑已通过 computed 实现
};

/** 商品标签选择变化 */
const handleProductTagChange = (value: number[]) => {
  form.value.productTagIds = value.join(',');
  updateSelectAllState();
};

/** 根据标签ID获取标签名称 */
const getTagName = (tagId: number) => {
  const tag = productTagList.value.find((t) => t.id === tagId);
  return tag ? tag.name : '';
};

/** 移除已选择的标签 */
const removeTag = (tagId: number) => {
  selectedProductTags.value = selectedProductTags.value.filter((id) => id !== tagId);
  form.value.productTagIds = selectedProductTags.value.join(',');
  updateSelectAllState();
};

/** 全选/取消全选 */
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedProductTags.value = filteredProductTags.value.map((tag) => tag.id);
  } else {
    selectedProductTags.value = [];
  }
  form.value.productTagIds = selectedProductTags.value.join(',');
};

/** 更新全选状态 */
const updateSelectAllState = () => {
  selectAll.value = filteredProductTags.value.length > 0 && selectedProductTags.value.length === filteredProductTags.value.length;
};

/** 格式化商品标签显示（将ID转换为名称） */
const formatProductTags = (productTagIds: string) => {
  if (!productTagIds) return '-';
  const ids = productTagIds.split(',').map(Number);
  const names = ids
    .map((id) => {
      const tag = productTagList.value.find((t) => t.id === id);
      return tag ? tag.name : '';
    })
    .filter((name) => name);
  return names.join('、') || '-';
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerTagVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户标签编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delCustomerTag(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/customerTag/export',
    {
      ...queryParams.value
    },
    `customerTag_${new Date().getTime()}.xlsx`
  );
};

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