import loading from './draw/loading.js'
import { basePage, leftScroll } from './draw/base.js'
import Content from './draw/content.js'
import Details from './draw/details.js'
import setPrice from './draw/price.js'

import ContactModal from './draw/ContactModal.js'
import ProductModal from './draw/ProductModal.js'
import SizeModal from './draw/SizeModal.js'
import PriceModal from './draw/PriceModal.js';
import HelpModal from './draw/HelpModal.js';
//import canvas from './libs/weapp-adapter.js'
import drawText from './util/drawText.js'

var url = 'https://t6.9026.com/api/album/cat?parent_id=0&store_id=1'//初始顶级目录url
var SLDsource = []//二级目录对象列表
var GoodsSource = []//商品对象列表
var GoodsDetail//商品详情
var flag1 = 0//通过flag1来判断现在处于哪一个顶级目录，然后利用flag1传参数获取该顶级目录下的二级目录信息
var flag2 = 0//通过flag1来判断现在处于哪一个二级目录，然后利用flag2传参数获取该顶级目录下的商品列表
var flag3 = 0//通过flag3来判断选择的是哪一个商品，然后获取它的的详情
var flag4 = 0//价格设置参考参数
var flag5 = 0//风格菜单选中状态

//定义画布
let context

//定义按钮区域
//一级目录按钮区域
import {
  ExitBtnArea,
  FLDsource,
  FLDbtnArea,
  FLDbtnAreaOffset,
  DetailbtnArea,
  ContentbtnArea,
  SLDArea,
  setpriceArea,
  TopArea,
  SearchButtonArea,
  SetPriceBtnArea,
  page,
  modalCloseBtnArea,
  ProductBuyModalBtnArea,
  ProductSizeModalBtnArea,
  triggerMoveDelta,
  homepage_page_size
} from './conf/data.js'
import drawImage from './util/drawImage.js';

let current_page = page.homepage
//二级目录按钮区域
let SLDbtnArea = []

let priceModal
let productBuyModal
let isTouchMoving = false

GameGlobal.isiPhoneX = false

let percent = 10

function init() {
  console.log('init')
  let res = wx.getSystemInfoSync()
  let mobileType = res.model

  let drawRatio = GameGlobal.drawRatio = 2
  canvas.width = res.screenWidth * drawRatio
  canvas.height = res.screenHeight * drawRatio

  context = canvas.getContext('2d')

  if (mobileType == 'iPhone X') {
    GameGlobal.isiPhoneX = true
    GameGlobal.offsetX = 35 * drawRatio
    context.translate(offsetX, 0)
  } else {
    GameGlobal.isiPhoneX = false
    GameGlobal.offsetX = 0
  }
  GameGlobal.screenWidth = res.screenWidth * drawRatio - GameGlobal.offsetX
  GameGlobal.screenHeight = res.screenHeight * drawRatio
  GameGlobal.font_size = 28
  console.log('screenWidth: ' + screenWidth + ', screenHeight: ' + screenHeight)

  // context.fillStyle = '#fff'
  // context.fillRect(0, 0, screenWidth, screenHeight)
  // wx.setPreferredFramesPerSecond(30)
  sleep(0).then(() => {

    loading(percent)
    showLoading()
  })
}

// wx.getSystemInfoSync({
//   success: function (res) {
//     init(res)
//   }
// })
//定义是否在详情界面状态
let Detailstatus = false
//是否隐藏了按钮
let Buttonstatus = false
//touchmove是否结束
let touchend = false
//是不是经销商
let isAgent = false
//是否到尺寸和安装图片转换界面
let attrFlag = false
//风格是否打开
let styleOpen = true
//当前是尺寸还是安装
let attrORupload = true
//是否在设置价格的界面
let setprice = false
//是否点了报价
let setClick = false
//是否在设置电话
let setMobile = false
//定义当前页数
let product_page_index = 0
//手指开始点击的坐标，用于判断手势滑动的左右上下方向
let startx = 0
let starty = 0
//agent_id
let agent_id = 0
let user_id = 0
//状态 1 只选择热销 2 只选择最新上市 3只选择一个风格 4 同时选择热销和最新上市 5同时选择热销和风格 6同时选择最新上市和风格 7全选 0全不选
let status = 0
let style = 0
let cat_id = 0
//输入的搜索内容
var KeyWord = ''
//厂家名字
var FactoryName = ''
//输入的价格
var pricein = 0.0
//输入的电话
var mobilein = '0'

