<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <a-card :bordered="false">
      <div class="mp-field">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="mpId"
          :columns="columns"
          :datasource="datasource"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          class="sys-org-table"
        >
          <template #toolbar>
            <MpFieldSearch @add="openEdit" />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <div class="ele-text-heading">{{ record.name }}</div>
              <span class="ele-text-placeholder">{{ record.comments }}</span>
            </template>
            <template v-if="column.key === 'pageId'">
              <span v-if="record.pageId === 0" class="ele-text-placeholder"
                >全局</span
              >
              <span v-else class="ele-text-placeholder">{{
                record.pageName
              }}</span>
            </template>
            <template v-if="column.key === 'value'">
              <a-image
                v-if="record.type === 1"
                :src="record.value"
                :width="120"
              />
              <span v-else>{{ record.value }}</span>
            </template>
            <template v-if="column.key === 'action'">
              <a @click="copyText('{{ config.' + record.name + ' }}')">调用</a>
              <a-divider type="vertical" />
              <a @click="openEdit(record)">编辑</a>
              <template v-if="record.deleted == 0">
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此记录吗？"
                  @confirm="remove(record)"
                >
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </template>
              <template v-if="record.deleted == 1">
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要放回原处吗？"
                  @confirm="recovery(record)"
                >
                  <a class="ele-text-danger">恢复</a>
                </a-popconfirm>
              </template>
            </template>
          </template>
          <template #footer>
            <div class="ele-text-secondary"
              >温馨提示：跟随程序自动加载，通过<span v-pre
                >{{ config.mpLogo }}可以方便调用，文本内容不加密。</span
              ><a
                href="https://websoft.top"
                class="ele-text-secondary"
                target="_blank"
                >查看帮助文档</a
              ></div
            >
          </template>
        </ele-pro-table>
        <!-- 编辑弹窗 -->
        <MpFieldEdit
          v-model:visible="showEdit"
          :data="current"
          :pageId="pageId"
          @done="reload"
        />
      </div>
    </a-card>
  </a-page-header>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type { DatasourceFunction } from 'ele-admin-pro/es/ele-pro-table/types';
  import MpFieldSearch from './components/mp-field-search.vue';
  import { Mp } from '@/api/cms/mp/model';
  import MpFieldEdit from './components/mp-field-edit.vue';
  import { MpField, MpFieldParam } from '@/api/cms/mpField/model';
  import {
    pageMpField,
    removeMpField,
    undeleteMpField,
    updateMpField
  } from '@/api/cms/mpField';
  import { copyText, getPageTitle } from '@/utils/common';
  import router from '@/router';

  const props = defineProps<{
    mpId: any;
    data: Mp;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  const selection = ref<any[]>();
  // 当前编辑数据
  const current = ref<MpField | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const pageId = ref(0);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    if (pageId.value > 0) {
      where.pageId = pageId.value;
    }
    // where.pageId = router.currentRoute.value.params.id;
    return pageMpField({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<any[]>([
    {
      title: '键',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value'
    },
    // {
    //   title: '位置',
    //   dataIndex: 'pageId',
    //   key: 'pageId',
    //   width: 180,
    //   align: 'center'
    // },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      width: 120,
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center',
      hideInSetting: true
    }
  ]);

  const moveUp = (row?: MpField) => {
    updateMpField({
      id: row?.id,
      sortNumber: Number(row?.sortNumber) + 1
    }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

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

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

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

  // 从回收站放回原处
  const recovery = (row: MpField) => {
    const hide = message.loading('请求中..', 0);
    undeleteMpField(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 自定义行属性 */
  const customRow = (record: MpField) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  watch(
    () => router.currentRoute.value.params.id,
    (id) => {
      if (id) {
        console.log(router.currentRoute);
        if (id == ':id') {
          pageId.value = 0;
        } else {
          pageId.value = Number(id);
        }
      }
      reload();
    },
    { immediate: true }
  );
</script>

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