<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import type { InternalRowData } from 'naive-ui/es/data-table/src/interface';
import { fetchGetAllStoreList } from '@/service/api/goods/desk-category';
import {
  fetchGetBackendCommAudit,
  fetchGetBackendCommList,
  fetchGetReply
} from '@/service/api/user-management/user-reviews';
// import { useAuth } from '@/hooks/business/auth';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';

const columns: NaiveUI.TableColumn<InternalRowData>[] = [
  {
    key: 'nickName',
    title: '用户昵称',
    align: 'center',
    width: 200
  },
  {
    key: 'score',
    title: '评分',
    align: 'center',
    width: 250,
    render: row => {
      return (
        <div>
          <div class={'flex text-[12px] text-gray'}>
            <div class={'w-[100px] text-left'}> 商品评价：{row.score}.0 </div>
            <n-rate class={'ml2'} size="small" readonly default-value={row.score} />
          </div>
          <div class={'flex text-[12px] text-gray'}>
            <div class={'w-[100px] text-left'}> 配送打包：{row.deliveryPack}.0 </div>
            <n-rate class={'ml2'} size="small" readonly default-value={row.deliveryPack} />
          </div>
          <div class={'flex text-[12px] text-gray'}>
            <div class={'w-[100px] text-left'}> 送货速度：{row.deliverySpeed}.0 </div>
            <n-rate class={'ml2'} size="small" readonly default-value={row.deliverySpeed} />
          </div>
          <div class={'flex text-[12px] text-gray'}>
            <div class={'w-[100px] text-left'}> 配送员服务：{row.deliveryService}.0 </div>
            <n-rate class={'ml2'} size="small" readonly default-value={row.deliveryService} />
          </div>
        </div>
      );
    }
  },
  {
    key: 'content',
    title: '评价内容',
    align: 'center',
    width: 200
  },
  {
    key: 'jumpUrl',
    title: '图片',
    align: 'center',
    width: 200,
    resizable: true,
    render: row => {
      if (!row.imgs) return '---';
      const imgs = (row.pics as string | undefined)?.split(',') ?? [];
      return (
        <div class={'flex flex-wrap'}>
          {imgs.map((item, index) => {
            return <n-image key={index} width="50" src={item} />;
          })}
        </div>
      );
    }
  },
  {
    key: ' status',
    title: '审核状态',
    align: 'center',
    render: row => {
      const status = String(row.status); // 明确转换为字符串

      const statusObject: Record<string, string> = {
        '1': '审核通过',
        '0': '待审核',
        '-1': '审核不通过'
      };

      const tagMap: Record<string, NaiveUI.ThemeColor> = {
        '1': 'success',
        '0': 'warning',
        '-1': 'error'
      };

      return <NTag type={tagMap[status]}>{statusObject[status]}</NTag>;
    }
  },
  {
    key: 'replyContent',
    title: '回复内容',
    align: 'center',
    width: 200
  },
  {
    key: 'userMobile',
    title: '手机号',
    align: 'center',
    width: 200
  },
  {
    key: 'recTime',
    title: '提交时间',
    align: 'center',
    width: 200
  },
  {
    key: 'replyTime',
    title: '回复时间',
    align: 'center',
    width: 200
  },
  {
    key: 'endTime',
    title: '商品信息',
    align: 'center',
    minWidth: 200,
    maxWidth: 500,
    resizable: true,
    ellipsis: true,
    render: row => {
      const orderItems = Array.isArray(row.orderItems) ? row.orderItems : [];
      if (!orderItems.length) return '---';
      return (
        <div class={'flex flex-wrap'}>
          {orderItems.map((item, index) => {
            return <n-image key={index} class={'mr2 shrink-0'} width="50" src={item.pic} />;
          })}
        </div>
      );
    }
  },
  {
    key: 'shopName',
    title: '门店名称',
    align: 'center',
    width: 200
  }
];

const [registerTable, { refresh, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        label: '评分',
        field: 'score',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '5分',
              value: '5'
            },
            {
              label: '4分',
              value: '4'
            },
            {
              label: '3分',
              value: '3'
            },
            {
              label: '2分',
              value: '2'
            },
            {
              label: '1分',
              value: '1'
            }
          ]
        }
      },
      {
        label: '审核状态',
        field: 'status',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '待审核',
              value: '0'
            },
            {
              label: '通过',
              value: '1'
            },
            {
              label: '不通过',
              value: '-1'
            }
          ]
        }
      },
      {
        label: '是否回复',
        field: 'replySts',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '未回复',
              value: '0'
            },
            {
              label: '已回复',
              value: '1'
            }
          ]
        }
      },
      {
        label: '提交时间',
        component: 'NDatePicker',
        field: 'createTime',
        componentProps: {
          type: 'datetimerange',
          defaultTime: ['00:00:00', '23:59:59']
        }
      },
      {
        label: '门店名称',
        component: 'ApiSelect',
        field: 'shopId',
        componentProps: {
          api: fetchGetAllStoreList,
          labelFeild: 'shopName',
          valueFeild: 'shopId'
        }
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    size: 'small',
    gridProps: {
      cols: '1 xl:4 s:1 l:3',
      itemResponsive: true
    },
    collapsedRows: 1
  },
  tableConfig: {
    keyField: 'id',
    title: '用户评论列表',
    showAddButton: false,
    fieldMapToTime: [['createTime', ['startTime', 'endTime']]],
    scrollX: 3000,
    opWdith: 200
  }
});
const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue }] = useModalFrom({
  modalConfig: {
    title: '回复评论',
    width: 700,
    isShowHeaderText: false,
    height: 200
  },
  formConfig: {
    schemas: [
      {
        label: '',
        field: 'prodCommId',
        component: 'NInput',
        show: false
      },
      {
        field: 'replyContent',
        label: '回复内容',
        component: 'NInput',
        componentProps: { type: 'textarea' },
        required: true
      }
    ],
    gridProps: {
      cols: '1'
    },
    labelWidth: 120
  }
});
async function handleSubmit() {
  const form = await getFieldsValue();
  await fetchGetReply(form);
  closeModal();
  refresh();
}

async function handleAudit(row: Api.userManagement.userReviews, status: number | string) {
  setTableLoading(true);
  await fetchGetBackendCommAudit({ prodCommId: row.prodCommId, status });
  refresh();
}

async function reply(row: Api.userManagement.userReviews) {
  openModal(row);
  await setFieldsValue({ prodCommId: row.prodCommId, replyContent: '' });
  const form = await getFieldsValue();
  console.log(form, row);
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchGetBackendCommList" @register="registerTable">
      <template #op="{ row }">
        <NSpace>
          <NButton v-if="row.status == 1 && row.replySts == 0" size="small" ghost type="primary" @click="reply(row)">
            <template #icon>
              <SvgIcon icon="mdi:message-reply-text"></SvgIcon>
            </template>
            回复
          </NButton>

          <NPopconfirm
            v-if="row.status == 0"
            positive-text="通过"
            negative-text="不通过"
            @positive-click="handleAudit(row, 1)"
            @on-negative-click="handleAudit(row, 0)"
          >
            <template #trigger>
              <NButton size="small" type="error" ghost>
                <template #icon>
                  <SvgIcon icon="icon-park-solid:audit"></SvgIcon>
                </template>
                审核
              </NButton>
            </template>
            请给出审核意见
          </NPopconfirm>
        </NSpace>
      </template>
    </ZTable>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
