import React, { useContext, useEffect, useState } from 'react';
import { Row, Col, Button, Tabs, Table, Divider, Radio, Select, Space, Typography, Progress } from 'antd';
import { ContainerOutlined, SearchOutlined, UserSwitchOutlined } from '@ant-design/icons';
import { stores_Context } from '../config';
import { observer } from 'mobx-react';
import { NavLink, useParams } from 'react-router-dom';
import * as comm from '../utils/commons';
import * as config from '../config';
import { utils, writeFileXLSX } from 'xlsx';
import SearchForm from './../components/search/SearchForm';
import { dataFieldAlias } from '../libs/ht';

const { Text } = Typography;

const Sale_KPI = () => {
  const { sale_store, date_picker_store: searchFormStore } = useContext(stores_Context);
  const { formValues } = searchFormStore;
  const { loading, operator } = sale_store.salesTrade;

  const [groupType, setGroupType] = useState('dept');
  const dataSource = [].concat(sale_store.salesTrade[groupType], operator);

  const pageRefresh = (queryData) => {
    const overviewFlag = queryData.DepartmentList.toLowerCase() === 'all' || queryData.DepartmentList.toLowerCase().includes(',');
    const _groupType = overviewFlag ? 'overview' : 'dept';
    setGroupType(_groupType);
    sale_store.fetchOperatorTradeData(_groupType, { ...queryData, groupDateType: 'year' });
    sale_store.fetchOperatorTradeData('operator', { ...queryData, groupDateType: 'year' });
  };
  const monthCol = new Array(12).fill(1).map((_, index) => {
    return {
      title: `${index + 1}月`,
      dataIndex: `M${index + 1}Percent`,
      valueType: 'digit',
      width: '7.5em',
      render: (_, row) => (
        <Space direction={'vertical'}>
          <div>
            <Text italic type={'secondary'}>
              {dataFieldAlias.SumML.formatter(row.mData[`month_${String(index + 1).padStart(2, '0')}`]?.MLKPIvalue || 0)}
            </Text>
          </div>
          <div>{dataFieldAlias.SumML.formatter(row.mData[`month_${String(index + 1).padStart(2, '0')}`]?.SumML || 0)}</div>
          {row.mData[`month_${String(index + 1).padStart(2, '0')}`]?.MLKPIrates || 0 ? (
            <Progress
              percent={row.mData[`month_${String(index + 1).padStart(2, '0')}`]?.MLKPIrates || 0}
              size="small"
              format={(percent) => `${row.mData[`month_${String(index + 1).padStart(2, '0')}`]?.MLKPIrates || 0}%`}
            />
          ) : (
            '-'
          )}
        </Space>
      ),
    };
  });
  const columns = [
    {
      title: ``,
      dataIndex: 'groupsLabel',
      editable: false,
      width: '7.5em',
    },
    {
      title: '年度',
      dataIndex: 'yearValue',
      width: '10em',
      render: (_, row) => (
        <Space direction={'vertical'}>
          <div>
            <Text italic type={'secondary'}>
              <span style={{ marginRight: '.5em' }}>目标</span>
              {dataFieldAlias.SumML.formatter(row.yData?.MLKPIvalue || 0)}
            </Text>
          </div>
          <div>
            <span style={{ marginRight: '.5em' }}>完成</span>
            {dataFieldAlias.SumML.formatter(row.yData?.SumML || 0)}
          </div>
          {row.yData?.MLKPIrates || 0 ? <Progress percent={row.yData?.MLKPIrates || 0} size="small" format={(percent) => `${row.yData?.MLKPIrates || 0}%`} /> : '-'}
        </Space>
      ),
    },
    ...monthCol,
  ];
  return (
    <div>
      <Row gutter={16} style={{ margin: '-16px -8px' }}>
        <Col md={24} lg={24} xxl={24}>
          <SearchForm
            defaultValue={{
              initialValue: {
                ...formValues,
              },
              shows: ['DateType', 'DepartmentList', 'WebCode', 'IncludeTickets', 'years'],
              fieldProps: {
                DepartmentList: { show_all: true },
                WebCode: { show_all: true },
                years: { hide_vs: true },
              },
            }}
            onSubmit={(_err, obj, form, str) => {
              pageRefresh(obj);
            }}
          />
        </Col>
      </Row>

      <Row>
        <Col className="gutter-row" md={24}>
          <Table
            key={`salesTradeTable`}
            loading={loading}
            columns={columns}
            rowKey="groupsKey"
            scroll={{
              x: 1000,
            }}
            dataSource={dataSource}
            pagination={false}
          />
        </Col>
      </Row>
    </div>
  );
};
export default observer(Sale_KPI);
