<template>
  <PageWrapper contentBackground>
    <template #footer>
      <a-tabs v-model:activeKey="language" @change="changeTable">
        <a-tab-pane key="cn" tab="Chinese" />
        <a-tab-pane key="en" tab="English" />
      </a-tabs>
    </template>

    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button
            type="primary"
            @click="openModal(true, { language })"
            v-if="getCheckPerm('case-add')"
          >
            新增案例</a-button
          >
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '撤回',
                //icon: 'icon-park-outline:folder-withdrawal-one',
                ifShow: getCheckPerm('case-withdraw') && record.isPublic == 1,
                onClick: handleWithdraw.bind(null, record),
              },
              {
                label: '发布',
                //icon: 'arcticons:efa-publish',
                ifShow: getCheckPerm('case-publish') && record.isPublic == 0,
                onClick: handlePublish.bind(null, record),
              },
              {
                label: '预览',
                //icon: 'ep:edit',
                ifShow: getCheckPerm('case-preview'),
                onClick: handlePreview.bind(null, record),
              },
              {
                label: '编辑',
                //icon: 'ep:edit',
                ifShow: getCheckPerm('case-edit') && record.isPublic == 0,
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                ifShow: getCheckPerm('case-delete'),
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <addNewModal @register="register" @update="reload" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { Time } from '/@/components/Time';
  import { caseListApi, caseReleaseApi, casePublicApi, caseDelApi } from '/@/api/operate';
  import { Descriptions, Switch, Tabs } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import addNewModal from './components/case/addModal.vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      PageWrapper,
      TableImg,
      addNewModal,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage } = useMessage();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const userStore = useUserStore();
      const [register, { openModal }] = useModal();
      const language = ref<string>('cn'); //未处理，0已处理（默认1）
      const columns: BasicColumn[] = [
        {
          title: '案例标题',
          dataIndex: 'title',
          ellipsis: true,
          width: 250,
        },
        // {
        //   title: '来源',
        //   dataIndex: 'source',
        //   ellipsis: true,
        //   width: 120,
        // },
        {
          title: '类型',
          dataIndex: 'typeId',
          ellipsis: true,
          width: 80,
          customRender: ({ record }) => {
            let obj = {
              smartCity: '智慧城市',
              museum: '博物馆',
              government: '刑侦消防',
              property: '房产营销',
            };
            return obj[record.typeId] || '智慧城市';
          },
        },
        {
          title: '创建人',
          ellipsis: true,
          dataIndex: 'sysUserName',
          width: 120,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 150,
          customRender: ({ record }) => {
            return (
              record.createTime &&
              h(Time, {
                value: record.createTime,
                mode: 'datetime',
              })
            );
          },
        },
        {
          title: '发布时间',
          dataIndex: 'publicTime',
          width: 150,
          customRender: ({ record }) => {
            return (
              record.publicTime &&
              h(Time, {
                value: record.publicTime,
                mode: 'datetime',
              })
            );
          },
        },
        {
          title: '排序',
          ellipsis: true,
          dataIndex: 'sort',
          width: 80,
        },
        // {
        //   title: '是否显示',
        //   dataIndex: 'isShow',
        //   ifShow: getCheckPerm('case-display'),
        //   width: 80,
        //   customRender: ({ record }) => {
        //     if (!Reflect.has(record, 'pendingStatus')) {
        //       record.pendingStatus = false;
        //     }
        //     return h(Switch, {
        //       checked: record.isShow === 1,
        //       checkedChildren: '是',
        //       unCheckedChildren: '否',
        //       loading: false,
        //       onChange: async (checked: boolean) => {
        //         record.pendingStatus = true;
        //         const id: string = record.id || '';
        //         const newStatus = checked ? 1 : 0;
        //         Reflect.set(record, 'isShow', newStatus);
        //         await caseReleaseApi({ id: id, isShow: newStatus });
        //         createMessage.success(t('common.optSuccess'));
        //         // reload()
        //       },
        //     });
        //   },
        //},
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        schemas: [
          {
            field: 'publicTime',
            label: t('routes.operate.releaseTime'),
            component: 'RangePicker',
            componentProps: {
              maxLength: 100,
              format: 'YYYY-MM-DD',
              valueFormat: 'YYYY-MM-DD',
              showTime: true,
            },
            colProps: {
              xl: 8,
              xxl: 8,
            },
          },
          {
            field: 'title',
            label: '案例标题',
            component: 'Input',
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'typeId',
            label: '类型',
            component: 'Select',
            componentProps: {
              placeholder: '请选择类型',
              options: [
                {
                  label: '智慧城市',
                  value: 'smartCity',
                  key: 'smartCity',
                },
                {
                  label: '博物馆',
                  value: 'museum',
                  key: 'museum',
                },
                {
                  label: '刑侦消防',
                  value: 'government',
                  key: 'government',
                },
                {
                  label: '房产营销',
                  value: 'property',
                  key: 'property',
                },
              ],
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
        ],
      };
      const [registerTable, { reload }] = useTable({
        api: caseListApi,
        title: '案例列表',
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        showIndexColumn: false,
        searchInfo: { language },
        rowKey: 'id',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        beforeFetch: (T) => {
          if (T.ctivated) {
            T.publicTimeStart = T.ctivated[0];
            T.publicTimeEnd = T.ctivated[1];
          }
          return T;
        },
        actionColumn: {
          width: 230,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        canResize: true,
      });
      async function handleDelete(record: Recordable) {
        await caseDelApi({ id: record.id });
        createMessage.success(t('common.optSuccess'));
        reload();
      }
      async function handlePublish(record: Recordable) {
        console.log('点击了发布', record);
        await casePublicApi({ id: record.id, isPublic: 1 });
        createMessage.success(t('common.optSuccess'));
        reload();
      }
      function handleEdit(record: Recordable) {
        console.log('点击了编辑', record);
        openModal(true, { ...record, language });
      }
      function handlePreview(record: Recordable) {
        const host = userStore.isEnv;
        console.log('host', host);
        if(record.outsideLink){
          return window.open(record.outsideLink, '_blank');
        }
        let url =
          window.location.host == 'www.4dkankan.com'
            ? `https://www.4dkankan.com/#/cases/detail/${record.id}`
            : `https://test.4dkankan.com/#/cases/detail/${record.id}`;
        if (host) {
          url = window.location.host.includes('test')
            ? `https://testeur.4dkankan.com/#/cases/detail/${record.id}`
            : `https://eur.4dkankan.com/#/cases/detail/${record.id}`;
        }
        window.open(url, '_blank');
      }
      async function handleWithdraw(record: Recordable) {
        await casePublicApi({ id: record.id, isPublic: 0 });
        createMessage.success(t('common.optSuccess'));
        reload();
      }
      function changeTable(val: string) {
        language.value = val;
        reload();
      }
      function hendleAddNew() {
        console.log('新增新闻');
      }
      return {
        registerTable,
        handleDelete,
        handleEdit,
        handleWithdraw,
        handlePublish,
        hendleAddNew,
        changeTable,
        reload,
        language,
        register,
        openModal,
        getCheckPerm,
        handlePreview,
      };
    },
  });
</script>
