import {$el, $elByClass} from "../plugin/getElPlugin.js";
import {c, classSwitch, finStrOf, getProductId, headModule, hrefModule, productRenderModule, debounce} from "../shares/utils.js";
import htmlInsert from "../plugin/htmlPlugin.js";
import template from "../template.js";
import {oHeadEvent} from "./bindEvent.js";

export let lastIdx = new Number(0),
    idx = 0,
    navSpeed = 5000,
    navArr = [],
    sIdx = 0,
    lastPageX = 0,
    newOffsetArr = [],
    newIdx = [],
    newOffX = 0,
    _sIdx = 0,
    pIdx = 0,
    pageIdx = 0,
    honourSpeed = 1,
    honourSerInterval,
    oHonour,
    searchClick = 0,
    nIdx = 0,
    timer = null
    event = {
        headEvent : {
            init() {
                lastIdx.initVal = 0
                !document.documentElement.scrollTop
                    ?   $el('.headerBox').style.position = "relative"
                    :   $el('.headerBox').style.position = "fixed"
            },
            phoneSwitch() {
                classSwitch($elByClass('phoneHideBox')[0])
            },
            menuEvent() {
                let nextElClassName = this.nextElementSibling.className,
                    lastNode = $elByClass('fMenu')[lastIdx],
                    lastNextEl = lastNode?.nextElementSibling,
                    idx = $elByClass('fMenu').indexOf(this)
                lastNode?.className && (lastNode.className = lastNode.className.replaceAll('MenuActive', ' '))
                lastNextEl.className = lastNextEl.className.replaceAll('slide-in-bck-bottom', 'dNone')
                classSwitch(this.nextElementSibling, nextElClassName, false,false) && (this.className = this.className + ' MenuActive')
                //利用包装类
                lastNode === this && lastNode.initVal!==0 &&(lastNode.className = lastNode.className.replaceAll('MenuActive', ' '))
                lastNode.initVal++
                lastIdx = idx
            },
            MenuBigBoxEvent(event){
                let tar = event.target || event.srcElement,
                    tarClassName = tar.className,
                    navHeaderIdx = Array.prototype.indexOf.call($el('.navHeader').children,tar)
                //可以优化⬇
                if(finStrOf(tarClassName,'phoneHideBox') && !finStrOf($el('.navHeader').className,'dNone')){
                    classSwitch($elByClass('phoneHideBox')[0])
                }else if(finStrOf(tarClassName,'phoneHideBox') && finStrOf($el('.navHeader').className,'dNone')){
                    classSwitch($elByClass('productBox')[0],$elByClass('productBox')[0].className,true,false)
                    classSwitch($elByClass('navHeader')[0],$elByClass('navHeader')[0].className,true,false)
                }else if(finStrOf(tarClassName,'navHeaderProduct')){
                    classSwitch($elByClass('productBox')[0],$elByClass('productBox')[0].className,true,false)
                    classSwitch($elByClass('navHeader')[0],$elByClass('navHeader')[0].className,true,false)
                }
            },
            headerEvent(item,idx,e){
                e.preventDefault()
                hrefModule(this.getAttribute('href'))
            },
            navClick(list,sw){
                let _idx = list.indexOf(this)
                sw.slideToLoop(_idx,300,false)
            },
            headScroll(e){
                let scrollTop = document.documentElement.scrollTop,
                    oHead = $el('.headerBox'),
                    tar = $el('.navBigBox') || $el('.posterBigBox')
                $el('.poster') && (()=>{
                    $el('.posterBox').style.transform = `translateY(${scrollTop}px)`
                    if(scrollTop <  $el('.poster').offsetHeight/1.5){
                        ($el('.poster').style.filter = 'blur(0)')
                    }else{
                        ($el('.poster').style.filter = 'blur(15px)')
                    }
                })();
                if(scrollTop){
                    tar && (()=>{
                        tar.style.paddingTop = getComputedStyle($el('.headerBox'),null)['height']
                        $el('.navBigBox') && ($el('.navIcon').style.marginTop = getComputedStyle($el('.headerBox'),null)['height'])
                    })()
                    oHead.style.position = 'fixed'
                }else{
                    tar && (()=>{
                        tar.style.paddingTop = 0+'px'
                        $el('.navBigBox') && ( $el('.navIcon').style.marginTop = 0+'px')
                    })()
                    oHead.style.position = 'relative'

                }
                $el('.aboutsBg') && (()=>{
                    // $el('.aboutsBg').children[0].style.transform = `translateY(${scrollTop}px)`
                })()
            },
            searchBoxClick(){
                 (()=>{
                    let oSearch = $el('.searchBigBox'),
                        _oSearch = $el('.searchBox')
                    if(!(searchClick % 2 ===0)){
                        _oSearch.style.display = 'none'
                        oSearch.style.height = 0+'px'
                        oSearch.style.paddingTop = 0+'px'
                        $el('.searchDetail').style.display = 'none'
                        $el('.searchBox').style.borderRadius = 10+'px'
                        htmlInsert({
                            data:[],
                            dom:'',
                            el:'.searchDetail'
                        })
                        _oSearch.value = ''
                    }else{
                        _oSearch.style.display = 'block'
                        oSearch.style.height = 60+'px'
                        oSearch.style.paddingTop = 10+'px'
                    }
                    searchClick++
                })()
            },
            searchBoxInput(opt,e){
                let oSearchDetail = $el('.searchDetail'),
                        _item = []
                    if(timer !== null){
                        clearTimeout(timer);
                    }
                    timer = setTimeout(()=>{
                        fetch(`/home/HomeSearch?search=${e.target.value}`,{
                            method:'GET',
                        }).then(res=>{
                            return res.json()
                        }).then(res=> {
                            if(res.code === 0){
                                res.data.content.map(item=>{
                                    _item.push({
                                        dictionary_id:item.id,
                                        product_type:item.product_name
                                    })
                                })
                                oSearchDetail.style.display = 'block'
                                $el('.searchBox').style.borderRadius = '10px 10px 0 0'
                                htmlInsert({
                                    data:_item,
                                    dom:template().searchTpl,
                                    el:'.searchDetail'
                                })
                            }else{
                                _item = []
                                oSearchDetail.style.display = 'none'
                                $el('.searchBox').style.borderRadius = 10+'px'
                                htmlInsert({
                                    data:_item,
                                    dom:'',
                                    el:'.searchDetail'
                                })
                            }
                        })
                    },500);

                    // let save = [],
                    //     text = this.value || 'none',
                    //     isFine = false,
                    //     _item = [],
                    //     oSearchDetail = $el('.searchDetail')
                    // opt.map((item,_index)=>{
                    //     item.children.map((item,index)=>{
                    //         item.product_idx = index + (_index * opt?.[_index-1]?.children?.length || 0);
                    //         finStrOf(item.product_type,text) && (isFine = true) && (_item.push(item))
                    //     })
                    // })
                    // if(isFine){
                    //     oSearchDetail.style.display = 'block'
                    //     $el('.searchBox').style.borderRadius = '10px 10px 0 0'
                    //     console.log(_item);
                    //     htmlInsert({
                    //         data:_item,
                    //         dom:template().searchTpl,
                    //         el:'.searchDetail'
                    //     })
                    // }else{
                    //     oSearchDetail.style.display = 'none'
                    //     $el('.searchBox').style.borderRadius = 10+'px'
                    //     htmlInsert({
                    //         data:_item,
                    //         dom:'',
                    //         el:'.searchDetail'
                    //     })
                    // }
            },
        },
        homeEvent : {
            init() {
                let mySwiper = new Swiper('.swiper', {

                    fadeEffect: {
                        crossFade: true,
                    },
                    direction: 'horizontal', // 垂直切换选项
                    loop: true, // 循环模式选项
                    // 如果需要分页器
                    pagination: {
                        el: '.swiper-pagination',
                    },
                    // 如果需要前进后退按钮
                    navigation: {
                        nextEl: '.swiper-button-next',
                        prevEl: '.swiper-button-prev',
                    },
                })
                oHeadEvent.push({
                    node: [...$el('.swiper-pagination').children],
                    fnName: 'navClick',
                    args: [[...$el('.swiper-pagination').children],mySwiper],
                    type: 'click'
                })
                $el('.newRightHeadRight') && (()=>{
                    $elByClass('newRightHeadRight').map(item => {
                        item.getElementsByClassName('newButton')[0].className += 'newButtonActive'
                    })
                    $elByClass('newRightContentBox').map(() => {
                        newIdx.push(0)
                    })
                })()
                oHonour = $elByClass('aboutCertificate')
                honourSerInterval = setInterval(function (){
                    for (let node of oHonour) {
                        let children = [...node.children]
                        let isCross = parseInt(getComputedStyle(children[0])['right']) >= node.offsetWidth*1.8
                        children.map(item=>{
                            if(isCross){
                                item.style.right = -30+'px'
                            }else{
                                item.style.right =parseInt(getComputedStyle(children[0])['right']) + honourSpeed+'px'
                            }
                        })
                    }
                },10)
            },
            showButtonEvent(res) {
                let idx = $elByClass('showButton').indexOf(this),
                    aNode = $elByClass('showButton'),
                    tar = aNode[idx],
                    name = 'showActive'
                c(name,aNode,tar)
                c('showDetailBox2Active',$elByClass('showDetailBox2'),$elByClass('showDetailBox2')[idx])
                c('showItemBoxActive',$elByClass('showItemBox'),$elByClass('showItemBox')[idx])
                c('showItemActive',$elByClass('showItem'),$elByClass('showItemBox')[idx]?.children[0])
            },
            showLeftButtonEvent(res) {
                let n =  $el('.showItemBoxActive').children
                _sIdx = _sIdx <= 0 ? _sIdx = 0 : _sIdx - 1
                c('showItemActive',$elByClass('showItem'),$el('.showItemBoxActive').children[_sIdx])
                // _sIdx === 0 && (()=>{
                //     alert('暂无产品')
                // })()
            },
            showRightButtonEvent(res) {
                let n =  $el('.showItemBoxActive').children
                if(n.length>=2){
                    _sIdx = _sIdx >= n.length - 2 ? _sIdx = n.length - 2 : _sIdx + 1

                }else{
                    _sIdx = _sIdx >= n.length - 1 ? _sIdx = n.length - 1 : _sIdx + 1
                }
                c('showItemActive',$elByClass('showItem'),$el('.showItemBoxActive').children[_sIdx])
            },
            //nice mouse try 阻尼效果
            newRightContentMousedown(e) {
                //将目标子节点长度/2放入全局newOffsetArr中
                for (let i = 0; i < this.parentNode.children.length / 2; i++) {
                    let item = this.parentNode.children[i]
                    newOffsetArr.push(item.offsetWidth * i * 2) //这里创建阀值
                }
                //初始速度3
                let speed = 3,
                    //记录一开始触碰的x轴，兼容手机端
                    clickX = e.clientX || e.touches[0].clientX,
                    //将目标子节点伪数组扩展为数组
                    nodeList = [...this.parentNode.children]
                // 遍历子节点
                nodeList.map(item => {
                    // 首先清除子节点的transition
                    item.style.transition = ''
                    // 每个子节点绑定onmousemove
                    item.onmousemove = function (e) {
                        //当上一个位置大于这次的位置，即鼠标突然往左
                        if (lastPageX > e.pageX) {
                            nodeList.map(item => {
                                item.style.right = parseInt(getComputedStyle(this)['right']) + speed + 'px'
                            })
                            //当下一个位置大于这次的位置，即鼠标突然往右
                        } else if (lastPageX < e.pageX) {
                            nodeList.map(item => {
                                item.style.right = parseInt(getComputedStyle(this)['right']) - speed + 'px'
                            })
                            //鼠标禁止不动情况
                        } else {
                            nodeList.map(item => {
                                item.style.right = parseInt(getComputedStyle(this)['right']) + 'px'
                            })
                        }
                        // 最终位置
                        newOffX = clickX - e.pageX
                        //记录上一个位置
                        lastPageX = e.pageX
                    }
                    //手机端
                    item.ontouchmove = function (e) {
                        e.preventDefault()
                        if (lastPageX > e.touches[0].pageX) {
                            nodeList.map(item => {
                                item.style.right = parseInt(getComputedStyle(this)['right']) + speed + 'px'
                            })
                        } else if (lastPageX < e.touches[0].pageX) {
                            nodeList.map(item => {
                                item.style.right = parseInt(getComputedStyle(this)['right']) - speed + 'px'
                            })
                        } else {
                            nodeList.map(item => {
                                item.style.right = parseInt(getComputedStyle(this)['right']) + 'px'
                            })
                        }
                        newOffX = clickX - e.touches[0].pageX
                        lastPageX = e.touches[0].pageX
                    }
                })
            },
            //停止，当手指抬起来或者出界执行这个函数
            stopNewRightContentMousemove() {
                //向右是否超过当前宽度，是就下一个
                let isHalfRight = newOffX >= this.offsetWidth / 2 + 30,
                    //向左是否超过当前宽度，是就上一个
                    isHalfLeft = newOffX < -this.offsetWidth / 2 + 30,
                    // 保存index指向
                    _idx = Array.prototype.indexOf.call([...document.getElementsByClassName('newRightTop')], this.parentNode),
                    // 获取导航按钮
                    oNewButton = this.parentNode.getElementsByClassName('newButton')
                // 清空上一个导航按钮状态
                oNewButton[newIdx[_idx]].className = oNewButton[newIdx[_idx]].className.replaceAll('newButtonActive', ' ')
                // 越界判断
                if (isHalfRight) {
                    newIdx[_idx] = newIdx[_idx] >= newOffsetArr.length - 1 ? newIdx[_idx] = newOffsetArr.length - 1 : newIdx[_idx] + 1
                } else if (isHalfLeft) {
                    newIdx[_idx] = newIdx[_idx] <= 0 ? 0 : newIdx[_idx] - 1
                }
                // 目标映射导航按钮，即当前是第几个目标，导航按钮为第几个
                oNewButton[newIdx[_idx]].className += ' newButtonActive'
                //调度内容位移，清空状态
                lastPageX && (() => {
                    let nodeList = [...this.children]
                    nodeList.map(item => {
                        item.onmousemove = null
                        item.ontouchmove = null
                        item.style.right = newOffsetArr[newIdx[_idx]] + 'px'
                        item.style.transition = '0.5s'
                    })
                }).call(this)
                newOffX = 0
                newOffsetArr = []
            },
            // 导航按钮调度目标移动事件
            newButtonEvent() {
                //冗余判断是否存在导航按钮
                let tarElement = finStrOf(this.parentElement.className, 'new2ItemHeadTpl') === 0
                    ? this.parentElement.parentElement.nextElementSibling.children
                    : this.parentElement.parentElement.previousElementSibling.children,
                    // 获取下标
                    _idx = Array.prototype.indexOf.call($elByClass('newRightHeadRight'), this.parentElement),
                    idx = Array.prototype.indexOf.call([...$elByClass('newRightHeadRight')[_idx].children], this),
                    oNewButton = this.parentNode.getElementsByClassName('newButton')
                // 重复操作，将目标子节点长度/2放入全局newOffsetArr中
                for (let i = 0; i < tarElement.length / 2; i++) {
                    let item = tarElement[i]
                    newOffsetArr.push(item.offsetWidth * i * 2)
                }
                //清空上一个选中状态
                oNewButton[newIdx[_idx]].className = oNewButton[newIdx[_idx]].className.replaceAll('newButtonActive', ' ')
                // 更新内容状态
                newIdx[_idx] = idx;
                // 导航更新选中状态
                oNewButton[newIdx[_idx]].className += ' newButtonActive'
                //调度内容位移，清空状态
                ;(() => {
                    let nodeList = [...tarElement]
                    nodeList.map(item => {
                        item.onmousemove = null
                        item.ontouchmove = null
                        item.style.right = newOffsetArr[newIdx[_idx]] + 'px'
                        item.style.transition = '0.5s'
                    })
                }).call(this)
                newOffX = 0
                newOffsetArr = []
            },
            showDetailEvent(opt,e){
                let tar = e.target.parentElement,
                    idx = $elByClass('showDetailItem').indexOf(tar),
                    data = opt[sIdx].product[idx].product_id,
                    href = '/productInfo/'+data+'.html'
                hrefModule(href)

            },
            aboutCertificateEvent(){
                clearInterval(honourSerInterval)
            },
            _aboutCertificateEvent(){
                honourSerInterval = setInterval(function (){
                    for (let node of oHonour) {
                        let children = [...node.children]
                        let isCross = parseInt(getComputedStyle(children[0])['right']) >= node.offsetWidth*2.5
                        children.map(item=>{
                            if(isCross){
                                item.style.right = -30+'px'
                            }else{
                                item.style.right =parseInt(getComputedStyle(children[0])['right']) + honourSpeed+'px'
                            }
                        })
                    }
                },10)
            }
        },
        productEvent : {
            init() {
                $elByClass('productsTitle')[0] && (()=>{
                    setTimeout(()=>{
                        window.scrollTo(0,550);
                    })
                })()
            },
            productMenusItemEvent(opt){
                let idx = $elByClass('productMenusItem').indexOf(this)
                $elByClass('productMenusItem')[pIdx].className = $elByClass('productMenusItem')[sIdx].className.replaceAll('productMenusItemActive', ' ')
                this.className = this.className += ' productMenusItemActive'
                pIdx = idx
                let id = getProductId(opt,'productMenusItem',this)[0]
            },
            productPageEvent(){
                let isNum = isNaN(parseInt(this.innerText)),
                    pageNum = $elByClass('page').length-2,
                    pageEnd = ($el('.pageEnd')?.innerText) === undefined ? pageNum  : ~~$el('.pageEnd')?.innerText,
                    arr = []
                // pageIdx = Number($el('.pageActive').innerText)
                // console.log(pageIdx)
                console.log(pageEnd);
                for(let i = 0;i < pageEnd; i ++){
                    arr.push(i+1)
                }
                if(isNum){
                    $el('.pageActive') && (pageIdx = Number($el('.pageActive').innerText)-1)
                    if(finStrOf(this.getElementsByTagName('img')[0].src,'Left.png')){
                        pageIdx = pageIdx <= 0 ? pageIdx = 0 : pageIdx - 1
                    }else{
                        pageIdx = pageIdx >= pageEnd-1 ? pageIdx =  pageEnd-1: pageIdx + 1
                    }
                }else{
                    pageIdx = parseInt(this.innerText)-1
                }
                let l = location.href.split('/')
                l[location.href.split('/').length-2] = arr[pageIdx]
                location.href = l.join('/')
            },
            jumpEvent(){
                if($el('.jumpInput').value === '' || isNaN($el('.jumpInput').value) || (~~$el('.jumpInput').value) > ($el('.pageEnd')!==null ? (~~$el('.pageEnd').innerText) : $elByClass('page').length-2)){
                    alert('页数不能为空或不是数字或者超过页数')
                }else{
                    let l = location.href.split('/')
                    l[location.href.split('/').length-2] = ~~$el('.jumpInput').value
                    location.href = l.join('/')
                }
            }
        },
        productInfoEvent:{
            init(){
            },
            startProductCheck(){
                let pInfoHide = $el('.productDetail'),
                    x = null,
                    y = null,
                    tag = pInfoHide.getElementsByTagName('img')[0],
                    score = $el('.productInfoImgBox'),
                    tVal = score.clientWidth === 703  ? 553 : (score.clientWidth === 553 ? 403 : 282)
                ;
                (pInfoHide.style.display='block') && (()=>{
                    console.log(score.clientWidth);
                    $el('.productInfosHeader').onmousemove=function (e){
                        x = - e.pageX +tVal  +'px'
                        y = - e.offsetY /2 +'px'
                        tag.style.left = x
                        tag.style.top = y
                    }
                })()
            },
            stopProductCheck(){
                let pInfoHide = $el('.productDetail');
                (pInfoHide.style.display='none') && (()=>{
                    $el('.productInfosHeader').onmousemove=null
                })()
            }
        }
    }
export default {
    event : event[`${document.getElementsByTagName('body')[0].className}Event`],
    headEvent : event['headEvent']
}