import Constants from '@/constants';
import {
  pbcUsersPageUsingPost,
  updateMemberRecordStateUsingGet,
} from '@/services/pop-b2b2c/pbcUsersController';
import { gradeListUsingPost } from '@/services/pop-b2b2c/pbcVipGradeController';
import { handlePageQuery } from '@/utils/utils';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { Access, useAccess } from '@umijs/max';
import { message, Switch } from 'antd';
import React, { useRef } from 'react';

/**
 * 查询表格
 * @param param0
 */
const fetchData = async (params: API.PageVO) => {
  const msg = await pbcUsersPageUsingPost(params);
  return {
    data: msg.data?.records,
    total: msg.data?.total,
    success: msg.retcode,
  } as any;
};

const handleUpdateState = async (id: number, state: number) => {
  const hide = message.loading('正在保存');
  if (!id) return false;
  try {
    const msg = await updateMemberRecordStateUsingGet({ pbcId: id, state: state });
    hide();
    if (msg.retcode) {
      message.success(!id ? '新增成功！' : '保存成功！');
      return true;
    }
    message.error(msg.retmsg);
    return false;
  } catch (error) {
    hide();
    message.error(!id ? '新增失败，请重试！' : '保存失败，请重试！');
    return false;
  }
};

// eslint-disable-next-line @typescript-eslint/ban-types
const TableList: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const access: any = useAccess();

  const columns: ProColumns<API.PbcUsers>[] = [
    {
      title: '会员类型',
      dataIndex: 'pbcUserType',
      valueEnum: Constants.pbcUserType
    },
    {
      title: '会员昵称',
      dataIndex: 'pbcUserNickName',
    },
    {
      title: '手机号',
      dataIndex: 'pbcUserMobile',
    },
    {
      title: '入口',
      dataIndex: 'pbcUserSourceType',
      search: false,
      valueEnum: Constants.pbcUserSourceType
    },
    {
      title: '分享人昵称',
      dataIndex: 'pbcUserSourceUserNickName',
    },
    {
      title: '分享人店铺',
      dataIndex: 'pbcBusinessInfo',
      search: false,
      render: (text, record) => {
        return record.pbcBusinessInfo?.pbcBusinessName
      }
    },
    {
      title: '会员等级',
      dataIndex: 'pbcVipGradeName',
      valueType: 'select',
      request: async () => {
        const msg = await gradeListUsingPost();
        if (msg.retcode && msg.data) {
          return msg.data.map((e) => {
            return {
              label: e.pbcVipGradeName,
              value: e.pbcVipGradeName,
            };
          });
        }
        return [];
      },
    },
    {
      title: '注册日期',
      dataIndex: 'pbcCreateAt',
      valueType: 'dateTimeRange',
      render: (text, record) => record.pbcCreateAt,
    },
    {
      title: '状态',
      dataIndex: 'pbcState',
      valueType: 'select',
      valueEnum: Constants.state,
      render: (_, record) => {
        return (
          <Access key="switch" accessible={access.memberUpdateState}>
            <Switch
              checked={record.pbcState === 1}
              onChange={async (value) => {
                const success = await handleUpdateState(record.pbcId || 0, value ? 1 : 2);

                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
            />
          </Access>
        );
      },
    },
  ];
  return (
    <PageContainer
      header={{
        title: '',
        breadcrumb: {},
      }}
    >
      <ProTable<API.PbcUsers>
        columns={columns}
        actionRef={actionRef}
        request={(param: any) => {
          console.log(param)
          let hasUserType = false
          if (param.pbcUserType) {
            param.pbcUserType = parseInt(param.pbcUserType)
            hasUserType = true
          }
          const queryParam = handlePageQuery(param);
          if (!hasUserType && queryParam.filters) {
            queryParam.filters.push({
              key: 'pbcUserType'.replace(/([A-Z])/g, '_$1').toLowerCase(),
              value: 1,
              action: '<=',
            });
          }
          return fetchData(queryParam);
        }}
        rowKey="pbcId"
        size="small"
        bordered
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        pagination={{
          pageSize: 20,
          showSizeChanger: true,
        }}
        scroll={{
          y: 'calc(100vh - 320px)',
        }}
        dateFormatter="string"
        options={false}
        toolBarRender={() => []}
      />
    </PageContainer>
  );
};

export default TableList;