let isLoading = true

function showLoading() {
  
  let interval = window.requestAnimationFrame(function () {
    // console.log('next frame')
    if (percent < 99.6 && isLoading) {
      percent += 0.2
      loading(percent)
      showLoading(percent)
    } else {
      isLoading = false;
      window.cancelAnimationFrame(interval)
      interval = null;
    }
  }, canvas)
}


//绘制函数
function reStart(dontReset) {
  console.log('reStartSuccess')//调用成功输出'reStartSuccess'
  // !dontReset && reset()//清空之前屏幕上的绘制内容，减少缓存占用，及信息重叠
  if (current_page === page.homepage || current_page === page.set_price) {
    //绘制两个侧边栏
    return basePage(context, KeyWord, isAgent, flag1, flag5, setprice).then(({height}) => {
      if (current_page === page.homepage) {
        new Content(GoodsSource, product_page_index, height).draw()
      } else {
        new setPrice(GoodsSource, product_page_index, height).draw()
      }
    })
    
  } else {//绘制详细内容
    try {
      let dt = new Details()
      //console.log('进入详情')
      let img = new Image()
      img.src = GoodsDetail.detail_pic
      if (Buttonstatus == false) {
        return dt.showDetails(context, GoodsDetail.detail_pic, GoodsDetail.name, GoodsDetail.price).catch(() => {
          wx.hideLoading()
          wx.showToast({
            title: '商品详情图片加载失败',
            icon: 'none',
            duration: 800
          })
          current_page = page.homepage
        })
      }
      else {
        return drawImage(context, GoodsDetail.detail_pic, 0, 0, screenWidth, screenHeight)
      }

    } catch (e) {
      console.log(e.message)
      Detailstatus = false
      wx.showToast({
        title: '暂无详情',
        icon: 'none'
      })
    }
  }
}

wx.onShow((e) => {
  if (!isLoading) {
    console.log('on show')
    sleep(500).then(() => reStart())
  } else {
    init()
  }
})
//触摸响应函数
wx.onTouchStart(((e) => {
  try {
    //e.preventDefault()
    var x = e.touches[0].clientX * 2 - offsetX
    var y = e.touches[0].clientY * 2
    startx = x
    starty = y
  } catch (evt) {
    console.log(evt.message)
  }

}))
wx.onTouchMove((e) =>{
  var endX = e.changedTouches[0].clientX * 2 - offsetX
  var endY = e.changedTouches[0].clientY * 2
  switch (current_page) {

    case page.product_buy_modal:
      handleProductBuyModalMoveEvents(startx, starty, endX, endY)
      startx = endX
      starty = endY
      break;
  }

})

//滑动响应函数
wx.onTouchEnd(((e) => {
  var endX = e.changedTouches[0].clientX * 2 - offsetX
  var endY = e.changedTouches[0].clientY * 2

  if (Math.abs(startx - endX) > 30 || Math.abs(starty - endY) > 30) {  //trigger move
    switch (current_page) {
      case page.homepage:
      case page.set_price:
        if (Math.abs(starty - endY) > triggerMoveDelta) {
          handleHomepageMoveEvents(startx, starty, endX, endY)
        }
        break;
      case page.product_homepage:
        if (Math.abs(startx - endX) > triggerMoveDelta) {
          handleProductHomepageMoveEvents(startx, starty, endX, endY)
        }
        break;
    }
  } else {
    switch (current_page) {
      case page.homepage:
        handleHomepageEvents(endX, endY)
        handelExitEvents(endX, endY)
        break;
      case page.product_homepage:
        handleProductHomepageEvents(endX, endY)
        handelExitEvents(endX, endY)
        break;
      case page.set_price:

        handleHomepageEvents(endX, endY)
        handelExitEvents(endX, endY)
        break;
      case page.set_price_modal:
        handleModalCloseModal(endX, endY)
        handleSetPriceModalEvents(endX, endY)
        break;
      case page.set_price_help_modal:
        handleModalCloseModal(endX, endY)
        break;
      case page.product_contact_modal:
        handleModalCloseModal(endX, endY)
        break;
      case page.product_buy_modal:
        handleModalCloseModal(endX, endY)
        handleProductBuyModalEvents(endX, endY)
        break;
      case page.product_size_modal:
        handleModalCloseModal(endX, endY)
        handleProductSizeModalEvents(endX, endY)
        break;
    }
  }
}))


