import React, { useState, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { ProTable } from '@ant-design/pro-components';
import { Button, notification } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { virtualGoodsColumn } from './staticData/goods';
import utilStyle from '@/utils/utils.less';
import { apiVirtualList, apiVirtualGoodsDel } from './service';
import { getEnterpriseList, getEnterpriseName } from './service/bll';
import { getToUrlQuery } from '@/utils/utils';

// 企业虚拟商品
const VirtualGoods = () => {
  const history = useHistory();
  const refTable = useRef();
  const [pageLoaded, setPageLoaded] = useState(false);
  const [enterprises, setEnterprises] = useState(null); // 企业列表
  const [enterpriseId, setEnterpriseId] = useState(''); // 选中企业ID

  // 刷新列表
  const onRefresh = () => {
    if (pageLoaded) {
      refTable?.current?.reloadAndRest();
    }
  };

  // 搜索商品列表
  const searchList = async params => {
    if (params.createDate && params.createDate.length) {
      const [startDateTime, endDateTime] = params.createDate;
      params.startDateTime = startDateTime;
      params.endDateTime = endDateTime;
    }
    const data = {
      page: params.current || 1,
      size: params.pageSize || 10,
      data: Object.assign({}, params, {
        enterpriseId,
      }),
    };
    const res = await apiVirtualList(data);
    if (res && res.data && res.data.records && res.data.records.length) {
      return {
        data: res.data.records || [],
        total: res.data.total || 0,
      };
    }
    return {
      data: [],
      total: 0,
    };
  };
  // 删除商品
  const onDel = async id => {
    await apiVirtualGoodsDel({
      id,
    });
    refTable.current.reload();
    notification.success({
      message: '删除成功',
    });
  };
  // 跳转添加商品
  const toAdd = async () => {
    const params = getToUrlQuery();
    const query = Object.assign(
      {
        id: enterpriseId,
        name: getEnterpriseName(enterprises, enterpriseId),
      },
      params,
    );
    history.push({
      pathname: '/virtualGoodsInfo',
      query,
    });
  };

  // 改变企业
  const onChangeEnterprise = v => {
    setEnterpriseId(v);
    onRefresh();
  };

  // 获取企业列表
  const getList = async () => {
    const obj = await getEnterpriseList({
      type: 2,
    });
    if (obj.list && Object.keys(obj.list).length) {
      setEnterprises(obj.list);
      setEnterpriseId(`${obj.id}`);
    } else if (!enterpriseId) {
      notification.error({ message: '未找到企业' });
    }
    setPageLoaded(true);
  };

  useEffect(() => {
    getList();
  }, []);

  const options = {
    onDel,
    enterprises,
    enterpriseId,
    onChangeEnterprise,
  };

  let request = () => ({
    data: [],
    total: 0,
  });
  if (enterpriseId) {
    request = params => searchList({ ...params });
  }

  return (
    <div className={utilStyle.formPageBox}>
      {pageLoaded && (
        <ProTable
          search={{
            span: 6,
            className: utilStyle.formSearch,
            collapsed: false,
            collapseRender: () => null,
          }}
          actionRef={refTable}
          tableClassName={utilStyle.formTable}
          columns={virtualGoodsColumn(options)}
          request={request}
          rowKey={r => r.id}
          bordered
          options={false}
          scroll={{ x: 1300 }}
          toolbar={{
            actions: [
              <Button key="1" icon={<PlusOutlined />} type="primary" onClick={toAdd}>
                添加虚拟商品
              </Button>,
            ],
          }}
        />
      )}
    </div>
  );
};

export default VirtualGoods;
