<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :parse-data="parseData"
        v-model:selection="selection"
        :scroll="{ x: 800 }"
        cache-key="proUserFeedbackTable"
      >
        <template #toolbar>
          <search
            :selection="selection"
            @search="reload"
            @add="openEdit"
            @remove="removeBatch"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'images'">
            <ele-image-upload
              v-model:value="record.thumbnail"
              :limit="9"
              disabled="true"
              :item-style="{ width: '60px', height: '60px' }"
            />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-popconfirm
                placement="topRight"
                title="确定要删除此评价吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <feedbackEdit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    PlusOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { messageLoading, toDateString } from 'ele-admin-pro/es';
  import feedbackEdit from './components/feedback-edit.vue';
  import Search from './components/search.vue';
  import {
    pageUserFeedback,
    removeUserFeedback,
    removeBatchUserFeedbacks
  } from '@/api/user/feedback';
  import type {
    UserFeedback,
    UserFeedbackParam
  } from '@/api/user/feedback/model';

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '用户信息',
      dataIndex: 'nickname',
      showSorterTooltip: false
    },
    {
      title: '反馈内容',
      dataIndex: 'content'
    },
    {
      title: '图片附件',
      dataIndex: 'images',
      key: 'images'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center'
    }
  ]);

  // 表格选中数据
  const selection = ref<UserFeedback[]>([]);

  // 当前编辑数据
  const current = ref<UserFeedback | null>(null);

  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const type = ref('goodsName');
  const searchText = ref('');

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    if (type.value == 'goodsName') {
      where.goodsName = searchText.value;
    }
    if (type.value == 'goodsCode') {
      where.goodsCode = searchText.value;
    }
    if (type.value == 'userId') {
      where.userId = searchText.value;
    }
    return pageUserFeedback({ ...where, ...orders, page, limit });
  };

  /* 整理数据结构 */
  const parseData = (data: any) => {
    return {
      count: data.count,
      list: data.list.map((d) => {
        // 处理图片附件
        if (d.images) {
          d.images = JSON.parse(d.images);
          d.thumbnail = [];
          if (d.images.length > 0) {
            d.images.map((pic, index) => {
              d.thumbnail.push({
                url: pic.url
              });
            });
          }
        }
        return d;
      })
    };
  };

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

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

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

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