import React, { useEffect, useMemo, useState } from 'react';
import { NodeGroup } from 'react-move';
import { interpolate, interpolateTransformSvg } from 'd3-interpolate';
import ProductAbnormal from './productionAbnormal';
import styles from './index.less';
import { useCallback } from 'react';
import moment from 'moment';
import { Modal } from 'antd';

type ProductProgressKanbanData = KANBAN.ProductProgress.ProductProgressKanbanDataDto;
type ProductProgressKanbanSetting = KANBAN.ProductProgress.ProductProgressKanbanSetting;

type FevorPanelProps = {
  setting: ProductProgressKanbanSetting;
  data: ProductProgressKanbanData[];
  conditionKey: string;
  rowMovingTime: number;
};

const FevorPanel: React.FC<FevorPanelProps> = ({ setting, data, conditionKey, rowMovingTime }) => {
  const rowHight = 52;
  const displayCount = 13;
  const [displayData, setDisplayData] = useState<ProductProgressKanbanData[]>([]);
  const [displayAt, setDisplayAt] = useState(0);
  const [pause, setPause] = useState(false);
  const [scollOnce, setScollOnce] = useState(false);
  const [groupData, setGroupData] = useState({});
  const [isModalOpen, setIsModalOpen] = useState(false);
  const closeModal = () => setIsModalOpen(false);
  const [criteria, setCriteria] = useState({});
  const openModal = (step, zgh) => {
    setCriteria({
      workshopName: '',
      zgh: zgh,
      operationName: step.name,
      status: '1,2,3,4,5',
      createdDateFrom: moment()
        .date(1)
        .hour(0)
        .minute(0)
        .second(0)
        .millisecond(0)
        .format('YYYY-MM-DD HH:mm'),
      createdDateTo: moment().format('YYYY-MM-DD HH:mm'),
      current: 1,
      pageSize: 10,
    });
    setIsModalOpen(true);
  };
  let processCt = {};

  //去掉步骤中的重复步骤名
  let tempStepName = '';
  setting.progress.steps = setting.progress.steps.filter((s) => {
    if (tempStepName == s.name) {
      return false;
    }
    tempStepName = s.name;
    return true;
  });
  const row_segment2_section_width = useMemo(
    () => (100 / setting.progress.steps.length).toFixed(4) + '%',
    [setting],
  );

  const updateDisplayData = (da: number, sData: ProductProgressKanbanData[]) => {
    let endAt1 = da + displayCount;
    let endAt2 = 0;
    if (endAt1 > sData.length) {
      endAt2 = endAt1 - sData.length;
      endAt1 = sData.length;
    }
    const ret = sData.slice(da, endAt1);
    if (sData.length > displayCount) {
      sData.slice(0, endAt2).forEach((i) => ret.push(i));
    }
    setDisplayData(ret);
  };

  useEffect(() => {
    data.forEach((s) => {
      for (const key in s.stepData) {
        s.stepData[key].tempOverDue = 0;
        //全部数量完成
        if (s.stepData[key].actualQuantity >= s.planQuantity) {
          //完成日期超过计划日期
          if (
            moment(s.stepData[key].actualEndDate).isAfter(moment(s.stepData[key].plannedEndDate))
          ) {
            let day = moment(s.stepData[key].actualEndDate)
              .hour(0)
              .minute(0)
              .second(0)
              .millisecond(0)
              .diff(
                moment(s.stepData[key].plannedEndDate).hour(0).minute(0).second(0).millisecond(0),
                'day',
                false,
              );
            s.stepData[key].tempOverDue = day;
          }
          if (s.stepData[key]?.actualEndDate) {
            s.stepData[key].tempEndDate = moment(s.stepData[key]?.actualEndDate).format('YY.MM.DD');
          }
        } else {
          if (moment().isAfter(moment(s.stepData[key]?.plannedEndDate))) {
            let day = moment()
              .hour(0)
              .minute(0)
              .second(0)
              .millisecond(0)
              .diff(
                moment(s.stepData[key]?.plannedEndDate).hour(0).minute(0).second(0).millisecond(0),
                'day',
                false,
              );
            s.stepData[key].tempOverDue = day;
          }
        }
        if (s.stepData[key].tempOverDue < setting.overdueNone) {
          s.stepData[key].tempOverDue = 0;
        } else if (
          s.stepData[key].tempOverDue >= setting.overdueWarn &&
          s.stepData[key].tempOverDue <= setting.overdueSeverity
        ) {
          s.stepData[key].tempOverDue = 1;
        } else if (s.stepData[key].tempOverDue > setting.overdueSeverity) {
          s.stepData[key].tempOverDue = 2;
        }
        if (processCt[key] == null) {
          processCt[key] = 0;
        }
        if (s.stepData[key].tempEndDate) {
          processCt[key] = processCt[key] + 1;
        }
      }
    });
    setGroupData(processCt);
    setDisplayAt(0);
    updateDisplayData(0, data);
  }, [conditionKey, data]);

  const scoll = useCallback(() => {
    if (pause) {
      return;
    }
    let da = 0;
    if (data.length > displayCount) {
      da = displayAt + 1;
      if (da >= data.length) {
        da = 0;
      }
    }
    setDisplayAt(da);
    updateDisplayData(da, data);
  }, [data, displayAt, pause]);

  useEffect(() => {
    const t = setInterval(() => {
      scoll();
    }, rowMovingTime * 1000);
    return () => {
      clearTimeout(t);
    };
  }, [rowMovingTime, scoll]);

  useEffect(() => {
    if (scollOnce) {
      scoll();
      setScollOnce(false);
    }
  }, [scollOnce, scoll]);

  return (
    <div className={styles.main}>
      <div className={styles.row_container}>
        <div className={styles.table_header_1}>
          <div className={styles.table_cell_c}>施工号</div>
        </div>
        <div className={styles.table_header_s}>
          <div className={styles.row_container}>
            {setting.progress.steps.map((step, i) => (
              <div
                className={styles.table_header_2}
                key={step.code}
                style={{ width: row_segment2_section_width }}
              >
                {step.name}
              </div>
            ))}
          </div>
          <div className={styles.row_container}>
            {setting.progress.steps.map((step, i) => (
              <div className={styles.row_container} style={{ width: row_segment2_section_width }}>
                <div className={styles.table_header_3}>计划</div>
                <div className={styles.table_header_3}>实际</div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div style={{ height: rowHight * displayCount }}>
        <NodeGroup
          data={displayData}
          keyAccessor={(d) => d.aufnr}
          start={(d, i) => {
            return { y: i * rowHight, opacity: 0 };
          }}
          enter={() => {
            return { opacity: [1], timing: { duration: 1000 } };
          }}
          update={(d, i) => {
            return { y: [i * rowHight], opacity: [1], timing: { duration: 1000 } };
          }}
          leave={() => {
            return { y: [-rowHight], opacity: [0], timing: { duration: 1000 } };
          }}
          interpolation={(begValue, endValue, attr) => {
            if (attr === 'transform') {
              return interpolateTransformSvg(begValue, endValue);
            }
            return interpolate(begValue, endValue);
          }}
        >
          {(nodes) => (
            <div
              className={styles.rowcontent}
              onMouseEnter={() => setPause(true)}
              onMouseLeave={() => {
                setPause(false);
                setScollOnce(true);
              }}
            >
              {nodes.map((node) => (
                <div
                  className={styles.row_container}
                  key={node.key}
                  style={{
                    position: 'absolute',
                    left: 0,
                    top: 0,
                    width: '100%',
                    transform: `translate(0px, ${node.state.y}px)`,
                    opacity: node.state.opacity,
                  }}
                >
                  <div className={styles.table_content} style={{ height: rowHight }}>
                    <div className={styles.table_cell_c}>{node.data.zgh}</div>
                  </div>
                  <div className={styles.table_content_s}>
                    {setting.progress.steps.map((step) => (
                      <div
                        className={styles.table_content2}
                        style={{ width: row_segment2_section_width, height: rowHight }}
                        key={step.code}
                      >
                        <div className={styles.table_cell_c2_left}>
                          {node.data.stepData[step.name]?.plannedEndDate
                            ? moment(node.data.stepData[step.name]?.plannedEndDate).format(
                                'YY.MM.DD',
                              )
                            : ' '}
                        </div>
                        <div
                          onClick={() => openModal(step, node.data.zgh)}
                          className={
                            `${styles.table_cell_c2_right} ` +
                            (node.data.stepData[step.name]?.tempOverDue == 1
                              ? styles.cell_backgroud_ovderdue1
                              : '') +
                            (node.data.stepData[step.name]?.tempOverDue == 2
                              ? styles.cell_backgroud_ovderdue2
                              : '')
                          }
                        >
                          {node.data.stepData[step.name]?.tempEndDate
                            ? node.data.stepData[step.name]?.tempEndDate
                            : ' '}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </NodeGroup>
      </div>
      <div className={styles.row_container}>
        <div className={styles.bottom_row_container}>
          <div className={styles.bottom_header_1}>本月累计达成率：</div>
          <div className={styles.table_content_s}>
            {setting.progress.steps.map((step, i) => (
              <div
                className={
                  `${styles.bottom_header_2} ` +
                  (i + 1 === setting.progress.steps.length && styles.no_right_border)
                }
                style={{ width: row_segment2_section_width }}
              >
                {data.length > 0
                  ? (
                      ((groupData && groupData[step.name] ? groupData[step.name] : 0) /
                        data.length) *
                      100
                    ).toFixed(2) + '%'
                  : ''}
                {data.length > 0 && (
                  <div className={styles.bottom_header_2_val}>
                    {groupData && groupData[step.name] ? groupData[step.name] : '0'}/{data.length}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
      <Modal
        title={'生产异常明细'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <ProductAbnormal values={criteria} />
      </Modal>
    </div>
  );
};

export default FevorPanel;
