import { useContext, useEffect, useState } from 'react';
import { stores_Context } from './../config';
import { observer } from 'mobx-react';
import { Row, Col, Tabs, Spin } from 'antd';
import { flush, isEmpty, objectMapper, pick } from './../utils/commons';
import { KPIObjects } from './../libs/ht';
import ObjectPanel from '../components/kpi/ObjectPanel';
import OverviewPanel from './../components/kpi/OverviewPanel';
import './kpi.css';

const objectComponents = {
  // 'overview': OverviewPanel,
  'overview': ObjectPanel,
  'bu': ObjectPanel,
  'dept': ObjectPanel,
  'du': ObjectPanel,
  'operator': ObjectPanel,
  'destination': ObjectPanel,
  'country': ObjectPanel,
};
const objectFilterKey = {
  'bu': ['HTBusinessUnits'],
  'dept': ['DepartmentList'],
  // 'du': 'du',
  // 'operator': 'operator',
  'destination': ['city', ],
  'country': ['country'],
};
export default observer((props) => {
  const { KPIStore, DictDataStore, date_picker_store: searchFormStore } = useContext(stores_Context);
  // useEffect(() => {
  //   return () => {};
  // }, []);
  const [curObject, setCurObject] = useState('overview');
  const onObjectChange = (object) => {
    setCurObject(object);
    setRetObjects([]);
  };
  useEffect(() => {
    onSearchSubmit(searchFormStore.formValuesToSub);

    return () => {};
  }, [curObject]);

  const [retObjects, setRetObjects] = useState([]);
  const onSearchSubmit = async (obj, formVal={}) => {
    const getkpiParam = objectMapper(obj, {
      DateType: { key: 'date_type' },
      Date1: { key: 'start_date' },
      Date2: { key: 'end_date' },
      HTBusinessUnits: { key: 'object_id' },
      DepartmentList: { key: curObject === 'dept' ? 'object_id' : 'dept_id' },
      businessUnits: { key: 'object_id' },
      WebCode: { key: 'object_id' },
      operator: { key: 'object_id' },
      country: { key: 'object_id' },
    });
    Object.assign(getkpiParam, { object: curObject });
    KPIStore.setSettingYear(formVal?.year?.year() || KPIStore.settingYear);
    // console.log('invoke on search', obj, formVal, getkpiParam);
    if (curObject === 'operator') {
      KPIStore.setListLoading(true);
      const searchOperator = await DictDataStore.fetchDictData('operator', {
        // is_assign: 1,
        dept_id: (obj?.DepartmentList || '').replace('ALL', ''),
        q: searchFormStore.formValues?.operator?.label || '',
      });
      if ((!isEmpty(getkpiParam.dept_id) && getkpiParam.dept_id !== 'ALL')
        || !isEmpty(searchFormStore.formValues?.operator)) {
        // && isEmpty(getkpiParam.object_id)
        setRetObjects(searchOperator.dataSource);
        getkpiParam.object_id = searchOperator.dataSource.map((ele) => ele.key).join(',');
        delete getkpiParam.dept_id;
      }
    }
    await getKPIList(getkpiParam);
  };
  const getKPIList = async (getkpiParam) => {
    const _data = await KPIStore.getList(getkpiParam);
    // KPIStore.getList(getkpiParam).then((data) => {
      // // setDataSource(data);
      if (objectFilterKey?.[curObject]) {
        const selectItems = Object.values(pick(searchFormStore.formValues, objectFilterKey[curObject]));
        const _selectItems = flush(selectItems).map((ele) => ({ ...ele, value: ele.key }));
        setRetObjects(_selectItems);
      }
    // });
  };
  return (
    <>
      <Row>
        <Col span={24}>
          <Tabs
            onChange={onObjectChange}
            type="card"
            items={KPIObjects.map((ele, i) => {
              const ObjectItemPanel = objectComponents?.[ele.key] || ObjectPanel;
              return {
                ...ele,
                children: (
                  <Spin spinning={KPIStore.listLoading}>
                    <ObjectItemPanel title={ele.label} {...{ curObject, onSearchSubmit, objects: retObjects }} />
                  </Spin>
                ),
              };
            })}
          />
        </Col>
      </Row>
    </>
  );
});