/**
 * events handler
 * @param {*} x 
 * @param {*} y 
 */
function handleHomepageMoveEvents(startx, starty, endX, endY) {
  let deltaY = endY - starty
  if (startx < FLDbtnArea[0].startX && startx > SLDArea[0].endX ) {

    //翻页控制
    if (deltaY < 0) {
      if (product_page_index < Math.ceil(GoodsSource.length / homepage_page_size) - 1) {
        product_page_index++//点击翻页时页数+1
        console.log(`下一页：${product_page_index}`)
        reStart()
      }
    } else {
      if (product_page_index > 0) {
        product_page_index--//点击翻页时页数-1
        console.log(`上一页：${product_page_index}`)
        reStart()
      }
    }
  } else if (startx >= FLDbtnArea[0].startX) { //右侧菜单滑动
    let offsetY = FLDbtnAreaOffset.y - deltaY 
    if (offsetY < 0) {
      offsetY = 0
    }
    if (offsetY !== FLDbtnAreaOffset.y) {
      FLDbtnAreaOffset.y = offsetY
      leftScroll(context, flag1)
    }
  }
}

function handleProductHomepageMoveEvents(startx, starty, endX, endY) {
  let deltaX = endX - startx
  if (deltaX > 0) {//向右滑动
    Buttonstatus = false
    if (flag3 <= 0) {
      wx.showToast({
        title: '已经是第一个了',
        icon: 'none',
        duration: 800
      })
      flag3 = 0
      reStart(true)
    } else {
      flag3 = flag3 - 1
      console.log('flag3:' + flag3)
      getGoodsDetail(callback4, GoodsSource)
    }
  }
  if (deltaX < 0) {//向左滑动
    Buttonstatus = false
    if (flag3 == GoodsSource.length - 1) {
      wx.showToast({
        title: '已经是最后一个了',
        icon: 'none',
        duration: 800
      })
    } else if (flag3 < GoodsSource.length - 1) {
      flag3 = flag3 + 1
      console.log('flag3:' + flag3)
      getGoodsDetail(callback4, GoodsSource)
    }
  }
}

