import React, { 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([]);
  const [summaryRow, setSummaryRow] = useState({});
  useEffect(() => {
    const r1 = props.columns.reduce((r, v) => ({
      ...r,
      ...(v.children ? v.children.reduce((rc, vc, ci) => ({
        ...rc,
        ...(vc?.titleX ? {[`${v?.titleX || v.title},${vc.titleX}`]: vc.titleX } : {[(v?.titleX || v.title) + (ci || '')]: `${vc?.titleX || vc?.title || ''}`}),
      }), {}) : {})
    }), {});
    const flatCols = props.columns.flatMap((v, k) =>
      v.children ? v.children.map((vc, ci) => ({ ...vc, title: `${v?.titleX || v.title}` + (vc?.titleX ? `,${vc.titleX}` : (ci || '')) })) : {...v, title: `${v?.titleX || v.title}`}
    );
      // .filter((c) => c.dataIndex)
      // !['string', 'number'].includes(typeof vc.title) ? `${v?.titleX || v.title}` : `${v?.titleX || v.title}-${vc.title || ''}`
      ;
    setColumnsMap(flatCols);
    // console.log('flatCols', flatCols);

    setSummaryRow(r1);
    // console.log('summaryRow', r1);

    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 x_val = item[`${kset.dataIndex}_X`];
        // const _title = kset.title.replace('-[object Object]', '');
        const v = { [kset.title]: x_val || data_val || render_val };
        return { ...sv, ...v };
      }, {});
      return itemMapped;
    });
    const ws = utils.json_to_sheet([].concat(isEmpty(summaryRow) ? [] : [summaryRow], 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}
    >
      {props.btnTxt || '导出excel'}
    </Button>
  );
};
