import { css } from "@linaria/core";
import { defineComponent, onMounted, onUnmounted, reactive, ref } from "vue";
import { useCtx } from "../../context";
import { ShowItem } from "@/modules/list/state";
import Dialog from "./dialog";
import { conformsTo, divide } from "lodash";
import dialog from "@/modules/list/actions/dialog";
import { nextTick } from "process";

export default defineComponent({
  setup() {
    const ctx = useCtx();
    const { list } = ctx;
    const state = reactive({
      scrollElement: [] as any,
      dialogId: 0,
    });
    function clickItem(e: any, itemIndex: number) {
      list.actions.addDialog(e, itemIndex);
    }

    const rows: number[] = [];
    for (let i = 0; i < list.state.totalRow; i++) {
      rows.push(i);
    }

    function renderRow(start: number, end: number) {
      const arr = [];
      for (let i = start; i < end; i++) {
        const item = list.state.items[i];

        arr.push(
          <div
            class="item"
            onClick={(e) => {
              clickItem(e, i);
            }}
          >
            <img key={i} src={item.url} />
            <div class={"name"}>{item.name}</div>
            {/* <span class="debug">
              {`${Math.round(item.offsetX)}, ${Math.round(item.currX)}`}
            </span> */}
          </div>
        );
      }
      return arr;
    }

    const rootRef = ref<HTMLElement>();
    const scrollRefs = ref();
    onMounted(async () => {
      await list.actions.loadData(
        rootRef.value?.clientWidth as number,
        rootRef.value?.clientHeight as number
      );

      scrollInit();
      scrollEvent();
      nextTick(() => {
        scrollStart();
      });
    });

    let timmerRef = ref<any>(0);
    let speedRef = ref<number>(1);
    onUnmounted(() => {
      rows.map((e, i) => {
        if (state.scrollElement[i].timmer) {
          clearTimeout(state.scrollElement[i].timmer);
        }
      });
    });
    const MoveStart = (id: number) => {
      state.dialogId = id;
    };
    const scrollInit = () => {
      rows.map((e, i) => {
        state.scrollElement[i] = {};
        state.scrollElement[i].y = -(
          scrollRefs[i].clientHeight - list.state.parentHeight
        );
        state.scrollElement[i].trans = false;
        state.scrollElement[i].timmer = 0;
      });
    };
    const scrollEvent = () => {
      rows.map((e, i) => {
        eventListener(i);
      });
    };
    const scrollStart = () => {
      rows.map((e, i) => {
        scrollItem(i);
      });
    };
    const scrollItem = (i: number) => {
      state.scrollElement[i].y += speedRef.value;
      state.scrollElement[i].trans = true;
      if (state.scrollElement[i].y >= 0) {
        state.scrollElement[i].trans = false;
        state.scrollElement[i].y = -(
          scrollRefs[i].clientHeight - list.state.parentHeight
        );
      }
      state.scrollElement[i].timmer = setTimeout(() => {
        scrollItem(i);
      }, 1000 / 20);
    };
    const eventListener = (i: number) => {
      let down = false;
      let y = 0;
      scrollRefs[i].addEventListener("touchstart", (e) => {
        down = true;
        clearTimeout(state.scrollElement[i].timmer);
        let touch = e.touches[0];
        state.scrollElement[i].trans = false;
        y = touch.clientY;
      });
      scrollRefs[i].addEventListener("touchmove", (e) => {
        if (down) {
          let touch = e.touches[0];
          let offsetY = Math.floor(touch.clientY - y);
          state.scrollElement[i].y += offsetY;
          if (state.scrollElement[i].y >= 0) {
            state.scrollElement[i].y = -(
              scrollRefs[i].clientHeight - list.state.parentHeight
            );
          }
          y = touch.clientY;
        }
      });
      scrollRefs[i].addEventListener("touchend", (e) => {
        down = false;
        state.scrollElement[i].trans = true;
        state.scrollElement[i].timmer = setTimeout(() => {
          scrollItem(i);
        }, 1000 / 20);
        y = 0;
      });
    };
    return () => (
      <div class={rootStyle} ref={rootRef}>
        {rows.map((item, index) => {
          const rowCount = list.state.rowCount;
          const start = index * rowCount;
          const end = start + rowCount;

          return (
            <div class="row">
              <div
                class="content"
                ref={(el) => (scrollRefs[index] = el)}
                style={{
                  transform: `translateY(${state.scrollElement[index]?.y}px)`,
                  transitionProperty: `${
                    state.scrollElement[index]?.trans ? "transform" : "none"
                  }`,
                }}
              >
                {renderRow(start, end)}
              </div>
            </div>
          );
        })}

        {list.state.dialogs.map((item) => (
          <Dialog data={item} key={item.id} onMove={MoveStart} />
        ))}
      </div>
    );
  },
});

const rootStyle = css`
  position: relative;
  height: 100%;
  width: 100%;
  display: flex;
  background-color: #3f322c;
  overflow: hidden;
  user-select: none;
  flex-flow: row;
  padding-top: 0.1rem;
  padding-left: 0.1rem;

  .row {
    position: relative;
    flex: 1;
    margin-right: 0.1rem;
    width: 0;
    flex-shrink: 0;

    .content {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      transition-duration: 100ms;
      transition-timing-function: linear;

      img {
        pointer-events: none;
        width: 100%;
        object-fit: contain;
      }

      .item {
        position: relative;
        margin-bottom: 0.1rem;
        cursor: pointer;
        .name {
          width: 100%;
          padding: 0.04rem 0;
          color: #fff;
          font-size: 0.12rem;
          text-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .debug {
          position: absolute;
          left: 0;
          color: red;
        }
      }
    }
  }
`;
