import { Popconfirm, Space, Table, Typography } from 'antd';
import type { ColumnsType } from 'antd/lib/table';
import Link from 'antd/lib/typography/Link';
import _ from 'lodash';
import moment from 'moment';
import { useMemo } from 'react';
import { request, useIntl, useModel, useRequest } from 'umi';
import ExpandIcon from '../ExpandIcon';
import UserLink from '../UserInfo/link';
import PackageList from './list';
import RenewalModel from './renewal';

export interface MyPackageProps {
  userId?: number;
}

const MyPackage = (props: MyPackageProps) => {
  const { userId } = props;
  const { formatMessage } = useIntl();

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const uId = userId ?? currentUser?.id;

  const { data: dataSource, refresh } = useRequest(
    () => ({
      url: '/goapi/app/myPackage',
      method: 'POST',
      data: { userId: uId },
    }),
    {
      ready: !!userId || !!currentUser?.id,
      refreshDeps: [userId, currentUser?.id],
      formatResult: (res) => res.data.list ?? [],
    },
  );

  const columns = useMemo<ColumnsType<any>>(() => {
    const cols = [
      {
        title: formatMessage({ id: 'base.apply.multiple.app.name' }),
        dataIndex: 'multiAuditName',
        render: (__, record) => record.packageInfo?.multiAuditName,
      },
      {
        title: formatMessage({ id: 'base.owner' }),
        dataIndex: 'creator',
        render: (__, record) => <UserLink user={record.packageInfo?.creator} />,
      },
      {
        title: formatMessage({ id: 'pages.process.expiration' }),
        dataIndex: 'expiredAt',
        render: (__, record) => {
          const { expiredAt } = record.packageInfo ?? {};
          return (
            _.isNumber(expiredAt) && (
              <Typography.Text ellipsis={{ tooltip: true }}>
                {expiredAt === 0
                  ? formatMessage({ id: 'pages.setting.base.defaultExpirationTime.forever' })
                  : moment(expiredAt * 1000).format('YYYY-MM-DD HH:mm:ss')}
              </Typography.Text>
            )
          );
        },
      },
    ];

    // 必须是本人才可解绑/续期
    if (uId === currentUser?.id) {
      cols.push({
        title: formatMessage({ id: 'base.common.operation' }),
        dataIndex: 'option',
        render: (__, record) => {
          return (
            <Space>
              <Popconfirm
                title={formatMessage({ id: 'pages.unbind.confirm' })}
                onConfirm={async () => {
                  await request('/goapi/audit/multi/unbind', {
                    method: 'POST',
                    data: { uacAuditId: record.packageInfo?.uacAuditId },
                  });
                  refresh();
                }}
              >
                <Link>{formatMessage({ id: 'pages.unbind' })}</Link>
              </Popconfirm>

              <RenewalModel packageRow={record} refresh={refresh} />
            </Space>
          );
        },
      });
    }
    return cols;
  }, [currentUser?.id, formatMessage, refresh, uId]);

  return (
    <Table
      expandable={{
        defaultExpandAllRows: false,
        expandIcon: (p) => <ExpandIcon {...p} dataControl={false} />,
        rowExpandable: () => true,
        expandedRowRender: (record: any) => <PackageList applyList={record.applyList} />,
      }}
      rowKey={(row) => row.packageInfo?.batchAuditId}
      columns={columns}
      pagination={false}
      dataSource={dataSource}
    />
  );
};

export default MyPackage;