function handelExitEvents (x, y) {
  let d = ExitBtnArea[0]
  if (x >= d.startX && x <= d.endX && y >= d.startY && y <= d.endY) {
    console.log("exit")
    wx.exitMiniProgram({})
  }
}
function handleHomepageEvents(x, y) {
  //右边一级目录控制
  if (x >= FLDbtnArea[0].startX && y > TopArea[0].endY) {
    for (let i = 0, len = FLDbtnArea.length; i < len; i++) {
      if (x >= FLDbtnArea[i].startX
        && x <= FLDbtnArea[i].endX
        && y >= FLDbtnArea[i].startY
        && y <= FLDbtnArea[i].endY) {
        KeyWord = ''
        for (let i in FLDbtnArea) {//点击该按钮的时候，它变为活跃状态status=true，而其他所有按钮变为非活跃状态status=false
          FLDbtnArea[i].status = false
        }
        for (let i in ContentbtnArea) {//发生页面切换时所有商品详情均为不活跃状态
          ContentbtnArea[i].status = false
        }
        product_page_index = 0//发生页面切换时页数置0
        flag1 = i
        flag2 = 0//发生一级目录切换时，二级目录选中第一个
        flag5 = 0//风格重置为新品
        status = 2
        //FLDbtnArea[btn].status = true
        // current_page = page.homepage
        getGoodsSource(callback3, SLDsource)
      }
    }
  } else if (x <= SLDArea[0].endX && y > TopArea[0].endY) {
  //左边二级目录控制
    for (let i = 0; i < SLDArea.length; i++) {
      let d = SLDArea[i]
      KeyWord = ''
      if (d && x >= d.startX && x <= d.endX && y >= d.startY && y <= d.endY) {
        // current_page = page.homepage
        if (i === 0) { //新品上市
          product_page_index = 0
          flag2 = 0
          flag5 = 0
          status = 2
          getGoodsSource(callback3, SLDsource)
        } else if (i === 1) { //促销产品
          product_page_index = 0
          flag2 = 0
          flag5 = 1
          status = 1
          getGoodsSource(callback3, SLDsource)
        } else if (i === 2) { //风格
          product_page_index = 0
          flag2 = 0
          flag5 = 2
          status = 3
          getGoodsSource(callback3, SLDsource)
        } else if (isAgent == true && i === 4) { //报价
            if (current_page === page.set_price) { //退出报价
              setprice = false
              current_page = page.homepage
              reStart()
            } else {

              if (GoodsSource.length === 0) {
                wx.showToast({
                  title: '当前列表无商品',
                  icon: 'none',
                  duration: 500
                })
              } else {
                current_page = page.set_price
                setprice = true
                reStart()
              }
            }
        } else if (setprice && i === 5) { //报价帮助按钮
          current_page = page.set_price_help_modal
          new HelpModal(context).draw()
        }
      }
    }
  } else if (y <= TopArea[0].endY) {
    //搜索
    if (x >= SearchButtonArea[0].startX
      && x <= SearchButtonArea[0].endX
      && y >= SearchButtonArea[0].startY
      && y <= SearchButtonArea[0].endY) {
      //清除目录控制状态 
      flag5 = -1
      for (let i in FLDbtnArea) {
        FLDbtnArea[i].status = false
      }
      GoodsSource = []
      wx.showKeyboard({
        defaultValue: '',
        maxLength: 8,
        multiple: false,
        confirmHold: true,
        confirmType: 'done',
        success: function () {
          wx.onKeyboardConfirm(function handleKeyboardConfirm(res) {
            wx.offKeyboardConfirm(handleKeyboardConfirm)
            wx.hideKeyboard({})
            if (res.value && res.value !== KeyWord) {
              KeyWord = res.value
              search(KeyWord)
            }
          })
        }
      })
    }
  } else if (setprice) { //打开报价弹窗
    for (let con in setpriceArea) {
      if (x >= setpriceArea[con].startX
        && x <= setpriceArea[con].endX
        && y >= setpriceArea[con].startY
        && y <= setpriceArea[con].endY) {
        current_page = page.set_price_modal
        setClick = true
        con = parseInt(con)
        flag4 = (product_page_index * homepage_page_size) + con
        priceModal = new PriceModal(context, GoodsSource[flag4])
        priceModal.draw().then(() => {
          wx.showKeyboard({
            defaultValue: '',
            maxLength: 8,
            multiple: false,
            confirmHold: true,
            confirmType: 'done',
            success: function () {
              wx.onKeyboardConfirm(function handleKeyboardConfirm(res) {
                wx.offKeyboardConfirm(handleKeyboardConfirm)
                pricein = res.value
                priceModal.updatePrice(pricein)
                wx.hideKeyboard({})
              })
            }
          })
        })
        break;
      }
    }
  } else {  //进入商品详情
    for (let con in ContentbtnArea) {
      if (x >= ContentbtnArea[con].startX
        && x <= ContentbtnArea[con].endX
        && y >= ContentbtnArea[con].startY
        && y <= ContentbtnArea[con].endY) {
        current_page = page.product_homepage
        Detailstatus = true
        for (let x in ContentbtnArea) {
          ContentbtnArea[x].status = false
        }
        ContentbtnArea[con].status = true//用于判断是否进入详情
        con = parseInt(con)
        flag3 = (product_page_index * homepage_page_size) + con
        Buttonstatus = false
        getGoodsDetail(callback4, GoodsSource)
        break;
      }
    }
  }
}
function handleProductHomepageEvents(x, y) {
  if (x >= DetailbtnArea[5].endX && x <= DetailbtnArea[6].startX && y >= 90 && y <= DetailbtnArea[1].startY) {
     //隐藏或显示按钮
    if (Buttonstatus == true) {
      Buttonstatus = false
      reStart()
    } else {
      Buttonstatus = true
      reStart()
    }
  } else {
     for (let i = 0; i < DetailbtnArea.length; i++) {
       let d = DetailbtnArea[i]
       if (x >= d.startX && x <= d.endX && y >= d.startY && y <= d.endY) {
         if (i === 0) {  //返回
           Detailstatus = false
           current_page = page.homepage
           reStart() //重绘
         } else if (i === 1) {//分享好友
           wx.shareAppMessage({
             //title: '经销商id:' + agent_id,
             query: 'agent_id=' + agent_id + '&product_id=' + GoodsDetail.id
           })

         } else if (i === 2) {//联系商家
           current_page = page.product_contact_modal
           let tel = GoodsDetail.mobile
           new ContactModal(context, FactoryName, tel, GoodsDetail.addr).draw()
         } else if (i === 3) {//详情&购买

           wx.showLoading({
             title: 'loading',
           })
           current_page = page.product_buy_modal
           productBuyModal = new ProductModal(context, GoodsDetail)
           productBuyModal.draw().then(() => {
             wx.hideLoading()
           })
         } else if (i === 4) {//尺寸&安装

           wx.showLoading({
             title: 'loading',
           })
           current_page = page.product_size_modal
           new SizeModal(context, GoodsDetail, 'size').draw().then(() => {
             wx.hideLoading()
           })
         } else if (i === 5) {//上一张
           Buttonstatus = false
           if (flag3 <= 0) {
             wx.showToast({
               title: '已经是第一个了',
               icon: 'none',
               duration: 800
             })
             flag3 = 0
             reStart()
           }
           if (flag3 > 0) {
             flag3 = flag3 - 1
             console.log('flag3:' + flag3)
             getGoodsDetail(callback4, GoodsSource)
           }
         } else if (i === 6) {//下一张
           Buttonstatus = false
           if (flag3 == GoodsSource.length - 1) {
             wx.showToast({
               title: '已经是最后一个了',
               icon: 'none',
               duration: 800
             })
           }
           if (flag3 < GoodsSource.length - 1) {
             flag3 = flag3 + 1
             console.log('flag3:' + flag3)
             getGoodsDetail(callback4, GoodsSource)
           }
         }
       }
     }
  }
  
}
function handleModalCloseModal(x, y) {
  if (x >= modalCloseBtnArea[0].startX
    && x <= modalCloseBtnArea[0].endX
    && y >= modalCloseBtnArea[0].startY
    && y <= modalCloseBtnArea[0].endY) {
      if (current_page === page.set_price_help_modal || current_page === page.set_price_modal) {
        current_page = page.set_price
      } else {
        current_page = page.product_homepage
      }
      reStart()
    }
}
function handleSetPriceModalEvents(x, y) {
  // 点击价格，弹出键盘
  if (x >= SetPriceBtnArea[0].startX
    && x <= SetPriceBtnArea[0].endX
    && y >= SetPriceBtnArea[0].startY
    && y <= SetPriceBtnArea[0].endY) {
    wx.showKeyboard({
      defaultValue: '',
      maxLength: 8,
      multiple: false,
      confirmHold: true,
      confirmType: 'done',
      success: function () {
        wx.onKeyboardConfirm(function handleKeyboardConfirm(res) {
          wx.offKeyboardConfirm(handleKeyboardConfirm)
          pricein = res.value
          priceModal.updatePrice(pricein)
          wx.hideKeyboard({})
        })
      }
    })
  } else if (x >= SetPriceBtnArea[1].startX
    && x <= SetPriceBtnArea[1].endX
    && y >= SetPriceBtnArea[1].startY
    && y <= SetPriceBtnArea[1].endY) {
  // 保存价格
    wx.showLoading({
      title: 'loading',
    })
    let turl = 'https://t6.9026.com/api/album/set-price'
    wx.request({
      url: turl,
      data: {
        store_id: 1,
        agent_id: agent_id,
        type: 1,
        price: pricein,
        goods_id: GoodsSource[flag4].id
      },
      method: 'GET',
      success: function () {
        wx.hideLoading()
        wx.showToast({
          title: GoodsSource[flag4].name + '价格已更新为' + pricein,
          icon: 'none',
          duration: 1500
        })
        current_page = page.set_price
        getGoodsSource(callback3, SLDsource)
      }
    })
  }
}
function handleProductBuyModalMoveEvents(x1, y1, x2, y2) {
  let p
  if (!isTouchMoving) {
    isTouchMoving = true
    p = productBuyModal.scroll(x1, y1, x2, y2)
    if (p) {
      p.then(() => {
        isTouchMoving = false
      })
    } else {
      isTouchMoving = false
    }
  }
}
function handleProductBuyModalEvents(x, y) {
  let d = ProductBuyModalBtnArea[3]
  if (x >= d.startX && x <= d.endX && y >= d.startY && y <= d.endY) {
    let is_fav = GoodsDetail.is_favorite
    let url
    if (is_fav) {
      url = 'https://t6.9026.com/api/album/favorite_del'
    } else {
      url = 'https://t6.9026.com/api/album/add_favorite'
    }
    wx.showLoading({
      title: 'loading',
    })
    wx.request({
      url: url,  //这里''里面填写你的服务器API接口的路径    
      data: {
        store_id: 1,
        user_id: 1,
        product_id: GoodsDetail.id
      },  //这里是可以填写服务器需要的参数    
      method: 'GET', // 声明GET请求    
      // header: {}, // 设置请求的 header，GET请求可以不填    
      success: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          GoodsDetail.is_favorite = is_fav ? '0' : '1'
          productBuyModal.fav()
          wx.showToast({
            title: '收藏成功',
            icon: 'none',
            duration: 500
          })
        } else {
          wx.showToast({
            title: '收藏失败',
            icon: 'none',
            duration: 500
          })
        }
        //console.log(res.statusCode)
      },
      fail: function(error) {
        console.error('收藏失败', error)
        wx.showToast({
          title: '收藏失败',
          icon: 'none',
          duration: 500
        })
      }
    });
  }
}
function handleProductSizeModalEvents(x, y) {
  let d0 = ProductSizeModalBtnArea[0]
  let d1 = ProductSizeModalBtnArea[1]
  let d2 = ProductSizeModalBtnArea[2]
  if (x >= d0.startX && x <= d0.endX && y >= d0.startY && y <= d0.endY) {
    reStart().then(() => {

      new SizeModal(context, GoodsDetail, 'size').draw()
    })
  } else if (x >= d1.startX && x <= d1.endX && y >= d1.startY && y <= d1.endY) {
    reStart().then(() => {

      new SizeModal(context, GoodsDetail, 'pic').draw()
    })
  } else if (x >= d2.startX && x <= d2.endX && y >= d2.startY && y <= d2.endY) {
    reStart().then(() => {

      new SizeModal(context, GoodsDetail, 'video').draw()
    })
  }
}



