<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="companyId"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @advanced="openAdvanced"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'companyName'">
              <div class="company-box">
                <a-image
                  :height="45"
                  :width="45"
                  :preview="false"
                  :src="record.companyLogo"
                  fallback="https://file.wsdns.cn/20230218/550e610d43334dd2a7f66d5b20bd58eb.svg"
                />
                <div class="company-info">
                  <a
                    class="ele-text-heading"
                    @click="openUrl('/oa/company/detail/' + record.companyId)"
                  >
                    {{ record.companyName }}
                  </a>
                  <span class="ele-text-placeholder">
                    {{ record.shortName }}
                  </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'status'">
              <template v-if="record.status == 0">
                <a-badge status="processing" :text="`正常`" />
              </template>
              <template v-if="record.status == 1">
                <a-badge status="default" :text="`冻结`" />
              </template>
            </template>
            <template v-if="column.key === 'expirationTime'">
              <template v-if="expirationTime(record.expirationTime) < 30">
                <a-space>
                  <span class="ele-text-danger">{{
                    toDateString(record.expirationTime, 'yyyy-MM-dd')
                  }}</span>
                  <span class="ele-text-placeholder"
                    >(剩余{{ expirationTime(record.expirationTime) }}天)</span
                  >
                </a-space>
              </template>
              <template v-else>
                {{ toDateString(record.expirationTime, 'yyyy-MM-dd') }}
              </template>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">编辑</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>
    </div>
    <!-- 编辑弹窗 -->
    <CompanyEdit 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';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import { openUrl } from '@/utils/common';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import CompanyEdit from './components/company-edit.vue';
  import {
    pageCompany,
    removeBatchCompany,
    removeCompany
  } from '@/api/oa/company';
  import { Company, CompanyParam } from '@/api/oa/company/model';
  import { toDateString } from 'ele-admin-pro';

  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'companyId',
      width: 80,
      hideInTable: true
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName'
    },
    {
      title: '企业类型',
      dataIndex: 'companyType',
      width: 180,
      align: 'center',
      key: 'companyType'
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 180,
      key: 'status',
      customRender: ({ text }) => ['正常', '冻结'][text]
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 180,
      sorter: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      fixed: 'right',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<Company[]>([]);
  // 当前编辑数据
  const current = ref<Company | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示高级搜索
  const showAdvancedSearch = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 默认类型
    if (where.keywords == undefined) {
      where.companyStatus = '开发中';
      where.showExpiration = undefined;
    }
    return pageCompany({
      ...where,
      ...orders,
      page,
      limit
    });
  };

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

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

  const expirationTime = (dateTime) => {
    const now = new Date().getTime();
    const expiration = new Date(dateTime).getTime();
    const mss = expiration - now;
    let days = Math.floor(mss / (1000 * 60 * 60 * 24));
    let hours = Math.floor((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((mss % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.round((mss % (1000 * 60)) / 1000);
    return days;
  };

  /* 打开高级搜索 */
  const openAdvanced = () => {
    showAdvancedSearch.value = !showAdvancedSearch.value;
  };

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

  /* 批量删除 */
  const removeBatch = () => {
    console.log(selection.value);
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchCompany(selection.value.map((d) => d.companyId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 自定义行属性 */
  const customRow = (record: Company) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openUrl('/oa/company/detail/' + record.companyId);
        // window.open('/oa/company/detail/' + record.companyId);
      }
    };
  };

  reload();
</script>

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

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .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;
  }
  .company-box {
    display: flex;
    .company-info {
      display: flex;
      margin-left: 5px;
      flex-direction: column;
    }
  }
</style>
