import React, { useRef, useState } from 'react';
import { Button, message } from 'antd';
import UpdateForm from './components/UpdateForm';
import { Access, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { pbcVipGradePageUsingPost, saveOrUpdateGradeUsingPost } from '@/services/pop-b2b2c/pbcVipGradeController';
import { handlePageQuery } from '@/utils/utils';

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

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: API.PbcVipGrade) => {
  const hide = message.loading('正在保存');

  try {
    const msg = await saveOrUpdateGradeUsingPost({ ...fields });
    hide();
    if (msg.retcode) {
      message.success(!fields.pbcId ? '添加成功' : '保存成功');
      return true;
    }
    message.error(msg.retmsg);
    return false;
  } catch (error) {
    hide();
    message.error(!fields.pbcId ? '添加失败请重试！' : '保存失败请重试！');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const access: any = useAccess();
  const actionRef = useRef<ActionType>();
  const [stepFormValues, setStepFormValues] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const columns: ProColumns<API.PbcVipGrade>[] = [
    {
      title: '会员等级名称',
      dataIndex: 'pbcVipGradeName',
      search: false,
    },
    {
      title: '折扣权益',
      dataIndex: 'pbcVipGradeDiscount',
      search: false,
      render: (text, record) => record.pbcVipGradeDiscount ? record.pbcVipGradeDiscount * 10 + '折' : '-'
    },
    {
      title: '入会时长',
      dataIndex: 'pbcBusinessId',
      search: false,
    },
    {
      title: '采购金额',
      dataIndex: 'pbcBusinessId',
      search: false,
    },
    {
      title: '操作',
      fixed: 'right',
      valueType: 'option',
      render: (text, record) => (
        <span>
          <Access key="config" accessible={access.memberGradeSave}>
            <Button type="link" onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}>
              编辑
            </Button>
          </Access>
        </span>
      ),
    },
  ];
  return (
    <PageContainer
      header={{
        title: '',
        breadcrumb: {},
      }}
    >
      <ProTable<API.PbcVipGrade>
        columns={columns}
        actionRef={actionRef}
        request={(param: any) => {
          const queryParam = handlePageQuery(param);
          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={() => []}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async (value: any) => {
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});
              actionRef.current?.reload();
            }
          }}
          onCancel={() => {
            message.destroy();
            handleUpdateModalVisible(false);
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageContainer>
  );
};

export default TableList;
