import { createContext, useContext, useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { stores_Context } from '../config';
import { Table, Row, Col, Divider, Button } from 'antd';
import SearchForm from '../components/search/SearchForm';
import { TableExportBtn } from './../components/Data';
import { uniqWith } from './../utils/commons';

// 注意TdCell要提到DataTable作用域外声明
const TdCell = (tdprops) => {
  // onMouseEnter, onMouseLeave在数据量多的时候，会严重阻塞表格单元格渲染，严重影响性能
  const { onMouseEnter, onMouseLeave, ...restProps } = tdprops;
  return <td {...restProps} />;
};

const SalesCustomerCareRegular = (props) => {
  const { orders_store, date_picker_store: searchFormStore, customer_store } = useContext(stores_Context);
  const { formValues, formValuesToSub, siderBroken } = searchFormStore;
  const { sales_regular_data: pageData } = customer_store;
  const [expandRowKeys, setExpandRowKeys] = useState([]);
  const [dataForExport, setDataForExport] = useState([]);
  useEffect(() => {
    setExpandRowKeys(pageData.data.map((ele) => ele.key));
    setDataForExport(pageData.data.reduce((r, c) => r.concat([{...c, children: undefined}], c.children.map(ele => ({...ele, operatorName: ele.rowLabel}))), []));
    return () => {};
  }, [pageData.data]);

  const allOPI1 = uniqWith(
    pageData.data.map((rr) => ({ text: rr.operatorName, value: rr.operatorName })),
    (a, b) => JSON.stringify(a) === JSON.stringify(b)
  ).sort((a, b) => a.text.localeCompare(b.text));

  const rowColumns = [
    { title: '顾问', dataIndex: 'operatorName', key: 'operatorName' },
    { title: '订单号', dataIndex: 'o_id', key: 'o_id' },
    { title: '预定日期', dataIndex: 'applyDate', key: 'applyDate' },
    { title: '订单状态', key: 'orderState', render: (_, r) => r.orderState === '1' ? '成行' : '', },
    { title: '毛利', dataIndex: 'ML', key: 'ML' },
    { title: '人数', dataIndex: 'personNum', key: 'personNum' },
    { title: '天数', dataIndex: 'tourdays', key: 'tourdays' },
    // { title: '人天数', dataIndex: 'CGI_PersonDays', key: 'CGI_PersonDays' },
    // { title: '走团日期', dataIndex: 'COLI_OrderStartDate', key: 'COLI_OrderStartDate' },
    { title: '小组', dataIndex: 'dept', key: 'dept' },
    { title: '老客户', key: 'IsOld', render: (_, r) => r.IsOld === '1' ? '是' : '' },
    { title: '老客户推荐', key: 'IsCusCommend', render: (_, r) => r.IsCusCommend === '1' ? '是' : '' },
    { title: '网站', dataIndex: 'WebCode', key: 'WebCode' },
    { title: '来源', dataIndex: 'SourceType', key: 'SourceType' },
    { title: '页面类型', dataIndex: 'COLI_LineClass', key: 'COLI_LineClass' },
  ];
  const columns = [
    { key: 'operatorName', title: '顾问', dataIndex: 'operatorName', width: '6em', filters: allOPI1, onFilter: (value, record) => record.operatorName === value, filterSearch: true },
    { key: 'SumOrder', title: '订单数', dataIndex: 'SumOrder', width: '5em' },
    { key: 'ConfirmOrder', title: '成交数', dataIndex: 'ConfirmOrder', width: '5em' },
    // { key: 'ConfirmPersonNum', title: '✔人数(SUM)', dataIndex: 'ConfirmPersonNum', width: '5em' },
    // { key: 'confirmTourdays', title: '✔团天数(AVG)', dataIndex: 'confirmTourdays', width: '5em' },
    { key: 'SumML', title: '预计毛利', dataIndex: 'SumML', width: '5em' }, // SumML_txt
    { key: 'ConfirmRates', title: '成交率', dataIndex: 'ConfirmRates_txt', width: '5em' },
    { key: 'SingleML', title: '单团毛利', dataIndex: 'SingleML', width: '5em' },
    { key: 'action', title: '', width: '5em', render: (_, r) => {
      const rowChildren = pageData.rawData.filter(ele => ele.operatorName === r.operatorName);
      return r.hasOld ? <TableExportBtn btnTxt='导出' label={`老客户-${r.operatorName}`} {...{ columns: rowColumns, dataSource: rowChildren }} /> : null;
    } },
  ];
  return (
    <>
      <Row gutter={16} className={siderBroken ? '' : 'sticky-top'}>
        <Col className="gutter-row" span={24}>
          <SearchForm
            defaultValue={{
              initialValue: {
                ...formValues,
                ...pageData.searchValues,
              },
              shows: ['DateType', 'DepartmentList', 'WebCode', 'dates'],
              fieldProps: {
                DepartmentList: { show_all: false, mode: 'multiple' },
                WebCode: { show_all: false, mode: 'multiple' },
                dates: { hide_vs: true },
              },
            }}
            onSubmit={(_err, obj, form, str) => {
              customer_store.setSearchValues(obj, form, 'sales_regular_data');
              customer_store.get_sales_regular_data(obj);
              // MeetingDataStore.setSearchValues(form);
              // dataRefresh(obj);
            }}
          />
        </Col>
      </Row>
      <h2>销售-老客户, 含推荐</h2>
      <Divider orientation="right" plain>
        <TableExportBtn btnTxt='导出明细' label={`${formValuesToSub.Date1}-销售.老客户-明细`} {...{ columns: rowColumns, dataSource: pageData.rawData }} />
        <Divider type={'vertical'} />
        <TableExportBtn btnTxt='导出下表' label={`${formValuesToSub.Date1}-销售.老客户`} {...{ columns, dataSource: dataForExport }} />
      </Divider>
      <Table
        sticky
        dataSource={pageData.data}
        loading={pageData.loading}
        columns={columns}
        pagination={false}
        defaultExpandAllRows
        expandable={{ defaultExpandAllRows: true, defaultExpandedRowKeys: pageData.data.map((ele) => ele.key) }}
      />
    </>
  );
};
export default observer(SalesCustomerCareRegular);
