import type { CSSProperties } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import Crust1 from '../../components/Real4K/Crust1';
import Style1 from '../../components/Real4K/Style1';
import SettingForm from './components/SettingForm';
import type { Setting } from './components/SettingForm';
import styles from './index.less';
import FevorPanel from './components/FevorPanel';
import moment from 'moment';
import { queryJiejingWorkSiteProduction } from '@/services/kanban/api';

type DataGroupItem = {
  fevor: string;
  style: CSSProperties | undefined;
  data: KANBAN.JiejingProductionScheduleKanbanDto[];
};

const Main: React.FC = () => {
  const [setting, setSetting] = useState<Setting>({
    autoResize: false,
    intervalTime: 600,
    rowMovingTime: 5,
  });

  const [settingFormVisible, setSettingFormVisible] = useState(false);
  const [startTime, setStartTime] = useState<moment.Moment>(moment());
  const [endTime, setEndTime] = useState<moment.Moment>(moment());
  const [data, setData] = useState<KANBAN.JiejingProductionScheduleKanbanDto[]>([]);
  const [conditionKey, setConditionKey] = useState('');
  const dataGroup = useMemo((): DataGroupItem[] => {
    if (!!!data) {
      return [];
    }
    if (!!!data.length) {
      return [];
    }
    const dataGropuInit = new Map<string, DataGroupItem>();
    const dataGroupTemp = data.reduce((group, item) => {
      const { fevor } = item;
      if (!group.has(fevor)) {
        group.set(fevor, { fevor, data: [], style: undefined });
      }
      group.get(fevor)?.data.push(item);
      return group;
    }, dataGropuInit);

    const totalWidth = 3840;
    const marginLeft = 40;
    const count = dataGroupTemp.size;
    const perWidth = (totalWidth - (count - 1) * 40) / count;

    const returnValue: DataGroupItem[] = [];
    let isfirst = true;
    dataGroupTemp.forEach((item) => {
      returnValue.push(item);
      if (isfirst) {
        item.style = { width: perWidth };
        isfirst = false;
        return;
      }
      item.style = { width: perWidth, marginLeft };
    });

    return returnValue;
  }, [data]);

  useEffect(() => {
    const { intervalTime } = setting;
    const refresh = async () => {
      const now = Date.now();
      const st = moment(now).year(2000);
      const et = moment(now).year(2030);

      setStartTime(st);
      setEndTime(et);

      const dataResp = await queryJiejingWorkSiteProduction({
        startDate: st.format('YYYY-MM-DD HH:mm:ss'),
        endDate: et.format('YYYY-MM-DD HH:mm:ss'),
      });

      setData(dataResp.data);
      setConditionKey(now.toString());
    };
    refresh().finally();
    const t = setInterval(() => {
      refresh();
    }, intervalTime * 1000);
    return () => {
      clearTimeout(t);
    };
  }, [setting]);

  return (
    <>
      <Style1
        headerText="生产进度看板"
        autoResize={setting.autoResize}
        onHeaderClick={() => {
          setSettingFormVisible(true);
        }}
      >
        <div className={styles.main}>
          <div className={styles.title}>
            <div className={styles.title_work_site}>
              <div className={styles.title_work_site_legend} />
              <div className={styles.title_work_site_text}>洁净气瓶车间</div>
            </div>
            <div className={styles.title_machine_stat}>
              <div className={styles.title_machine_stat_item_l}>
                计划完成时间： {startTime.format('YYYY.MM.DD')} - {endTime.format('YYYY.MM.DD')}
              </div>
            </div>
            <div className={styles.title_right} />
          </div>
          <div className={styles.content}>
            {dataGroup.map((item) => (
              <div style={item.style} key={item.fevor}>
                <Crust1 className={styles.crust}>
                  <div className={styles.content_machs_1}>
                    <FevorPanel
                      dtoArray={item.data}
                      startTime={startTime}
                      endTime={endTime}
                      conditionKey={conditionKey}
                      rowMovingTime={setting.rowMovingTime}
                    />
                  </div>
                </Crust1>
              </div>
            ))}
          </div>
        </div>
      </Style1>
      <SettingForm
        values={{ ...setting }}
        visible={settingFormVisible}
        onVisibleChange={setSettingFormVisible}
        onSubmitting={async (settingParams) => {
          setSetting({ ...settingParams });
        }}
      />
    </>
  );
};

export default Main;