//清除之前绘制内容
function reset() {
  // context.clearRect(0, 0, screenWidth, screenHeight)
  context.fillStyle = "#fff"
  context.fillRect(0, 0, screenWidth, screenHeight)
}
//获取顶级目录列表
function getFLDsource(callback1, url) {
  try {
    wx.request({
      url: url,  //这里''里面填写你的服务器API接口的路径    
      data: {
      },  //这里是可以填写服务器需要的参数    
      method: 'GET', // 声明GET请求    
      // header: {}, // 设置请求的 header，GET请求可以不填    
      success: function (res) {
        if (res.statusCode == 200) {
          let test = JSON.stringify(res.data)
          let tet = JSON.parse(test)
          FLDsource.splice(0, FLDsource.length)
          for (let i in tet.data.cats) {
            FLDsource.push(tet.data.cats[i])
          }
          callback1(FLDsource)//导出顶级目录列表
        }
        //console.log(res.statusCode)
      }
    });
  } catch (e) {
    wx.showToast({
      title: '加载异常',
      icon: 'none',
      duration: 500
    })
  }

}
//在回调函数中通过顶级目录个数获得它的按钮区域
function callback1(res) {

  percent < 70 && (percent = 70)
  getSLDsource(callback2, FLDsource)//获取二级目录信息
}
//根据获取第一个请求函数得到的顶级目录信息来获取二级目录信息
function getSLDsource(callback2, FLDsource) {
  //  通过flag1来判断现在处于哪一个顶级目录，然后利用flag1传参数获取该顶级目录下的二级目录信息
  let u = 'https://t6.9026.com/api/album/style?store_id=1'
  //console.log(u)
  try {
    wx.request({
      url: u,
      data: {
      },
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 200) {
          let test = JSON.stringify(res.data)
          let tet = JSON.parse(test)
          SLDsource.splice(0, SLDsource.length)//每次调用重新填充数据的时候清空之前数据
          for (let i in tet.data.style) {
            SLDsource.push(tet.data.style[i])
          }
          callback2(SLDsource)//导出二级目录列表
        }
        //  console.log(res.statusCode)
      }
    })
  } catch (e) {
    wx.showToast({
      title: '加载异常',
      icon: 'none',
      duration: 500
    })
  }
}
//通过二级目录列表的长度来得到它的按钮区域列表
function callback2(res) {

  percent < 80 && (percent = 80)
  SLDbtnArea.splice(0, SLDbtnArea.length)//每次调用重新填充数据的时候清空之前数据
  for (let i = 0; i < res.length; i++) {
    let s = false
    if (i == flag2) s = true
    let SLDobj = new Object()
      SLDobj.startX = 0
    SLDobj.startY = 50 * (i + 4) + 70
      SLDobj.endX = 40
    SLDobj.endY = 50 * (i + 5) + 70
    SLDobj.status = s
    SLDbtnArea.push(SLDobj)
  }
  //console.log(SLDsource)
  // reStart()
  getGoodsSource(callback3, SLDsource)
}
function getGoodsSource(callback3, SLDsource) {
  cat_id = FLDsource[flag1].id
  if (SLDsource) {
    style = SLDsource[flag2].id
  }
  let u = 'https://t6.9026.com/api/album/goods' + '?store_id=1&cat_id=' + cat_id + '&status=' + status + '&style=' + style
  wx.showLoading({
    title: 'loading',
  })
  wx.request({
    url: u,
    data: {
    },
    method: 'GET',
    success: function (res) {
      try {
        wx.hideLoading()
        let test = JSON.stringify(res.data)
        let tet = JSON.parse(test)
        FactoryName = tet.data.name
        GoodsSource.splice(0, GoodsSource.length)//每次调用重新填充数据的时候清空之前数据
        for (let i in tet.data.goods) {
          GoodsSource.push(tet.data.goods[i])
        }
        if (GoodsSource.length === 0) {
          wx.showToast({
            title: '当前列表无商品',
            icon: 'none',
            duration: 500
          })
        }
      } catch (e) {
        wx.showToast({
          title: '请求异常',
          icon: 'none',
          duration: 800
        })
      }
      callback3(GoodsSource)//导出商品列表
      //console.log(res.statusCode)
    }
  })

}
function callback3(res) {
  percent < 100 && (percent = 100)
  console.log(GoodsSource)

  isLoading = false

  reStart().then(() => {
    let launchOption = wx.getLaunchOptionsSync()
    if (typeof launchOption.query.product_id !== 'undefined') {
      console.log("by share", launchOption)
      current_page = page.product_homepage
      getGoodsDetail(callback4, launchOption.query.prouct_id)
    }
  })
}
function getGoodsDetail(callback4, GoodsSource) {
  //如果所点击的区域没有商品展示，那么不进入详情界面
  let ur = 'https://t6.9026.com/api/album/goods-detail'
  wx.showLoading({
    title: 'loading',
  })

  wx.request({
    url: ur,
    data: {
      store_id: 1,
      agent_id: agent_id,
      goods_id: Array.isArray(GoodsSource) ? GoodsSource[flag3].id : GoodsSource,
      user_id: user_id
    },
    method: 'GET',
    success: function (res) {
      try {
        GoodsDetail = {}
        let test = JSON.stringify(res.data)
        let tet = JSON.parse(test)
        GoodsDetail = tet.data.goods
      } catch (e) {
        Detailstatus = false
        wx.showToast({
          title: '暂无商品详情',
          icon: 'none',
          duration: 800
        })
      }
      callback4(GoodsDetail)//导出商品列表
    },
    fail: function(error) {
      console.error(error)
      Detailstatus = false
    }
  })
}
function callback4(res) {
  if (Detailstatus == true)//如果没获取到详情，说明所点击区域没有元素，不进行重绘
    reStart(true)
}

