<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false" :body-style="{ padding: '16px' }">
        <ele-pro-table
          ref="tableRef"
          row-key="formId"
          :columns="columns"
          :datasource="datasource"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          class="sys-org-table"
        >
          <template #toolbar>
            <a-button type="primary" class="ele-btn-icon" @click="openEdit">
              <template #icon>
                <PlusOutlined />
              </template>
              <span>新增</span>
            </a-button>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <span @click="openPreview('/form/' + record.formId)">{{
                record.name
              }}</span>
            </template>
            <template v-if="column.key === 'path'">
              <span class="ele-text-placeholder">{{ record.path }}</span>
            </template>
            <template v-if="column.key === 'component'">
              <span class="ele-text-placeholder">{{ record.component }}</span>
            </template>
            <template v-if="column.key === 'formData'"> </template>
            <template v-if="column.key === 'status'">
              <a-badge
                v-if="record.status === 0"
                status="success"
                text="已发布"
                @click="onUpdateStatus(record)"
              />
              <a-badge
                v-if="record.status === 1"
                status="default"
                text="已关闭"
                @click="onUpdateStatus(record)"
              />
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openUrl('/cms/form-record?id=' + record.formId)"
                  ><SolutionOutlined />表单数据</a
                >
                <a-divider type="vertical" />
                <a-popover>
                  <template #content>
                    <div class="ele-cell">
                      <ele-qr-code
                        :value="`${domain}/form/${record.formId}`"
                        :size="160"
                        level="M"
                        :margin="1"
                      />
                      手机扫一扫
                    </div>
                  </template>
                  <a @click="onShare"><QrcodeOutlined />分享</a>
                </a-popover>
                <a-divider type="vertical" />
                <a @click="openEdit(record)">设计</a>
                <a-divider type="vertical" />
                <a @click="onUpdateStatus(record)">{{
                  record.status == 1 ? '发布' : '关闭'
                }}</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>

      <!-- 编辑弹窗 -->
      <!--      <FormEdit-->
      <!--        v-model:visible="showEdit"-->
      <!--        :data="current"-->
      <!--        @open="onOpen"-->
      <!--        @done="openEdit"-->
      <!--      />-->
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, unref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    ExclamationCircleOutlined,
    PlusOutlined,
    QrcodeOutlined,
    SolutionOutlined
  } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import FormEdit from './components/form-edit.vue';
  import {
    pageForm,
    removeForm,
    updateForm,
    removeBatchForm
  } from '@/api/cms/form';
  import type { Form, FormParam } from '@/api/cms/form/model';
  import { useRouter } from 'vue-router';
  import { openPreview, openUrl } from '@/utils/common';
  import { useTenantStore } from '@/store/modules/tenant';
  import { storeToRefs } from 'pinia';
  import { getSiteInfo } from '@/api/layout';
  const { push } = useRouter();
  const { currentRoute } = useRouter();
  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<Form[]>([]);
  // 当前编辑数据
  const current = ref<Form | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示批量移动弹窗
  const showMove = ref(false);
  // 二维码
  const showQrCode = ref(false);
  // 加载状态
  const loading = ref(true);
  // 网站域名
  const domain = ref('');

  getSiteInfo().then((data) => {
    // tenantId.value = data.tenantId;
    domain.value = String(data.domain);
  });

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      width: 90,
      dataIndex: 'formId'
    },
    {
      title: '表单标题',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      key: 'status'
    },
    {
      title: '操作',
      key: 'action',
      width: 380,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

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

  /* 打开编辑弹窗 */
  const openEdit = (row?: Form) => {
    push({
      path: '/website/form/detail',
      query: {
        id: row?.formId
      }
    });
  };

  const onShare = (item: any) => {
    showQrCode.value = true;
    current.value = item;
  };

  const onUpdateStatus = (row?: Form) => {
    updateForm({ ...row, status: row?.status == 1 ? 0 : 1 }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

  const onOpen = (e) => {
    console.log(e);
  };

  const openForm = (row?: Form) => {
    push({
      path: '/cms/form/detail',
      query: { id: row?.formId }
    });
  };

  /* 打开批量移动弹窗 */
  const openMove = () => {
    showMove.value = true;
  };

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

  /* 查询 */
  const query = () => {
    loading.value = true;
    reload();
  };

  /* 自定义行属性 */
  const customRow = (record: Form) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openUrl('/cms/form-record?id=' + record.formId);
        // openEdit(record);
      }
    };
  };

  watch(
    currentRoute,
    () => {
      query();
    },
    { immediate: true }
  );
</script>

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

<style lang="less" scoped>
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .design-item {
    margin: auto;
    display: flex;
    text-align: center;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 70px;
    height: 70px;
    border-radius: 70px;
    background: url('data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20version%3D%221.1%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%221%22%20x1%3D%220%22%20x2%3D%221%22%20y1%3D%220%22%20y2%3D%220%22%20gradientTransform%3D%22matrix(6.123233995736766e-17%2C%201%2C%20-0.024693877551020406%2C%206.123233995736766e-17%2C%200.5%2C%200)%22%3E%3Cstop%20stop-color%3D%22%230a060d%22%20stop-opacity%3D%221%22%20offset%3D%220%22%3E%3C%2Fstop%3E%3Cstop%20stop-color%3D%22%23660061%22%20stop-opacity%3D%221%22%20offset%3D%220.95%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22url(%231)%22%3E%3C%2Frect%3E%3C%2Fsvg%3E');
  }
  .ele-cell {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>
