import { useState, useEffect } from "react";
import { Tag, Button, message } from 'antd';
import { CaretUpOutlined, CaretDownOutlined, DownloadOutlined } from '@ant-design/icons';
import { utils, writeFile } from "xlsx";
import { isEmpty, getNestedValue } from "../utils/commons";

/**
 * @property diffPercent
 * @property diffData
 * @property data1
 * @property data2
 */
export const VSTag = (props) => {
  const { diffPercent, diffData, data1, data2 } = props;
  const CaretIcon = parseInt(diffPercent) < 0 ? CaretDownOutlined : CaretUpOutlined;
  const tagColor = parseInt(diffPercent) < 0 ? 'gold' : 'lime';
  return parseInt(diffPercent) === 0 ? (
    '-'
  ) : (
    <span>
      {/* <div>
        {data1} vs {data2}
      </div> */}
      <Tag icon={<CaretIcon />} color={tagColor}>
        {diffPercent}<span>%</span>{'  '}<span>{diffData}</span>
      </Tag>
    </span>
  );
};

/**
 * 导出表格数据存为xlsx
 */
export const TableExportBtn = (props) => {
  const output_name = `${props.label}`;
  const [columnsMap, setColumnsMap] = useState([]);
  useEffect(() => {
    const flatCols = props.columns.flatMap((v, k) => (v.children ? v.children.map((vc) => ({ ...vc, title: `${v.title}-${vc.title || ''}` })) : v)).filter(c => c.title);
    // console.log('flatCols', flatCols);
    setColumnsMap(flatCols);

    return () => {};
  }, [props.columns]);

  const onExport = () => {
    if (isEmpty(props.dataSource)) {
      message.warning('无结果.');
      return false;
    }
    const data = props.dataSource.map((item) => {
      const itemMapped = columnsMap.reduce((sv, kset) => {
        const render_val = typeof kset?.render === 'function' ? kset.render('', item) : null;
        const data_val = kset?.dataIndex ? (Array.isArray(kset.dataIndex) ? getNestedValue(item, kset.dataIndex) : item[kset.dataIndex]) : undefined;
        const v = { [kset.title]: data_val || render_val };
        return { ...sv, ...v };
      }, {});
      return itemMapped;
    });
    // console.log('data', data);
    const ws = utils.json_to_sheet(data, { header: columnsMap.filter((r) => r.dataIndex).map((r) => r.title) });
    const wb = utils.book_new();
    utils.book_append_sheet(wb, ws, 'sheet');
    writeFile(wb, `${output_name}.xlsx`);
  };

  return (
    <Button
      type="link"
      icon={<DownloadOutlined />}
      size="small"
      disabled={false}
      onClick={onExport}
    >
      导出excel
    </Button>
  );
};
