<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false" :body-style="{ padding: '16px' }">
        <ele-pro-table
          ref="tableRef"
          row-key="specId"
          :columns="columns"
          :datasource="datasource"
          :customRow="customRow"
          v-model:selection="selection"
          tool-class="ele-toolbar-form"
          class="sys-org-table"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-switch
                :checked="record.status === 0"
                checked-children="显示"
                un-checked-children="隐藏"
                size="small"
                @change="(val: boolean) => toggleStatus(record, val)"
              />
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要同步更新吗？这将把该规格的最新值更新到所有使用该模板的商品中。"
                  @confirm="syncSpec(record)"
                >
                  <a class="ele-text-success">同步更新</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此规格吗？删除后相关商品规格数据将受影响！"
                  @confirm="remove(record)"
                >
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
          <!-- 展开行：规格值管理面板 -->
          <template #expandedRowRender="{ record }">
            <SpecValuePanel :spec="record" />
          </template>
        </ele-pro-table>
      </a-card>

      <!-- 编辑弹窗 -->
      <ShopSpecEdit v-model:visible="showEdit" :data="current" @done="reload" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import { toDateString } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import ShopSpecEdit from './components/shopSpecEdit.vue';
  import SpecValuePanel from './components/specValuePanel.vue';
  import {
    pageShopSpec,
    removeShopSpec,
    removeBatchShopSpec,
    updateShopSpec,
    syncGoodsSpec
  } from '@/api/shop/shopSpec';
  import type { ShopSpec, ShopSpecParam } from '@/api/shop/shopSpec/model';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<ShopSpec[]>([]);
  // 当前编辑数据
  const current = ref<ShopSpec | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    return pageShopSpec({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'specId',
      key: 'specId',
      align: 'center',
      width: 70
    },
    {
      title: '规格名称',
      dataIndex: 'specName',
      key: 'specName',
      align: 'left',
      minWidth: 160
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 90
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      key: 'sortNumber',
      align: 'center',
      width: 80,
      sorter: true
    },
    {
      title: '备注',
      dataIndex: 'comments',
      key: 'comments',
      align: 'left',
      ellipsis: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 120,
      sorter: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd')
    },
    {
      title: '操作',
      key: 'action',
      width: 140,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

  /* 搜索 */
  const reload = (where?: ShopSpecParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: ShopSpec) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 切换显示/隐藏状态 */
  const toggleStatus = (row: ShopSpec, val: boolean) => {
    const newStatus = val ? 0 : 1;
    updateShopSpec({ ...row, status: newStatus })
      .then((msg) => {
        message.success(msg);
        row.status = newStatus;
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 删除单个 */
  const remove = (row: ShopSpec) => {
    const hide = message.loading('请求中..', 0);
    removeShopSpec(row.specId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 同步更新商品规格 */
  const syncSpec = (row: ShopSpec) => {
    const hide = message.loading('正在同步更新..', 0);
    syncGoodsSpec(row.specId!)
      .then((res) => {
        hide();
        const updatedCount = res?.data?.updatedCount ?? 0;
        message.success(`同步完成，已更新 ${updatedCount} 个商品`);
      })
      .catch((e) => {
        hide();
        message.error(e.message || '同步失败');
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的规格吗？删除后相关商品规格数据将受影响！',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchShopSpec(selection.value.map((d) => d.specId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 自定义行属性 */
  const customRow = (record: ShopSpec) => {
    return {
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'ShopSpec'
  };
</script>

<style lang="less" scoped></style>
