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

type ErrorDetailCriteria = KANBAN.ProductionComprehens.ErrorDetailCriteria;
type ProductionProgressKanbanData = KANBAN.ProductionProgress.ProductionProgressKanbanDataDto;
type ProductionProgressKanbanSetting = KANBAN.ProductionProgress.ProductionProgressKanbanSetting;

type ProgressTableProps = {
  setting: ProductionProgressKanbanSetting;
  data: ProductionProgressKanbanData[];
  conditionKey: string;
  rowMovingTime: number;
};

const ProgressTable: React.FC<ProgressTableProps> = ({
  setting,
  data,
  conditionKey,
  rowMovingTime,
}) => {
  const rowHight = 60;
  const displayCount = 13;

  const [displayData, setDisplayData] = useState<ProductionProgressKanbanData[]>([]);
  const [displayAt, setDisplayAt] = useState(0);
  const [lastConditionKey, setLastConditionKey] = useState('');
  const [pause, setPause] = useState(false);
  const [scollOnce, setScollOnce] = useState(false);
  //去掉步骤中的重复步骤名
  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: ProductionProgressKanbanData[]) => {
    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(() => {
    if (lastConditionKey !== conditionKey) {
      setLastConditionKey(conditionKey);
      setDisplayAt(0);
      updateDisplayData(0, data);
    }
  }, [conditionKey, lastConditionKey, 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]);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpen2, setIsModalOpen2] = useState(false);
  const [criteria, setCriteria] = useState({} as ErrorDetailCriteria);
  const closeModal = () => setIsModalOpen(false);
  const closeModal2 = () => setIsModalOpen2(false);
  const [productionDetailParams, setProductionDetailParams] = useState({
    kanbanSettingId: '',
    aufnr: '',
    processName: '',
  });
  const openModal = (data, step) => {
    if (!setting.id) return;
    if (data.stepData.length) {
      setProductionDetailParams({
        kanbanSettingId: setting.id,
        aufnr: data.aufnr,
        processName: step.name,
      });
      setIsModalOpen(true);
    }
  };

  const openModal2 = (zgh: string) => {
    setCriteria({
      workshopName: '',
      zgh: zgh,
      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,
    });
    if (!setting.id) return;
    setIsModalOpen2(true);
  };

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

  return (
    <div className={styles.main}>
      <div className={styles.row_container} style={{ height: rowHight }}>
        <div className={styles.row_segment1}>
          <div
            className={`${styles.row_segment1_section1} ${styles.no_top_border} ${styles.no_left_border}`}
          >
            <div className={styles.cell}>施工号</div>
          </div>
          <div className={`${styles.row_segment1_section2} ${styles.no_top_border}`}>
            <div className={styles.cell}>数量</div>
          </div>
        </div>
        <div className={styles.row_segment2}>
          {setting.progress.steps.map((step, i) => (
            <div
              className={
                `${styles.row_section} ${styles.no_top_border} ` +
                (i + 1 === setting.progress.steps.length && styles.no_right_border)
              }
              style={{ width: row_segment2_section_width }}
              key={step.code}
            >
              <div className={styles.cell}>{step.name}</div>
            </div>
          ))}
        </div>
      </div>
      <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.data_rowcontent}
            onMouseEnter={() => setPause(true)}
            onMouseLeave={() => {
              setPause(false);
              setScollOnce(true);
            }}
          >
            {nodes.map((node: { [key: string]: any; data: ProductionProgressKanbanData }) => (
              <div
                className={styles.row_container}
                key={node.key}
                style={{
                  position: 'absolute',
                  left: 0,
                  top: 0,
                  width: '100%',
                  height: rowHight,
                  transform: `translate(0px, ${node.state.y}px)`,
                  opacity: node.state.opacity,
                }}
              >
                <div className={styles.row_segment1}>
                  <div
                    className={styles.row_segment1_section1}
                    onClick={() => openModal2(node.data[setting.sgNoSourceType.code])}
                  >
                    <div className={styles.cell}>{node.data[setting.sgNoSourceType.code]}</div>
                  </div>
                  <div className={styles.row_segment1_section2}>
                    <div className={styles.cell}>{node.data.planQuantity}</div>
                  </div>
                </div>
                <div className={styles.row_segment2}>
                  {setting.progress.steps.map((step) => (
                    <div
                      className={styles.row_section}
                      style={{ width: row_segment2_section_width }}
                      key={step.code}
                      onClick={() => openModal(node.data, step)}
                    >
                      <StepCell step={step} data={node.data} setting={setting} />
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </NodeGroup>

      <Modal
        title={'批次完工'}
        visible={isModalOpen}
        footer={null}
        width={'70%'}
        onCancel={closeModal}
      >
        <ProductionDetail params={productionDetailParams} />
      </Modal>
      <Modal
        title={'生产异常'}
        visible={isModalOpen2}
        footer={null}
        width={'70%'}
        onCancel={closeModal2}
      >
        <ProductionAbnormal values={criteria} />
      </Modal>
    </div>
  );
};

export default ProgressTable;
