import {
  get,
  post
} from '../../utils/http'
import {
  PROJECT_TYPE
} from '../../utils/global'
var WxParse = require('../../components/local/wxParse/wxParse.js')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tempTime: null,
    visible2: false,
    deviceList: [],
    projectData: null,
    currentDevice: 0,
    currentChangeDevice: null,
    currentChangeTime: null,
    source: 'project',
    sourceType: 1,
    sourceId: 0,
    storeId: 0,
    topBannerCurrentSwiper: 0,
    navBarTitles: {
      project: '项目详情',
      product: '套餐详情',
      goods: '产品详情',
      cardgoods: '产品详情',
      secondaryCard: '次卡详情'
    },
    // 下面是选择项目的操作
    showProducePup: false,
    selectProductData: {},
    selectProductIndex: '',
    selectProductCar: [],
    onCloseCar: false,
    showMoney: 0.0,
    toSelectProduct: {},
    shareInfo: '', //分享配置内容
    isNewUser: 0, //结果，1是新用户，0不是新用户
    isSkinPlan: false, //是否从测肤推荐跳转过来
    isTestSkin: false, //是否是从肤质推荐跳转过来的
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options')
    // 扫二维码进入的截取出id
    if (options.q) {
      let ticket = decodeURIComponent(options.q)
      console.log(ticket);
      var reg = new RegExp("(^|\\?|&)" + 'source' + "=([^&]*)(\\s|&|$)", "i");
      var reg1 = new RegExp("(^|\\?|&)" + 'id' + "=([^&]*)(\\s|&|$)", "i");
      var reg2 = new RegExp("(^|\\?|&)" + 'shareUserId' + "=([^&]*)(\\s|&|$)", "i");
      if (reg.test(ticket)) {
        options.source = unescape(RegExp.$2.replace(/\+/g, " "));
      };
      if (reg1.test(ticket)) {
        options.id = unescape(RegExp.$2.replace(/\+/g, " "));
      };
      if (reg2.test(ticket)) {
        app.globalData.shareUserId = unescape(RegExp.$2.replace(/\+/g, " "));
        console.log(unescape(RegExp.$2.replace(/\+/g, " ")), 'options.q');
      };
      app.globalData.isH5 = true //赋值是否从h5商城进入的
    }
    let source = options.source || 'project'
    let sourceId = options.project_id || options.id
    let sourceType = PROJECT_TYPE[source] || 1
    let isSkinPlan = false
    if (options.isSkinPlan=='true') {
      isSkinPlan = true
    }
    let isTestSkin = false
    if (options.isTestSkin=='true') {
      isTestSkin = true
    }
    if (options.shareUserId) {
      app.globalData.shareUserId = options.shareUserId //赋值全局分享人ID
    }
    console.log(app.globalData.shareUserId);
    wx.setNavigationBarTitle({
      title: this.data.navBarTitles[source]
    })
    let storeId =
      options.store_id ||
      getApp().globalData.storeData.id ||
      wx.getStorageSync('store_id')
    this.setData({
      source,
      sourceId,
      sourceType,
      storeId,
      isSkinPlan,
      isTestSkin
    }, () => {

    })
    // 绑定分享参数
    wx.onCopyUrl(() => {
      let userID = wx.getStorageSync('userInfo')
      return {
        query: `project_id=${this.data.sourceId}&source=${this.data.source}&store_id=${wx.getStorageSync('store_id')}&shareUserId=${userID.uid}`
      }
    })
    // 获取分享配置消息
    this.getShareInfo()
    // 检查是否是新用户
    this.checkNewUser()
    // 测肤推荐方案埋点记录
    this.skinPlanRecord()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('store_id')) {
      this.getProjectInfo(this.data.sourceId, wx.getStorageSync('store_id'))
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 测肤推荐方案埋点记录
   */
  skinPlanRecord() {
    let url = this.data.isTestSkin ? '/v2/api/order/skin' : 'v2/api/order/recommend'
    if (this.data.isTestSkin || this.data.isSkinPlan) {
      get(url, {
        type: 1
      }, (res) => {})
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log(this.data.sourceId, 'this.data.sourceId')
    let userID = wx.getStorageSync('userInfo')
    return {
      title: this.data.shareInfo.share_text,
      imageUrl: this.data.shareInfo.share_image,
      path: `pages/projectDetail/projectDetail?project_id=${this.data.sourceId}&source=${this.data.source}&store_id=${wx.getStorageSync('store_id')}&shareUserId=${userID.uid}`, // 他人通过卡片进入小程序的路径，可以在后面拼接URL的形式带参数
    };
  },

  isShow() {},
  // 获取分享图片文案
  getShareInfo() {
    get('v2/api/share/info', {
      id: this.data.sourceId,
      type: this.data.source == 'secondaryCard' ? 'card' : this.data.source
    }, res => {
      this.setData({
        shareInfo: res.data
      })
    })
  },
  /**
   * swiper滚动事件
   * @param {*} e
   */
  swiperChange: function (e) {
    this.setData({
      topBannerCurrentSwiper: e.detail.current
    })
  },

  /**
   * 去支付
   */
  onPay() {
    // wx.requestPayment({
    //   timeStamp: '',
    //   nonceStr: '',
    //   package: '',
    //   signType: 'MD5',
    //   paySign: '',
    //   success(res) {},
    //   fail(res) {}
    // })
  },

  /**
   * 弹框状态
   */
  onPopupState(e, key, value) {
    if (e) {
      key = e.currentTarget.dataset.key
      value = e.currentTarget.dataset.value
    }
    this.setData({
      [key]: value
    })
  },

  /**
   * 选择设备
   */
  onDeviceChange(e) {
    if (this.data.deviceList[e.currentTarget.dataset.index].status == 0) {
      return
    }
    this.setData({
      currentDevice: e.currentTarget.dataset.index
    })
  },
  onConfirmDevice() {
    let currentChangeDevice = this.data.deviceList[this.data.currentDevice]
    if (currentChangeDevice.status == 0) {
      wx.showToast({
        title: '当前设备已被预约',
        icon: 'none'
      })
      return
    }
    this.setData({
      currentChangeDevice
    })
    this.onPopupState(null, 'visible2', false)
  },
  onConfirmDate() {
    // if(this.data.currentChangeTime.status == 0) {
    //   wx.showToast({
    //     title: '当前设备已被预约',
    //     icon: 'none'
    //   })
    //   return
    // }
    this.setData({
      currentChangeTime: this.data.tempTime
    })
    this.onPopupState(null, 'visible', false)
    this.getProjectDevice(this.data.currentChangeTime)
  },

  /**
   * 选择时间
   */
  onVisibleChange(e) {
    console.log(e)
    this.setData({
      // currentChangeTime: e.detail
      tempTime: e.detail
    })
  },

  /**
   * 获取详情页数据
   */
  getProjectInfo(product_id, store_id) {
    get(
      this.data.source === 'secondaryCard' ? 'v2/api/card/info' : 'api/product/info', this.data.source === 'secondaryCard' ? {
        id: this.data.sourceId,
        store_id
      } : {
        store_id,
        product_id,
        type: this.data.sourceType
      },
      (res) => {
        let content = this.removeCss(res.data.content)
        res.data.content = this.removeCss(res.data.content)
        WxParse.wxParse('article', 'html', content, this, 5)
        res.data.new_price = Number(res.data.new_price)
        this.setData({
          projectData: res.data
        })
      }
    )
  },

  /**
   * 获取设备
   */
  getProjectDevice(time) {
    let {
      currentChangeTime
    } = this.data
    get(
      'api/project/device', {
        project_id: this.data.projectData.id,
        store_id: this.data.projectData.store_id,
        order_day: currentChangeTime ? currentChangeTime.order_day : '',
        order_time_id: currentChangeTime ?
          currentChangeTime.time_id : currentChangeTime
      },
      (res) => {
        this.setData({
            deviceList: res.data
          },
          () => {
            this.onPopupState(null, 'visible2', true)
          }
        )
      }
    )
  },

  /**
   * 去除富文本图片默认样式
   */
  removeCss(content) {
    let reg = /(style|class)="[^"]+"/gi
    let img = /<img[^>]+>/gi
    let res
    if (img.test(content)) {
      res = content.match(img)
      for (let i = 0; i < res.length; i++) {
        content = content.replace(res[i], res[i].replace(reg, ''))
      }
    }
    // (/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
    return content.replace(/\<img/gi, '<img class="richImg"  ')
  },

  // 这里是选择项目
  showProjectSelect() {
    let toSelectProduct = {}
    toSelectProduct.desc = this.data.projectData.tags
    toSelectProduct.cover_url = this.data.projectData.banner_urls[0]
    toSelectProduct.name = this.data.projectData.name
    toSelectProduct.use_time = this.data.projectData.use_time
    toSelectProduct.price = this.data.projectData.price
    toSelectProduct.new_price = this.data.projectData.new_price
    toSelectProduct.id = this.data.projectData.id
    console.log(toSelectProduct, 'toSelectProduct2222');
    this.setData({
      toSelectProduct: toSelectProduct,
      selectProductIndex: '空',
      showProducePup: true
    })
    this.productV2(toSelectProduct.id)
  },

  /**
   * 获取升级产品列表
   * /api/store/info
   */
  productV2(id) {
    get(
      'v2/api/product/product', {
        id: id,
        store_id: this.data.storeId
      },
      (res) => {
        this.setData({
          selectProductData: res.data
        })
        console.log(res)
      }
    )
  },

  selectProduct(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectProductIndex: index
    })
  },

  // 关闭产品包
  onClosePay() {
    this.setData({
      showProducePup: false
    })
  },

  submit_bottom: function () {
    let toSelectProducts = this.data.toSelectProduct
    if (this.data.selectProductIndex == '空') {
      toSelectProducts.selectMaterial = ''
    } else {
      toSelectProducts.selectMaterial = this.data.selectProductData.upgrade[this.data.selectProductIndex]
    }
    console.log(toSelectProducts)
    this.setData({
      showProducePup: false,
      toSelectProduct: toSelectProducts
    })

    this.setSubmitCar()
  },

  setSubmitCar() {
    let currentPage = getCurrentPages(); // 获取当前页的数据，
    let previousPage = currentPage[currentPage.length - 2]; // 上一页的数据，
    console.log(previousPage);
    let selectProductCarData = !previousPage ? '' : previousPage.data.selectProductCar
    if (!selectProductCarData) {
      let toSelectProduct = wx.getStorageSync('toSelectProduct')
      if (!toSelectProduct) {
        toSelectProduct = []
      } else {
        toSelectProduct = JSON.parse(toSelectProduct)
      }
      toSelectProduct.push(this.data.toSelectProduct)
      wx.setStorageSync('toSelectProduct', JSON.stringify(toSelectProduct))
      wx.showToast({
        title: '成功加入购物车!',
        icon: 'none'
      })
      setTimeout(() => {
        // 测肤 推荐方案埋点
        if (this.data.isTestSkin) {
          app.globalData.isTestSkin = true
        } else if (this.data.isSkinPlan) {
          app.globalData.isSkinPlan = true
        }
        wx.switchTab({
          url: '/pages/orderBy/orderBy?cat_type=3',
        })
      }, 1000)
      return
    }

    for (let i = 0; i < selectProductCarData.length; i++) {
      if (selectProductCarData[i].id == this.data.toSelectProduct.id) {
        wx.showToast({
          title: '单项目只能选一次!',
          icon: "none"
        })
        return
      }
    }
    selectProductCarData.push(this.data.toSelectProduct)
    previousPage.setData({ //对上一个页面data中的参数进行赋值（上一个页面的数据是在当前页面进行赋值的），就变相实现了向上一个页面传值
      selectProductCar: selectProductCarData
    })

    previousPage.showCarMoney()
    wx.showToast({
      title: '成功加入购物车!',
      icon: 'none'
    })

    setTimeout(() => {
      wx.navigateBack()
    }, 1000)

    // wx.navigateBack({})
  },




  /**
   * 提交订单
   */
  addOrder() {
    if (this.data.source == 'goods' && this.data.projectData.num == 0) {
      wx.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }
    if (this.data.source == 'goods') {
      wx.navigateTo({
        url: `/pages/goodsOrderConfirm/goodsOrderConfirm?storeId=${this.data.storeId}&productId=${this.data.projectData.id}&isShow=false&source=${this.data.source}&isDirectOrder=true&goods_ids=${this.data.projectData.id}&type=2`,
      })
      return
    }

    if (this.data.source == 'project') {
      this.showProjectSelect()
      return
    }
    if (!wx.getStorageSync('token')) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
      return
    }
    let {
      currentChangeDevice,
      currentChangeTime,
      projectData,
      source
    } =
    this.data
    let _projectData = Object.assign({}, projectData)
    delete _projectData.content
    let url = `/pages/reserveProject/reserveProject?source=${
      this.data.source
    }&projectData=${encodeURIComponent(JSON.stringify(_projectData))}`
    if (source == 'product') {
      url = `/pages/reserveProduct/reserveProduct?source=${
        this.data.source
      }&productData=${encodeURIComponent(JSON.stringify(_projectData))}`
    } else if (['goods', 'cardgoods', 'secondaryCard'].indexOf(source) > -1) {
      // 美妆产品、项目卡券产品 直接跳转到确认订单
      url = `/pages/orderConfirm/orderConfirm?source=${source}&data=${JSON.stringify(
        _projectData
      )}&deviceData={}&timeData={}&storeId=${this.data.storeId}`
    }
    wx.navigateTo({
      url: url
    })
  },
  // 美妆产品加入购物车
  addGoods(type) {
    if (type == 'shopping') {
      wx.navigateTo({
        url: `/pages/goodsOrderConfirm/goodsOrderConfirm?storeId=${this.data.storeId}&productId=${this.data.projectData.id}&isShow=true&source=${this.data.source}`,
      })
    } else {
      let params = {
        goods_id: this.data.sourceId,
        store_id: this.data.storeId,
        source: app.globalData.isH5 ? 'h5' : '',
        share_user_id: app.globalData.shareUserId || '',
      }
      post('v2/api/car/add', params, (res) => {
        if (res.code == 200) {
          wx.showToast({
            title: '成功加入购物车!',
            icon: 'none'
          })
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/shoppingMall/shoppingMall?cat_type=3',
            })
          }, 1000);
        }
      })
    }



    // let params = {
    //   goods_id: this.data.sourceId,
    //   store_id: this.data.storeId
    // }
    // post('v2/api/car/add', params, (res) => {
    //   if (res.code == 200) {
    //     if (type == 'shopping') {
    //       wx.navigateTo({
    //         url: `/pages/goodsOrderConfirm/goodsOrderConfirm?storeId=${this.data.storeId}&productId=${this.data.projectData.id}&isShow=true&source=${this.data.source}`,
    //       })
    //     } else {
    //       wx.showToast({
    //         title: '成功加入购物车!',
    //         icon: 'none'
    //       })
    //       setTimeout(() => {
    //         wx.switchTab({
    //           url: '/pages/orderBy/orderBy?cat_type=3',
    //         })
    //       }, 1000)
    //     }
    //   }
    // })
  },
  // 检查是否是新用户
  checkNewUser() {
    get('v2/api/order/check_new_user', {}, (res => {
      // 结果，1是新用户，0不是新用户
      this.setData({
        isNewUser: res.data.status
      })
    }))
  }
})