import { Checkbox, Input, Popconfirm, Space, Typography } from 'antd';
import { ConfigProvider, Table } from 'antd5';
import { memo, useMemo } from 'react';
import { FormattedMessage } from 'umi';
import { leafBuildTree, treeLeafNode } from '../../utils/array';
import { requestBatchUnbind } from '../api';
import style from './index.less';

const { Text } = Typography;

export interface CityList {
  isOptShow?: boolean;
  DataSensitiveMap?: any;
  DataSensitiveLevelMap?: any;
  setOpenObj?: any;
  params?: any;
  setParams?: any;
  formatMessage?: any;
  moment?: any;
  appId?: any;
  setRenewalParams?: any;
  currentUser?: any;
  batchParams?: any;
  setBatchParams?: any;
  data?: any;
  permission?: any;
  run?: any;
  showSelected?: boolean;
}

const CityListTable = (props: CityList) => {
  const {
    isOptShow,
    DataSensitiveMap,
    DataSensitiveLevelMap,
    setOpenObj,
    params,
    setParams,
    formatMessage,
    moment,
    appId,
    setRenewalParams,
    currentUser,
    batchParams,
    setBatchParams,
    data,
    permission,
    run,
    showSelected,
  } = props;

  const columns = [
    {
      title: <FormattedMessage id="base.common.city.permission" defaultMessage="城市权限" />,
      dataIndex: 'cityName',
      ellipsis: true,
      render: (__: any, record: any) => {
        return (
          <Typography.Text ellipsis={{ tooltip: { placement: 'right' } }}>
            {record.cityName}
          </Typography.Text>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.funcList.sensitiveLevel" defaultMessage="敏感等级" />,
      dataIndex: 'dataSensitive',
      ellipsis: true,
      render: (__: any, record: any) => {
        return (
          <Text ellipsis={{ tooltip: true }}>
            {DataSensitiveLevelMap[record?.dataSensitive]?.text}
          </Text>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.funcList.sensitivity" defaultMessage="敏感度" />,
      dataIndex: 'sensitiveLevel',
      ellipsis: true,
      render: (__: any, record: any) => {
        return (
          <Text ellipsis={{ tooltip: true }}>{DataSensitiveMap[record.sensitiveLevel]?.text}</Text>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.process.expiration" defaultMessage="有效期" />,
      dataIndex: 'expiredAt',
      ellipsis: true,
      render: (__: any, record: any) => {
        return record.hasOwnProperty('expiredAt') ? (
          <Text ellipsis={{ tooltip: true }}>
            {record.expiredAt == 0
              ? formatMessage({ id: 'pages.setting.base.defaultExpirationTime.forever' })
              : record.expiredAt < 0
              ? '-'
              : moment().valueOf() < record.expiredAt * 1000
              ? moment(record.expiredAt * 1000).format('YYYY-MM-DD HH:mm:ss')
              : `${moment(record.expiredAt * 1000).format('YYYY-MM-DD HH:mm:ss')}(${formatMessage({
                  id: 'base.expiredAted',
                })})`}
          </Text>
        ) : null;
      },
    },
    {
      title: (
        <div style={{ textAlign: 'center' }}>
          <FormattedMessage id="base.permission.operation" defaultMessage="操作" />
        </div>
      ),
      dataIndex: 'permissionOption',
      fixed: 'right',
      hidden: !isOptShow,
      render: (__: any, record: any) => [
        <>
          <Space>
            {record?.isBind ? (
              <Popconfirm
                key={`del${record.cityId}`}
                title={formatMessage({ id: 'pages.unbind.confirm' })}
                onConfirm={async () => {
                  try {
                    const allSettledPromise = requestBatchUnbind(
                      { userCityList: [record.cityId] },
                      currentUser,
                      appId,
                      formatMessage,
                    );
                    if (allSettledPromise) {
                      allSettledPromise.then(() => {
                        run();
                      });
                    }
                  } catch (error) {}
                }}
              >
                <a>
                  <FormattedMessage id="pages.unbind" />
                </a>
              </Popconfirm>
            ) : null}
            {record?.expiredAt <= 0 || record?.isAllowApply === 0 || !record?.isBind ? null : (
              <a
                key={`renewal${record.cityId}`}
                onClick={() => {
                  setRenewalParams({ userCityList: [record.cityId] });
                  setOpenObj({ open: true, reload: false });
                }}
              >
                <FormattedMessage id="base.renewal" />
              </a>
            )}
          </Space>
        </>,
      ],
    },
  ];

  const dataSource = useMemo(() => {
    const list = permission?.userCityList ?? data?.userCityList ?? [];
    if (!showSelected) return list;
    const leaf = treeLeafNode(list, (v) => {
      return v.isBind;
    }).map((v) => v.cityId);
    return leafBuildTree(leaf, list, 'cityId');
  }, [data?.userCityList, permission?.userCityList, showSelected]);

  if (!data?.userCityList?.length) return null;

  return (
    <div>
      {Boolean(isOptShow) && (
        <Space className={style.permission_name}>
          <label style={{ whiteSpace: 'nowrap' }}>
            {formatMessage({ id: 'page.process.permission.name' })}
          </label>
          <Input
            placeholder={''}
            value={params?.userCityList}
            onChange={(val) => {
              setParams({ ...params, userCityList: val.target.value });
            }}
            style={{ width: 200 }}
          />
        </Space>
      )}

      <ConfigProvider
        theme={{
          token: {
            colorPrimary: '#F16622',
            colorLink: '#F16622',
          },
        }}
      >
        <Table
          rowKey={'cityId'}
          virtual
          scroll={{ y: 400 }}
          rowSelection={
            isOptShow
              ? {
                  columnWidth: 50,
                  selectedRowKeys: batchParams?.userCityList,
                  onChange: (rowKey) => {
                    setBatchParams((key: any) => {
                      return { ...key, userCityList: rowKey };
                    });
                  },
                  getCheckboxProps: (record: any) => ({
                    disabled:
                      record?.expiredAt < 0 || record?.isAllowApply === 0 || !record?.isBind,
                  }),
                }
              : {
                  columnWidth: 50,
                  hideSelectAll: true,
                  renderCell: (checked, record: any) => {
                    return <Checkbox disabled checked={record.isBind} />;
                  },
                }
          }
          columns={columns as any}
          pagination={false}
          dataSource={dataSource}
        />
      </ConfigProvider>
    </div>
  );
};
export default memo(CityListTable);
