import { Button, Popup } from "vant";
import { } from "vant";
import { defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import styles from "./index.module.less";
import { getImage } from "./images";
import {getGuidance, setGuidance} from './api'
export default defineComponent({
  name: "courseware-list",
  emits: ["close"],
  setup(props, { emit }) {
    const data = reactive({
      box: {},
      show: false,
      steps: [
        {
          ele: "",
          eleRect: {} as DOMRect,
          img: getImage("courseware-list1.png"),
          handStyle: {
            top: "1.5rem",
            left:"3.5rem",
            transform: 'rotate(-90deg)'
          },
          imgStyle: {
            top: ".7rem",
            left:"5rem",
          },
          btnsStyle: {
            top: "3.5rem",
            left:"6.2rem",
          },
          boxStyle:{
					},
					eleRectPadding: {
						left: -4,
						top: -4,
						width: -8,
						height: -8
					  }
        },
        {
          ele: "",
          img: getImage("courseware-list2.png"),
          handStyle: {
            top: "-.25rem",
            left:"1.38rem",
            transform: 'rotate(-90deg)'
          },
          imgStyle: {
            top: "-1.2rem",
            left:"2.4rem",

          },
          btnsStyle: {
            top: "1.6rem",
            left:'3.6rem',
          },
          eleRectPadding: {
						left: 4,
						top: 4,
						width: 8,
						height: 8
					  }
        },
        {
          ele: "",
          img: getImage("courseware-list3.png"),
          handStyle: {
            bottom: "-2.1rem",
            left:'0.66rem',

          },
          imgStyle: {
            top: "1.1rem",
            left:'-2rem'
          },
          btnsStyle: {
            top:"4.2rem",
            left:'-0.5rem',
          },
          eleRectPadding: {
						left: 4,
						top: 4,
						width: 8,
						height: 8
					  }

        },
        {
          ele: "",
          img: getImage("courseware-list4.png"),
          handStyle: {
            top: ".8rem",
            left:'1rem',

          },
          imgStyle: {
            top: "1.1rem",
            left:'-4.6rem',

          },
          btnsStyle: {
            top: "4rem",
            left: "-4.5rem",
            "justify-content": "center",
            padding: 0,
          },
        },
      ],
      step: 0,
    });
    const tipShow = ref(false)
    const guideInfo = ref({} as any)
    const getAllGuidance = async()=>{
      try{
        const res = await getGuidance({guideTag:'guideInfo'})
        if(res.data){
          guideInfo.value = JSON.parse(res.data?.guideValue) || null
        }else{
          guideInfo.value = {}
        }
        if (guideInfo.value &&guideInfo.value.courseware) {
          tipShow.value = false;
        } else {
          tipShow.value = true;
        }
      }catch(e){
        console.log(e)
      }

      // const guideInfo = localStorage.getItem('teacher-guideInfo');

    }
    getAllGuidance()
  //  const guideInfo = localStorage.getItem('guideInfo')
  //  if(guideInfo&&JSON.parse(guideInfo).courseware){
  //   tipShow.value =false
  //  }else {
  //   tipShow.value =true
  //  }
    const getStepELe = () => {
      const ele: HTMLElement = document.getElementById(`courseware-${data.step}`)!;
      if (ele) {
				const eleRect = ele.getBoundingClientRect();

				const left = data.steps[data.step].eleRectPadding?.left || 0;
				const top = data.steps[data.step].eleRectPadding?.top || 0;
				const width = data.steps[data.step].eleRectPadding?.width || 0;
				const height = data.steps[data.step].eleRectPadding?.height || 0;
				data.box = {
				  left: eleRect.x - left + 'px',
				  top: eleRect.y - top + 'px',
				  width: eleRect.width + width + 'px',
				  height: eleRect.height + height + 'px'
				};
			  }else{
				handleNext()
			  }
    };
    onMounted(() => {
      getStepELe();
      window.addEventListener("resize", resetSize);
    });
    const resetSize = ()=>{
      getStepELe();
    }

    onUnmounted(()=>{
      window.removeEventListener("resize", resetSize);
    })

    const handleNext = () => {
      if (data.step >= 3) {
       endGuide();
        return;
      }
      data.step = data.step + 1;
      getStepELe();
    };

    const endGuide = async()=>{
      // let guideInfo = JSON.parse(localStorage.getItem('guideInfo') || '{}') || null
      if(!guideInfo.value){
        guideInfo.value = {courseware:true}
      }else{
        guideInfo.value.courseware = true
      }

      try{
        const res = await setGuidance({guideTag:'guideInfo',guideValue:JSON.stringify(guideInfo.value)})
      }catch(e){
        console.log(e)
      }
      // localStorage.setItem('guideInfo',JSON.stringify(guideInfo))
      console.log('调用list完成')
      tipShow.value = false
    //  localStorage.setItem('endC')
    }
    return () => (
      <Popup teleport="body" overlay={false} closeOnClickOverlay={false} class={["popup-custom", styles.guidePopup]} v-model:show={tipShow.value}>
      <div class={styles.content} onClick={() => handleNext()}>
      {data.step!=data.steps.length-1&&<div
          class={styles.backBtn}
          onClick={(e: Event) => {
            e.stopPropagation();
           endGuide()
          }}
        >

          跳过
        </div>}
        <div class={styles.box} style={{...data.box,...data.steps[data.step].boxStyle}} id={`modeType-${data.step}`}>
          {data.steps.map((item: any, index) => (

            <div
              onClick={(e: Event) => e.stopPropagation()}
              class={styles.item}
              style={{
                display: index === data.step ? "" : "none",
                left: `${item.eleRect?.left}px`,
                top: `${item.eleRect?.top}px`,
              }}
            >
              <img class={styles.img} style={item.imgStyle} src={item.img} />
              <img class={styles.iconHead} style={item.handStyle} src={getImage("indexDot.png")} />
              <div class={styles.btns} style={item.btnsStyle}>
                {data.step + 1 == data.steps.length ? (
                  <>
                     <Button class={[styles.btn]} round type="primary" onClick={() =>endGuide()}>
                      完成
                    </Button>
                    <Button
                      class={[styles.btn,styles.endBtn]}
                      round
                      color="transparent"
                      style={{ "border-color": "#fff" }}
                      type="primary"
                      onClick={() => {
                        data.step = 0;
                        getStepELe();
                      }}
                    >
                      再看一遍
                    </Button>

                  </>
                ) : (
                  <Button class={styles.btn} round type="primary" onClick={() => handleNext()}>
                    下一步 ({data.step + 1}/{data.steps.length})
                  </Button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
      </Popup>
    );
  },
});
