<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false" :body-style="{ padding: '16px' }">
        <ele-pro-table
          ref="tableRef"
          row-key="specValueId"
          :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 === 'specId'">
              {{ specNameMap[record.specId] || record.specId }}
            </template>
            <template v-if="column.key === 'image'">
              <a-image
                v-if="record.image"
                :src="record.image"
                :width="36"
                :height="36"
                style="object-fit: cover; border-radius: 4px"
              />
              <span v-else class="ele-text-secondary">-</span>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此规格值吗？"
                  @confirm="remove(record)"
                >
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>

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

<script lang="ts" setup>
  import { createVNode, ref, reactive, onMounted } 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 ShopSpecValueEdit from './components/shopSpecValueEdit.vue';
  import {
    pageShopSpecValue,
    removeShopSpecValue,
    removeBatchShopSpecValue
  } from '@/api/shop/shopSpecValue';
  import type {
    ShopSpecValue,
    ShopSpecValueParam
  } from '@/api/shop/shopSpecValue/model';
  import { listShopSpec } from '@/api/shop/shopSpec';

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

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

  // specId -> specName 映射表
  const specNameMap = reactive<Record<number, string>>({});

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'specValueId',
      key: 'specValueId',
      align: 'center',
      width: 70
    },
    {
      title: '所属规格',
      dataIndex: 'specId',
      key: 'specId',
      align: 'center',
      width: 120
    },
    {
      title: '规格值',
      dataIndex: 'specValue',
      key: 'specValue',
      align: 'left',
      minWidth: 120
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'image',
      align: 'center',
      width: 70
    },
    {
      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?: ShopSpecValueParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

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

  /* 删除单个 */
  const remove = (row: ShopSpecValue) => {
    const hide = message.loading('请求中..', 0);
    removeShopSpecValue(row.specValueId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .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);
        removeBatchShopSpecValue(selection.value.map((d) => d.specValueId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

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

  // 加载规格名称映射表
  const loadSpecNames = async () => {
    try {
      const list = await listShopSpec();
      (list || []).forEach((s) => {
        if (s.specId !== undefined) {
          specNameMap[s.specId] = s.specName || String(s.specId);
        }
      });
    } catch (e) {
      // ignore
    }
  };

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

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

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