function UserLogin() {
  
  // wx.showLoading({
  //   title: '正在登录',
  // })
  wx.login({
    success: function (res) {
      let code = res.code
      console.log(code)
      percent < 20 && (percent = 20)
      wx.getUserInfo({
        success: function (res) {
          percent < 30 && (percent = 30)
          let encrypted_data = res.encryptedData
          let iv = res.iv
          let tx = res.userInfo.avatarUrl
          let nn = res.userInfo.nickName
          console.log('getUserInfo success')
          let params = {
            code: code,
            avatar: tx,
            nickName: nn,
            iv: iv,
            store_id: 1
          }
          // wx.showToast({
          //   title: JSON.stringify(params),
          //   icon: 'none',
          //   duration: 5000
          // })

          wx.request({
            url: 'https://t6.9026.com/api/album/xyx_login',
            method: 'POST',
            data: params,
            success: function (res) {
              percent < 60 && (percent = 60)
              let data = res.data.data
              let is_agent = data.is_agent
              if (is_agent == 1) {
                isAgent = true
                agent_id = data.agent_id
                user_id = data.user_id
                wx.hideLoading()
                getFLDsource(callback1, url)
              }
              else {
                isAgent = false
                var test = wx.getLaunchOptionsSync()
                console.log(test)
                agent_id = test.query.agent_id
                user_id = data.user_id
                if (agent_id == undefined)
                  agent_id = 0
                console.log(agent_id)
                wx.hideLoading()
                getFLDsource(callback1, url)
              }
            }, fail: function () {
              isLoading = false
              // drawText(context, code, 0, 0, '', 28, '#000')
              // drawText(context, tx, 0, font_size, '', 28, '#000')
              // drawText(context, nn, 0, font_size * 2, '', 28, '#000')
              // drawText(context, iv, 0, font_size * 3, '', 28, '#000')
              wx.showToast({
                title: '系统登录失败',
                icon: 'none',
                duration: 800
              })

            }
          })
        }, fail: function(){
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'none',
            duration: 800
          })
        }
      })
    }, fail: function () {
      wx.showToast({
        title: '微信登录失败',
        icon: 'none',
        duration: 800
      })
    }
  })
}
function search(KeyWord) {
  wx.request({
    url: 'https://t6.9026.com/api/album/goods',
    data: {
      store_id: 1,
      cat_id: cat_id,
      status: status,
      keywords: KeyWord
    },
    method: 'GET',
    success: function (res) {
      try {
        let test = JSON.stringify(res.data)
        let tet = JSON.parse(test)
        GoodsSource.splice(0, GoodsSource.length)//每次调用重新填充数据的时候清空之前数据
        wx.showToast({
          title: '这次共搜索到' + tet.data.goods.length + '个产品',
          icon: 'none',
          duration: 800
        })
        for (let i in tet.data.goods) {
          GoodsSource.push(tet.data.goods[i])
        }
      } catch (e) {
        wx.showToast({
          title: '请求异常',
          icon: 'none',
          duration: 800
        })
      }
      callback3(GoodsSource)//导出商品列表
    }
  })
}
function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}
/*
主函数
*/
export default class Main {
  constructor() {
    UserLogin()
  }
}