import {
  conversion,
  setShoppingCart,
  getShoppingCart,
  _GLOBAL_UI_DATA_KEY
} from '../../../utils/week-index'
import { fhPostWxMsg } from '../../../api/notice/notice'
import { _SUCCESS, _FAIL } from '../../../utils/subscribe-message'
import { submitOrder } from './_utils'
import { fhGetReduceNurseDelivery } from '../../../api/actives/index'
import { fhGetMeals } from '../../../api/week/index'
const baseUrl = require('../../../api/index.js').config
const {
  fhGetCartAll,
  fhDeleteCartAll
} = require('../../../api/cart/index')
const order = require('../../../api/order.js')
const member = require('../../../api/member.js')
const masses = require('../../../api/masses.js')
const { getHospitalInfo } = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    preventTouchMove: true,
    orderlist: [],
    tableIndex: 0,
    tablelist: ['无需餐具', 1, 2, 3, 4, 5, 6, 7, 8],
    tableunselect: ['未选择'],
    tableselct: [
      {
        num: '无需餐具',
        cover: false
      },
      {
        num: 1,
        cover: false
      },
      {
        num: 2,
        cover: false
      },
      {
        num: 3,
        cover: false
      },
      {
        num: 4,
        cover: false
      },
      {
        num: 5,
        cover: false
      },
      {
        num: 6,
        cover: false
      },
      {
        num: 7,
        cover: false
      },
      {
        num: 8,
        cover: false
      }
    ],
    showcover: false,
    coverindex: 0,
    tableflag: false,
    remarker: '',
    orderid: '',
    storeid: '',
    currentflag: 1,
    latitude: '',
    longitude: '',
    currentLo: null,
    currentLa: null,
    markers: null,
    scale: 16,
    // integral: false,
    showcoupon: false,
    couponflag: 1,
    isScroll: true,
    productIds: '',
    specIds: '',
    // couponlist:[],
    canNotUseCoupons: [],
    canUseCoupons: [],
    couponnum: '',
    couponid: '',
    couponindex: '',
    usePoint: false,

    // 时间选择
    timeIndex: 0,
    timeOne: [],
    timeTwo: [],
    reserveName: '',
    reservePhone: '',
    addressid: '',
    address: [],
    // 秒杀
    seckillflag: false,
    couponnumber: '',
    payflag: false,
    shareCode: '',
    //环保
    huanbaoflag: true,
    // 自提柜
    normalflag: true,
    mentionflag: false,
    showMention: false,
    mentionid: '',
    mentionindex: '',
    mentiondata: false,
    trueindex: 'fail',
    // 外卖禁用
    takeAwayStatus: '',
    // 餐次时间
    showMeals: false,
    mealList: [],
    // 日期列表
    showDates: false,
    dateList: [],
    allFoodList: [],
    currFoodList: [],
    activeDateKey: 0,
    dayNum: 0,
    mealNum: 0,
    foodNum: 0,
    // 预订单
    advancedayindex: 0,
    advancetimeindex: 0,
    advancelist: [],
    selectadvance: 0,
    truedayindex: 0,
    scheduleflag: false,
    scheduletime: '',
    isclose: false,
    appointexpect: '',
    //选择餐具的积分规则
    ruleflag: false,
    //打烊下预订单
    storeType: '',
    // 备注
    // remarkterm:''
    // 来源
    from: null,
    // 活动的额外信息
    extraInfo: {},
    // 埋点信息
    trackInfo: {},
    // 加载中
    loading: true,
    // 是否需要护工帮助
    needHelp: false,
    // 护工推单规则
    pushSingleRule: `<p>1、优选推单给患者预约护工；</p>
    <p>2、如果患者没有预约护工，系统择优推送同病房患者预约护工；</p>
    <p>3、如果同病房患者没有预约护工，系统择优推送同科室患者预约护工；</p>
    <p>4、如果同科室病房患者没有预约护工，系统择优推送同住院楼患者预约的护工；</p>
    <p>5、以上条件达不到，系统会呼叫平台其他闲置护工进行接单；</p>`,
    nurseDelivery: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMeals()
    let { from, extraInfo = {} } = options

    this.hospitalIdInfo = getHospitalInfo()
    extraInfo = {
      ...extraInfo,
      ...this.hospitalIdInfo
    }

    wx.setStorageSync('selectCouponlist', [])
    var that = this
    if (options.addressflag == 1) {
      that.setData({
        storeid: options.storeid,
        currentflag: options.currentflag || that.data.currentflag
      })
      wx.setStorageSync('storeid', that.data.storeid)
      wx.setStorageSync('currentflag', that.data.currentflag)
      wx.setStorageSync('addressid', '')
    }
    var cflag = wx.getStorageSync('currentflag')

    const storeid = wx.getStorageSync('storeid')
    const merchantId = wx.getStorageSync('merchantid')

    that.setData({
      addressid: options.addressid,
      currentflag: cflag,
      storeCartKey: `cart_${merchantId}_${storeid}`,
      from,
      extraInfo:
        typeof extraInfo === 'string' ? JSON.parse(extraInfo) : extraInfo
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    if (this.payFlagShow) return

    await this.getReduceNurseDelivery()

    const { extraInfo = {} } = this.data
    const groupFlag = this.computedActivityGroup()

    var that = this
    const otherShare = wx.getStorageSync('otherShare')
    this.setData({
      shareCode: otherShare
    })

    let memberId = wx.getStorageSync('memberId')
    let addressid = wx.getStorageSync('addressid')
    let lat = wx.getStorageSync('latitude')
    let lon = wx.getStorageSync('longitude')
    let storeid = wx.getStorageSync('storeid')
    let nowflag = wx.getStorageSync('currentflag')
    let cablist = wx.getStorageSync('mentionlist')
    // var cabindex = wx.getStorageSync('trueindex');
    let dayNum = 0
    let mealNum = 0
    let foodNum = 0
    let dateList = []
    let test = []
    let shitangChildOrderConfirms = []
    const { results: arr } = await fhGetCartAll(memberId)
    arr.forEach(dateItem => {
      test = []
      dayNum++
      dateList.push({ day: dateItem.date, week: dateItem.week })
      dateItem.shitangWeekMealsDtoList.forEach(mealItem => {
        test = []
        mealNum++
        mealItem.foodDtoList.forEach(foodItem => {
          const ele = conversion(foodItem.cartFoodDto)
          if (ele.arraylisting) {
            test.push({
              num: ele.num || ele.number,
              skuId: ele.id || ele.skuId || ele.foodSkuId,
              storeFoodId: ele.storeFoodId || ele.foodId,
              foodType: ele.foodType,
              attributes: ele.arraylisting.join('+'),
              commonNum: ele.commonNum
            })
          } else {
            test.push({
              num: ele.num || ele.number,
              skuId: ele.id || ele.skuId || ele.foodSkuId,
              storeFoodId: ele.storeFoodId || ele.foodId,
              foodType: ele.foodType,
              commonNum: ele.commonNum
            })
          }
          foodNum += ele.num || ele.number
        })
        if (test.length) {
          shitangChildOrderConfirms.push({
            foodForms: test,
            mealsId: mealItem.storeShitangMealsId,
            orderDate: dateItem.date,
            orderType: 8,
            lat: lat,
            lon: lon,
            ...extraInfo
          })
        }
      })
    })
    this.setData({
      allFoodList: arr,
      currFoodList: arr[0],
      dateList,
      dayNum,
      mealNum,
      foodNum
    })
    if (cablist == '') {
      if (addressid == '') {
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/shitang_order_confirm',
          {},
          {
            foodForms: shitangChildOrderConfirms[0].foodForms,
            // orderType: nowflag,
            orderType: 4,
            lat: lat,
            lon: lon,
            shitangChildOrderConfirms,
            ...extraInfo
          },
          '加载中',
          function (res) {
            if (res.code == 200) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              var testway = ''
              testway = 1
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: '',
                  takeAwayStatus: 1,
                  appointexpect: result.expectedTime,
                  // scheduletime: result.expectedTime.substring(11, 16),
                  loading: false
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              if (!that.data.address && that.data.currentflag == 1) {
                // that.obtainAdvance()
              }
              wx.setStorageSync('foodflag', 2)

              !groupFlag && wx.setStorageSync('foodlist', arr)
              wx.setStorageSync('couponindex', 'fo')

              // that.findCoupon()
              // that.obtainAdvance()
              //平台券
              let selectCouponlist = wx.getStorageSync('selectCouponlist')
              if (selectCouponlist != '') {
                that.getSelectCoupon(selectCouponlist)
              } else {
              }
            } else if (res.code == 520) {
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000) //延迟时间
            } else if (res.code == 525) {
              wx.setStorageSync('foodflag', 3)
              wx.setStorageSync('foodlist', '')
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            } else if (res.code == 522) {
              wx.navigateBack({
                delta: 1
              })
            } else if (res.code == 601) {
              setTimeout(function () {
                //要延时执行的代码
                wx.showToast({
                  title: res.message,
                  duration: 2000,
                  icon: 'none'
                })
              }, 500)
              for (var i = 0; i < that.data.tableselct.length; i++) {
                that.data.tableselct[i].cover = false
              }
              that.setData({
                currentflag: 2,
                couponindex: '',
                couponnum: '',
                usePoint: false,
                tableflag: false,
                tableselct: that.data.tableselct
              })
              wx.setStorageSync('currentflag', that.data.currentflag)
              wx.setStorageSync('trueindex', 'fail')
              wx.setStorageSync('mentionlist', '')
              that.onShow()
            }
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
      } else {
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/shitang_order_confirm',
          {},
          {
            foodForms: shitangChildOrderConfirms[0].foodForms,
            orderType: nowflag,
            lat: lat,
            lon: lon,
            addressId: addressid,
            shitangChildOrderConfirms,
            ...extraInfo
          },
          '加载中',
          function (res) {
            if (res.code == 200) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              var testway = ''
              testway = wx.getStorageSync('takeAwayStatus')
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: '',
                  takeAwayStatus: 1,
                  appointexpect: result.expectedTime,
                  // scheduletime: result.expectedTime.substring(11, 16)
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              if (!that.data.address && that.data.currentflag == 1) {
              }
              wx.setStorageSync('foodflag', 2)
              !groupFlag && wx.setStorageSync('foodlist', arr)
              wx.setStorageSync('couponindex', 'fo')
              // that.findCoupon()
              // that.obtainAdvance()
              //平台券
              let selectCouponlist = wx.getStorageSync('selectCouponlist')
              if (selectCouponlist != '') {
                that.getSelectCoupon(selectCouponlist)
              } else {
              }
            } else if (res.code == 520) {
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000) //延迟时间
            } else if (res.code == 525) {
              wx.setStorageSync('foodflag', 3)
              wx.setStorageSync('foodlist', '')
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            } else if (res.code == 522) {
              wx.navigateBack({
                delta: 1
              })
            } else if (res.code == 601) {
              setTimeout(function () {
                //要延时执行的代码
                wx.showToast({
                  title: res.message,
                  duration: 2000,
                  icon: 'none'
                })
              }, 500)

              for (var i = 0; i < that.data.tableselct.length; i++) {
                that.data.tableselct[i].cover = false
              }
              that.setData({
                currentflag: 2,
                couponindex: '',
                couponnum: '',
                usePoint: false,
                tableflag: false,
                tableselct: that.data.tableselct
              })
              wx.setStorageSync('currentflag', that.data.currentflag)
              wx.setStorageSync('trueindex', 'fail')
              wx.setStorageSync('mentionlist', '')
              that.onShow()
            }
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
      }
    } else {
      if (addressid == '') {
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/shitang_order_confirm',
          {},
          {
            foodForms: shitangChildOrderConfirms[0].foodForms,
            orderType: nowflag,
            lat: lat,
            lon: lon,
            cabInfo: cablist,
            shitangChildOrderConfirms,
            ...extraInfo
          },
          '加载中',
          function (res) {
            // wx.setStorageSync('mentionlist', "");
            if (res.code == 200) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              var testway = ''
              testway = wx.getStorageSync('takeAwayStatus')
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: '',
                  // takeAwayStatus: 1,
                  appointexpect: result.expectedTime,
                  // scheduletime: result.expectedTime.substring(11, 16),
                  loading: false
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              if (!that.data.address && that.data.currentflag == 1) {
              }
              wx.setStorageSync('foodflag', 2)

              // wx.setStorageSync('foodlist', that.data.orderfood);
              !groupFlag && wx.setStorageSync('foodlist', arr)
              wx.setStorageSync('couponindex', 'fo')

              // that.findCoupon()
              // that.obtainAdvance()
              //平台券
              let selectCouponlist = wx.getStorageSync('selectCouponlist')
              if (selectCouponlist != '') {
                that.getSelectCoupon(selectCouponlist)
              } else {
              }
            } else if (res.code == 520) {
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000) //延迟时间
            } else if (res.code == 525) {
              wx.setStorageSync('foodflag', 3)
              wx.setStorageSync('foodlist', '')
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            } else if (res.code == 522) {
              wx.navigateBack({
                delta: 1
              })
            } else if (res.code == 601) {
              setTimeout(function () {
                //要延时执行的代码
                wx.showToast({
                  title: res.message,
                  duration: 2000,
                  icon: 'none'
                })
              }, 500)
              for (var i = 0; i < that.data.tableselct.length; i++) {
                that.data.tableselct[i].cover = false
              }
              that.setData({
                currentflag: 2,
                couponindex: '',
                couponnum: '',
                usePoint: false,
                tableflag: false,
                tableselct: that.data.tableselct
              })
              wx.setStorageSync('currentflag', that.data.currentflag)
              wx.setStorageSync('trueindex', 'fail')
              wx.setStorageSync('mentionlist', '')
              that.onShow()
            }
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
      } else {
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/shitang_order_confirm',
          {},
          {
            foodForms: shitangChildOrderConfirms[0].foodForms,
            orderType: nowflag,
            addressId: addressid,
            lat: lat,
            lon: lon,
            cabInfo: cablist,
            shitangChildOrderConfirms,
            ...extraInfo
          },
          '加载中',
          function (res) {
            // wx.setStorageSync('mentionlist', "");
            if (res.code == 200) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              var testway = ''
              testway = wx.getStorageSync('takeAwayStatus')
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: '',
                  // takeAwayStatus: 1,
                  appointexpect: result.expectedTime,
                  // scheduletime: result.expectedTime.substring(11, 16),
                  loading: false
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              if (!that.data.address && that.data.currentflag == 1) {
              }
              wx.setStorageSync('foodflag', 2)
              !groupFlag && wx.setStorageSync('foodlist', arr)
              wx.setStorageSync('couponindex', 'fo')
              // that.findCoupon()
              // that.obtainAdvance()
              //平台券
              let selectCouponlist = wx.getStorageSync('selectCouponlist')
              if (selectCouponlist != '') {
                that.getSelectCoupon(selectCouponlist)
              } else {
              }
            } else if (res.code == 520) {
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            } else if (res.code == 525) {
              wx.setStorageSync('foodflag', 3)
              wx.setStorageSync('foodlist', '')
              wx.showToast({
                title: res.message,
                icon: 'none'
              })
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            } else if (res.code == 522) {
              wx.navigateBack({
                delta: 1
              })
            } else if (res.code == 601) {
              setTimeout(function () {
                //要延时执行的代码
                wx.showToast({
                  title: res.message,
                  duration: 2000,
                  icon: 'none'
                })
              }, 500)
              for (var i = 0; i < that.data.tableselct.length; i++) {
                that.data.tableselct[i].cover = false
              }
              that.setData({
                currentflag: 2,
                couponindex: '',
                couponnum: '',
                usePoint: false,
                tableflag: false,
                tableselct: that.data.tableselct
              })
              wx.setStorageSync('currentflag', that.data.currentflag)
              wx.setStorageSync('trueindex', 'fail')
              wx.setStorageSync('mentionlist', '')
              that.onShow()
            }
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
      }
    }
    //优惠券

    // 自提柜判断
    var cabinetflag = wx.getStorageSync('cabinetflag')
    var exindex = wx.getStorageSync('trueindex')
    if (cabinetflag == 3 && exindex != 'fail') {
      var testindex = wx.getStorageSync('trueindex')
      that.setData({
        mentionflag: true,
        normalflag: false,
        trueindex: testindex
      })
    } else if (that.data.normalflag && exindex == 'fail') {
      var testindex = wx.getStorageSync('trueindex')
      that.setData({
        mentionflag: false,
        normalflag: true,
        trueindex: testindex
      })
    } else if (!that.data.normalflag && exindex == 'fail') {
      var testindex = wx.getStorageSync('trueindex')
      that.setData({
        mentionflag: true,
        normalflag: false,
        trueindex: testindex
      })
    }
  },
  // 页面准备好时
  onReady() {
    this.addressModal = this.selectComponent('#address-modal')
    this.rulesModal = this.selectComponent('#rules-modal')
    this.addressModal.onClose()
  },
  takeFlag: function () {
    var that = this
    var lunchbox = wx.getStorageSync('lunchbox')
    for (var i = 0; i < that.data.tableselct.length; i++) {
      that.data.tableselct[i].cover = false
    }
    that.setData({
      currentflag: 2,
      couponindex: '',
      couponnum: '',
      usePoint: false,
      tableflag: false,
      tableselct: that.data.tableselct
    })
    wx.setStorageSync('currentflag', that.data.currentflag)
    wx.setStorageSync('trueindex', 'fail')
    wx.setStorageSync('mentionlist', '')
    that.onShow()
  },
  takeFlags: function () {
    var that = this
    var startSalePrice = wx.getStorageSync('startSalePrice')
    var lunchbox = wx.getStorageSync('lunchbox')
    for (var i = 0; i < that.data.tableselct.length; i++) {
      that.data.tableselct[i].cover = false
    }
    that.setData({
      currentflag: 1,
      couponindex: '',
      couponnum: '',
      usePoint: false,
      tableflag: false,
      tableselct: that.data.tableselct
    })
    wx.setStorageSync('currentflag', that.data.currentflag)
    that.onShow()
    // if (that.data.takeAwayStatus == 1) {
    // if (lunchbox >= that.data.orderlist.startSale) {
    //   that.setData({
    //     currentflag: 1,
    //     couponindex: '',
    //     couponnum: '',
    //     usePoint: false,
    //     tableflag: false,
    //     tableselct: that.data.tableselct
    //   })
    //   wx.setStorageSync('currentflag', that.data.currentflag);
    //   that.onShow();
    // } else {
    //   wx.showToast({
    //     title: '不满足外卖起送价',
    //     icon: 'none',
    //     duration: 2000
    //   })
    // }

    // } else {
    //   return;
    // }
  },
  bindpickertable: function (e) {
    var that = this
    if (e.detail.value == 0) {
      that.setData({
        huanbaoflag: true,
        tableIndex: e.detail.value
        // tableflag:true,
      })
    } else {
      that.setData({
        huanbaoflag: false,
        tableIndex: e.detail.value
        // tableflag:true
      })
    }
  },
  takecover: function () {
    var that = this
    that.setData({
      showcover: true
    })
  },
  hidecover: function () {
    var that = this
    that.setData({
      showcover: false
    })
  },
  takeTableware: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index
    for (var i = 0; i < that.data.tableselct.length; i++) {
      if (i == index) {
        that.data.tableselct[i].cover = true
      } else {
        that.data.tableselct[i].cover = false
      }
    }
    if (index == 0) {
      that.setData({
        huanbaoflag: true,
        tableselct: that.data.tableselct,
        coverindex: index,
        showcover: false,
        tableflag: true
      })
    } else {
      that.setData({
        huanbaoflag: false,
        tableselct: that.data.tableselct,
        coverindex: index,
        showcover: false,
        tableflag: true
      })
    }

    that.setData({
      tableselct: that.data.tableselct,
      coverindex: index,
      showcover: false,
      tableflag: true
    })
  },
  bindpickertime: function (e) {
    var that = this
    that.setData({
      timeIndex: e.detail.value
    })
  },
  // 新版提交订单
  async takePaid() {
    try {
    var that = this
      if (this.data.address === null) {
        console.log("address", this.data.address)
        !groupFlag &&
          wx.showModal({
            title: '收货地址',
            content: '现在您暂无收货地址，点击确认按钮即可快速添加',
            showCancel: true, //是否显示取消按钮
            cancelText: '取消', //默认是“取消”
            confirmText: '确认', //默认是“确定”
            success: function (res) {
              if (res.cancel) {
                return
              } else {
                that.showAddressModal()
              }
            },
            fail: function (res) {}, //接口调用失败的回调函数

            complete: function (res) {} //接口调用结束的回调函数（调用成功、失败都会执行）
          })
        return
      }
      // 需要优先创建地址
      const addressModule = this.selectComponent('#address-module')
      if (addressModule) {
        const address = await addressModule.verifyForm()
        this.setData({
          address: address
        })
        this.onShow()
      }
      const { extraInfo = {} } = this.data
      const groupFlag = this.computedActivityGroup()
      let groupId = null
      if (groupFlag) {
        const { focusGroupId } = extraInfo
        groupId = focusGroupId
      }
      await submitOrder.bind(this)()
      wx.$setGlobalData('cartTotalNumber', 0)
      wx.$setGlobalData('cartDishes', {})
      wx.$setGlobalData('boughtDiscountDishes', {})
      wx.$setGlobalData('selectedCategory', new Map())
      this.payWechat()
    } catch (e) {
      console.error('debug', e)
      this.setData({
        payflag:false
      })
    }
  },
  takeremarker: function (e) {
    var that = this
    that.setData({
      remarker: e.detail.value
    })
  },
  goAddress: function () {
    const flag = this.computedActivityGroup()
    if (flag) return
    var that = this
    wx.navigateTo({
      url:
        '../../range/add/add?storeid=' +
        that.data.storeid +
        '&currentflag=' +
        that.data.currentflag
    })
  },
  goUseAddresslist: function () {
    const flag = this.computedActivityGroup()
    if (flag) return
    const { from, extraInfo } = this.data
    var storeid = wx.getStorageSync('storeid')
    wx.redirectTo({
      url: `/package/range/entry/entry?storeid=${storeid}&from=${from}&extraInfo=${JSON.stringify(
        extraInfo || {}
      )}`
    })
  },
  takeIntegral: function () {
    var that = this
    var inflag = !that.data.usePoint
    var index = wx.getStorageSync('couponindex')
    that.setData({
      usePoint: inflag
    })
    if (index == 'fo') {
      that.getAggregate(that.data.usePoint, index, '')
    } else {
      that.getAggregate(
        that.data.usePoint,
        index,
        that.data.canUseCoupons[index].type
      )
    }
  },
  takeCouponone: function () {
    var that = this
    that.setData({
      couponflag: 1
    })
  },
  takeCoupontwo: function () {
    var that = this
    that.setData({
      couponflag: 2
    })
  },
  hideCoupon: function () {
    var that = this
    that.setData({
      showcoupon: false
    })
  },
  //优惠劵
  findCoupon: function () {
    var that = this
    const { orderlist } = this.data
    const { orderConfirmFoodList, platformCouponPrice, couponPrice } = orderlist
    let selectCouponlist = wx.getStorageSync('selectCouponlist')
    var cardNumber = wx.getStorageSync('cardNumber')
    var memberid = wx.getStorageSync('memberId')
    var id = wx.getStorageSync('storeid')
    var str = ''
    var testskulist = []
    for (var p = 0; p < that.data.orderfood.length; p++) {
      str += that.data.orderfood[p].cxItemId + ','
      testskulist.push(that.data.orderfood[p].foodTemplateSkuId)
    }
    if (str.length > 0) {
      str = str.substr(0, str.length - 1)
    }

    let seller = wx.getStorageSync('merchantid')
    if (selectCouponlist != '') {
      // 公众版优惠券
      masses.putCoupon(
        baseUrl.waimaiUrl + `/client/members/${memberid}/coupons`,
        {},
        {
          orderFee: orderlist.totalPrice,
          storeId: id,
          foodTemplateSkuIdList: testskulist,
          selectCouponList: selectCouponlist,
          merchantId: seller,
          platformCouponPrice: platformCouponPrice,
          couponPrice: couponPrice
        },
        '加载中',
        function (res) {
          if (res.code == 200) {
            var result = res.results
            for (var i = 0; i < result.canUse.length; i++) {
              result.canUse[i].endTime = result.canUse[i].endTime.substring(
                0,
                10
              )
              result.canUse[i].couponflag = false
              result.canUse[i].pointflag = false
              var y = String(result.canUse[i].value).indexOf('.') + 1
              if (y > 0) {
                result.canUse[i].pointflag = true
              }
            }
            for (var k = 0; k < result.noUse.length; k++) {
              result.noUse[k].endTime = result.noUse[k].endTime.substring(0, 10)
              result.noUse[k].pointflag = false
              var y = String(result.noUse[k].value).indexOf('.') + 1
              if (y > 0) {
                result.noUse[k].pointflag = true
              }
            }
            if (result.canAdd != null) {
              for (var i = 0; i < result.canAdd.length; i++) {
                result.canAdd[i].endTime = result.canAdd[i].endTime.substring(
                  0,
                  10
                )
                result.canAdd[i].couponflag = false
                result.canAdd[i].pointflag = false
                var y = String(result.canAdd[i].value).indexOf('.') + 1
                if (y > 0) {
                  result.canAdd[i].pointflag = true
                }
              }
            }
            if (result.notAdd != null) {
              for (var i = 0; i < result.notAdd.length; i++) {
                result.notAdd[i].endTime = result.notAdd[i].endTime.substring(
                  0,
                  10
                )
                result.notAdd[i].couponflag = false
                result.notAdd[i].pointflag = false
                var y = String(result.notAdd[i].value).indexOf('.') + 1
                if (y > 0) {
                  result.notAdd[i].pointflag = true
                }
              }
            }
            that.setData({
              canNotUseCoupons: result.noUse,
              canUseCoupons: result.canUse,
              canAddCoupons: result.canAdd,
              notAddCoupons: result.notAdd,
              couponnumber: result.canUse.length
            })
          } else {
            console.log(res.message)
          }
        },
        function (err) {
          wx.showToast({
            title: '失败'
          })
        }
      )
    } else {
      // 公众版优惠券
      masses.putCoupon(
        baseUrl.waimaiUrl + `/client/members/${memberid}/coupons`,
        {},
        {
          orderFee: orderlist.totalPrice,
          storeId: id,
          foodTemplateSkuIdList: testskulist,
          merchantId: seller,
          platformCouponPrice: platformCouponPrice,
          couponPrice: couponPrice
        },
        '加载中',
        function (res) {
          if (res.code == 200) {
            var result = res.results
            for (var i = 0; i < result.canUse.length; i++) {
              result.canUse[i].endTime = result.canUse[i].endTime.substring(
                0,
                10
              )
              result.canUse[i].couponflag = false
              result.canUse[i].pointflag = false
              var y = String(result.canUse[i].value).indexOf('.') + 1
              if (y > 0) {
                result.canUse[i].pointflag = true
              }
            }
            for (var k = 0; k < result.noUse.length; k++) {
              result.noUse[k].endTime = result.noUse[k].endTime.substring(0, 10)
              result.noUse[k].pointflag = false
              var y = String(result.noUse[k].value).indexOf('.') + 1
              if (y > 0) {
                result.noUse[k].pointflag = true
              }
            }
            that.setData({
              canNotUseCoupons: result.noUse,
              canUseCoupons: result.canUse,
              couponnumber: result.canUse.length
            })
          } else {
            console.log(res.message)
          }
        },
        function (err) {
          wx.showToast({
            title: '失败'
          })
        }
      )
    }
  },
  takeState: function (e) {
    var that = this
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    var test = 'fo'
    for (var i = 0; i < that.data.canUseCoupons.length; i++) {
      if (that.data.canUseCoupons[i].id == id) {
        if (that.data.canUseCoupons[i].couponflag == true) {
          that.data.canUseCoupons[i].couponflag = false
          index = test
        } else {
          that.data.canUseCoupons[i].couponflag = true
        }
      } else {
        that.data.canUseCoupons[i].couponflag = false
      }
    }
    that.setData({
      canUseCoupons: that.data.canUseCoupons,
      couponid: id,
      couponindex: index
    })
    wx.setStorageSync('couponindex', index)
    that.takeDefined()
  },
  selectCoupon: function () {
    const { orderlist } = this.data
    wx.setStorageSync('coupon-temp-order', orderlist)
    const temp = JSON.stringify(orderlist)
    const tempEncode = encodeURIComponent(temp)
    wx.navigateTo({
      url: `../comprehensive/comprehensive?orderlist=${tempEncode}`
    })
  },
  takeDefined: function (e) {
    var that = this
    var index = wx.getStorageSync('couponindex')
    if (index == 'fo') {
      that.getAggregate(that.data.usePoint, index, '')
    } else {
      that.getAggregate(
        that.data.usePoint,
        index,
        that.data.canUseCoupons[index].type
      )
    }
  },
  takeName: function (e) {
    var that = this
    that.setData({
      reserveName: e.detail.value
    })
  },
  takePhone: function (e) {
    var that = this
    that.setData({
      reservePhone: e.detail.value
    })
  },
  // 自提柜
  takeNormal: function () {
    var that = this
    var normal = !that.data.normalflag
    var mention = !that.data.mentionflag

    var trueindex = wx.getStorageSync('trueindex')
    that.setData({
      normalflag: normal,
      mentionflag: mention,
      trueindex: trueindex
    })
    if (that.data.normalflag) {
      wx.setStorageSync('trueindex', 'fail')
      wx.setStorageSync('mentionlist', '')
      that.onShow()
    } else {
      that.onShow()
    }
  },
  takeMention: function () {
    var that = this
    wx.redirectTo({
      url:
        '../cabinet/cabinet?lat=' +
        that.data.address.latitude +
        '&lon=' +
        that.data.address.longitude
    })
  },
  hideMention: function () {
    var that = this
    that.setData({
      showMention: false
    })
  },
  takeCondition: function (e) {
    var that = this
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    for (var i = 0; i < that.data.mentionlist.length; i++) {
      if (that.data.mentionlist[i].cab_code == id) {
        if (that.data.mentionlist[i].selectmention == true) {
          that.data.mentionlist[i].selectmention = false
        } else {
          that.data.mentionlist[i].selectmention = true
        }
      } else {
        that.data.mentionlist[i].selectmention = false
      }
    }
    that.setData({
      mentionlist: that.data.mentionlist,
      mentionid: id,
      mentionindex: index
    })
  },
  takeChoice: function (e) {
    var that = this
    if (that.data.mentionlist[that.data.mentionindex].selectmention == false) {
      that.setData({
        trueindex: 'fail',
        showMention: false
      })
    } else {
      that.setData({
        trueindex: that.data.mentionindex,
        showMention: false
      })
    }
  },
  // 优惠卷积分的提交
  getAggregate: function (checkpoint, checkindex, checktype) {
    var that = this
    const { extraInfo } = this.data
    var storeid = wx.getStorageSync('storeid')
    var arr = getShoppingCart(this.data.storeCartKey) || []
    var memberId = wx.getStorageSync('memberId')
    var cablist = wx.getStorageSync('mentionlist')
    var lat = wx.getStorageSync('latitude')
    var lon = wx.getStorageSync('longitude')
    var test = []

    arr.forEach((ele, index) => {
      if (ele.arraylisting) {
        test.push({
          num: ele.num,
          skuId: ele.id,
          storeFoodId: ele.storeFoodId,
          foodType: ele.foodType,
          attributes: ele.arraylisting.join('+'),
          commonNum: ele.commonNum
        })
      } else {
        test.push({
          num: ele.num,
          skuId: ele.id,
          storeFoodId: ele.storeFoodId,
          foodType: ele.foodType,
          commonNum: ele.commonNum
        })
      }
    })
    if (cablist == '') {
      if (checkindex == 'fo' && !checkpoint) {
        // 无优惠卷、无积分
        that.setData({
          showcoupon: false
        })
        //无优惠卷、有积分
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/confirm',
          {},
          {
            foodForms: test,
            orderType: that.data.currentflag,
            // commonCouponId: id,
            usePoints: false,
            lat: lat,
            lon: lon
          },
          '加载中',
          function (res) {
            var result = res.results
            that.confirmEnd(result)
            let newData = []
            newData.push({
              id: 0,
              latitude: result.storeLat,
              longitude: result.storeLon,
              iconPath:
                'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
              width: 35,
              height: 35
            })
            var testproduct = []
            var testspecid = []
            var productid = ''
            var specid = ''
            for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
              testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
              testspecid.push(result.orderConfirmFoodList[i].foodTemplateSkuId)
              productid = testproduct.join(',')
              specid = testspecid.join(',')
              if (result.orderConfirmFoodList[i].foodType == 2) {
                that.setData({
                  seckillflag: true
                })
              }
            }
            that.setData(
              {
                markers: newData,
                orderlist: result,
                orderfood: result.orderConfirmFoodList,
                address: result.memberAddresses,
                currentLo: result.storeLon,
                currentLa: result.storeLat,
                productIds: productid,
                specIds: specid,
                couponnum: result.couponPrice
              },
              () => {
                that.assignAddress(extraInfo.focusGroup, result.memberAddresses)
              }
            )
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
      } else if (checkindex == 'fo' && checkpoint) {
        //无优惠卷、有积分
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/confirm',
          {},
          {
            foodForms: test,
            orderType: that.data.currentflag,
            // commonCouponId: id,
            usePoints: true
          },
          '加载中',
          function (res) {
            var result = res.results
            that.confirmEnd(result)
            let newData = []
            newData.push({
              id: 0,
              latitude: result.storeLat,
              longitude: result.storeLon,
              iconPath:
                'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
              width: 35,
              height: 35
            })
            var testproduct = []
            var testspecid = []
            var productid = ''
            var specid = ''
            for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
              testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
              testspecid.push(result.orderConfirmFoodList[i].foodTemplateSkuId)
              productid = testproduct.join(',')
              specid = testspecid.join(',')
              if (result.orderConfirmFoodList[i].foodType == 2) {
                that.setData({
                  seckillflag: true
                })
              }
            }
            that.setData(
              {
                markers: newData,
                orderlist: result,
                orderfood: result.orderConfirmFoodList,
                address: result.memberAddresses,
                currentLo: result.storeLon,
                currentLa: result.storeLat,
                productIds: productid,
                specIds: specid,
                couponnum: result.couponPrice
              },
              () => {
                that.assignAddress(extraInfo.focusGroup, result.memberAddresses)
              }
            )
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
        that.setData({
          showcoupon: false
        })
      } else if (checkindex != 'fo' && !checkpoint) {
        // 有优惠卷，无积分
        //满减卷、直减卷
        if (
          that.data.canUseCoupons[checkindex].type == 1 ||
          that.data.canUseCoupons[checkindex].type == 2
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              commonCouponId: that.data.canUseCoupons[checkindex].id,
              usePoints: false,
              lat: lat,
              lon: lon
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (that.data.canUseCoupons[checkindex].type == 3) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              foodCouponIds: that.data.canUseCoupons[checkindex].id,
              foodCouponIds: {
                couponId: that.data.canUseCoupons[checkindex].id,
                foodPrice: that.data.canUseCoupons[checkindex].reductionAmount,
                foodSpecId: that.data.canUseCoupons[checkindex].specId
              },
              usePoints: false
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (
          that.data.canUseCoupons[checkindex].type == 4 ||
          that.data.canUseCoupons[checkindex].type == 5
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              wechatCoupon: {
                couponAmount:
                  that.data.canUseCoupons[checkindex].reductionAmount,
                couponId: that.data.canUseCoupons[checkindex].id,
                goodsNo: that.data.canUseCoupons[checkindex].goodsNo,
                goodsTag: that.data.canUseCoupons[checkindex].goodsTag
              },
              usePoints: false
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        }
      } else if (checkindex != 'fo' && checkpoint) {
        // 优惠卷、有积分
        if (
          that.data.canUseCoupons[checkindex].type == 1 ||
          that.data.canUseCoupons[checkindex].type == 2
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              commonCouponId: that.data.canUseCoupons[checkindex].id,
              usePoints: true,
              lat: lat,
              lon: lon
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (that.data.canUseCoupons[checkindex].type == 3) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              foodCouponIds: that.data.canUseCoupons[checkindex].id,
              foodCouponIds: {
                couponId: that.data.canUseCoupons[checkindex].id,
                foodPrice: that.data.canUseCoupons[checkindex].reductionAmount,
                foodSpecId: that.data.canUseCoupons[checkindex].specId
              },
              usePoints: true
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (
          that.data.canUseCoupons[checkindex].type == 4 ||
          that.data.canUseCoupons[checkindex].type == 5
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              wechatCoupon: {
                couponAmount:
                  that.data.canUseCoupons[checkindex].reductionAmount,
                couponId: that.data.canUseCoupons[checkindex].id,
                goodsNo: that.data.canUseCoupons[checkindex].goodsNo,
                goodsTag: that.data.canUseCoupons[checkindex].goodsTag
              },
              usePoints: true
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.pngimage/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        }
      }
    } else {
      if (checkindex == 'fo' && !checkpoint) {
        // 无优惠卷、无积分
        that.setData({
          showcoupon: false
        })
        //无优惠卷、有积分
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/confirm',
          {},
          {
            foodForms: test,
            orderType: that.data.currentflag,
            // commonCouponId: id,
            usePoints: false,
            cabInfo: cablist,
            lat: lat,
            lon: lon
          },
          '加载中',
          function (res) {
            var result = res.results
            that.confirmEnd(result)
            let newData = []
            newData.push({
              id: 0,
              latitude: result.storeLat,
              longitude: result.storeLon,
              iconPath:
                'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
              width: 35,
              height: 35
            })
            var testproduct = []
            var testspecid = []
            var productid = ''
            var specid = ''
            for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
              testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
              testspecid.push(result.orderConfirmFoodList[i].foodTemplateSkuId)
              productid = testproduct.join(',')
              specid = testspecid.join(',')
              if (result.orderConfirmFoodList[i].foodType == 2) {
                that.setData({
                  seckillflag: true
                })
              }
            }
            that.setData(
              {
                markers: newData,
                orderlist: result,
                orderfood: result.orderConfirmFoodList,
                address: result.memberAddresses,
                currentLo: result.storeLon,
                currentLa: result.storeLat,
                productIds: productid,
                specIds: specid,
                couponnum: result.couponPrice
              },
              () => {
                that.assignAddress(extraInfo.focusGroup, result.memberAddresses)
              }
            )
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
      } else if (checkindex == 'fo' && checkpoint) {
        //无优惠卷、有积分
        order.getOrder(
          baseUrl.waimaiUrl +
          '/client/' +
          memberId +
          '/order/' +
          storeid +
          '/confirm',
          {},
          {
            foodForms: test,
            orderType: that.data.currentflag,
            // commonCouponId: id,
            usePoints: true,
            cabInfo: cablist,
            lat: lat,
            lon: lon
          },
          '加载中',
          function (res) {
            var result = res.results
            that.confirmEnd(result)
            let newData = []
            newData.push({
              id: 0,
              latitude: result.storeLat,
              longitude: result.storeLon,
              iconPath:
                'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
              width: 35,
              height: 35
            })
            var testproduct = []
            var testspecid = []
            var productid = ''
            var specid = ''
            for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
              testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
              testspecid.push(result.orderConfirmFoodList[i].foodTemplateSkuId)
              productid = testproduct.join(',')
              specid = testspecid.join(',')
              if (result.orderConfirmFoodList[i].foodType == 2) {
                that.setData({
                  seckillflag: true
                })
              }
            }
            that.setData(
              {
                markers: newData,
                orderlist: result,
                orderfood: result.orderConfirmFoodList,
                address: result.memberAddresses,
                currentLo: result.storeLon,
                currentLa: result.storeLat,
                productIds: productid,
                specIds: specid,
                couponnum: result.couponPrice
              },
              () => {
                that.assignAddress(extraInfo.focusGroup, result.memberAddresses)
              }
            )
          },
          function (err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
        that.setData({
          showcoupon: false
        })
      } else if (checkindex != 'fo' && !checkpoint) {
        // 有优惠卷，无积分
        //满减卷、直减卷
        if (
          that.data.canUseCoupons[checkindex].type == 1 ||
          that.data.canUseCoupons[checkindex].type == 2
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              commonCouponId: that.data.canUseCoupons[checkindex].id,
              usePoints: false,
              cabInfo: cablist,
              lat: lat,
              lon: lon
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (that.data.canUseCoupons[checkindex].type == 3) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              foodCouponIds: that.data.canUseCoupons[checkindex].id,
              foodCouponIds: {
                couponId: that.data.canUseCoupons[checkindex].id,
                foodPrice: that.data.canUseCoupons[checkindex].reductionAmount,
                foodSpecId: that.data.canUseCoupons[checkindex].specId
              },
              usePoints: false
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (
          that.data.canUseCoupons[checkindex].type == 4 ||
          that.data.canUseCoupons[checkindex].type == 5
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              wechatCoupon: {
                couponAmount:
                  that.data.canUseCoupons[checkindex].reductionAmount,
                couponId: that.data.canUseCoupons[checkindex].id,
                goodsNo: that.data.canUseCoupons[checkindex].goodsNo,
                goodsTag: that.data.canUseCoupons[checkindex].goodsTag
              },
              usePoints: false
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        }
      } else if (checkindex != 'fo' && checkpoint) {
        // 优惠卷、有积分
        if (
          that.data.canUseCoupons[checkindex].type == 1 ||
          that.data.canUseCoupons[checkindex].type == 2
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              commonCouponId: that.data.canUseCoupons[checkindex].id,
              usePoints: true,
              cabInfo: cablist,
              lat: lat,
              lon: lon
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
                testspecid.push(
                  result.orderConfirmFoodList[i].foodTemplateSkuId
                )
                productid = testproduct.join(',')
                specid = testspecid.join(',')
                if (result.orderConfirmFoodList[i].foodType == 2) {
                  that.setData({
                    seckillflag: true
                  })
                }
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (that.data.canUseCoupons[checkindex].type == 3) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              foodCouponIds: that.data.canUseCoupons[checkindex].id,
              foodCouponIds: {
                couponId: that.data.canUseCoupons[checkindex].id,
                foodPrice: that.data.canUseCoupons[checkindex].reductionAmount,
                foodSpecId: that.data.canUseCoupons[checkindex].specId
              },
              usePoints: true
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        } else if (
          that.data.canUseCoupons[checkindex].type == 4 ||
          that.data.canUseCoupons[checkindex].type == 5
        ) {
          order.getOrder(
            baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            storeid +
            '/confirm',
            {},
            {
              foodForms: test,
              orderType: that.data.currentflag,
              wechatCoupon: {
                couponAmount:
                  that.data.canUseCoupons[checkindex].reductionAmount,
                couponId: that.data.canUseCoupons[checkindex].id,
                goodsNo: that.data.canUseCoupons[checkindex].goodsNo,
                goodsTag: that.data.canUseCoupons[checkindex].goodsTag
              },
              usePoints: true
            },
            '加载中',
            function (res) {
              var result = res.results
              that.confirmEnd(result)
              let newData = []
              newData.push({
                id: 0,
                latitude: result.storeLat,
                longitude: result.storeLon,
                iconPath:
                  'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
                width: 35,
                height: 35
              })
              var testproduct = []
              var testspecid = []
              var productid = ''
              var specid = ''
              for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
                testproduct.push(result.orderConfirmFoodList[i].foodId)
                testspecid.push(result.orderConfirmFoodList[i].skuId)
                productid = testproduct.join(',')
                specid = testspecid.join(',')
              }
              that.setData(
                {
                  markers: newData,
                  orderlist: result,
                  orderfood: result.orderConfirmFoodList,
                  address: result.memberAddresses,
                  currentLo: result.storeLon,
                  currentLa: result.storeLat,
                  productIds: productid,
                  specIds: specid,
                  couponnum: result.couponPrice
                },
                () => {
                  that.assignAddress(
                    extraInfo.focusGroup,
                    result.memberAddresses
                  )
                }
              )
              // console.log(result);
              // that.findCoupon();
            },
            function (err) {
              wx.showToast({
                title: '失败'
              })
            }
          )
          that.setData({
            showcoupon: false
          })
        }
      }
    }
  },
  // 平台券提交
  getSelectCoupon: function (selectCouponlist) {
    var that = this
    var storeid = wx.getStorageSync('storeid')
    var arr = getShoppingCart(this.data.storeCartKey) || []
    var memberId = wx.getStorageSync('memberId')
    var cablist = wx.getStorageSync('mentionlist')
    var lat = wx.getStorageSync('latitude')
    var lon = wx.getStorageSync('longitude')
    var test = []
    arr.forEach((ele, index) => {
      if (ele.arraylisting) {
        test.push({
          num: ele.num,
          skuId: ele.id,
          storeFoodId: ele.storeFoodId,
          foodType: ele.foodType,
          attributes: ele.arraylisting.join('+'),
          commonNum: ele.commonNum
        })
      } else {
        test.push({
          num: ele.num,
          skuId: ele.id,
          storeFoodId: ele.storeFoodId,
          foodType: ele.foodType,
          commonNum: ele.commonNum
        })
      }
    })
    let commonCouponId = ''
    let platformCouponId = ''
    for (var p = 0; p < selectCouponlist.length; p++) {
      if (selectCouponlist[p].couponType === 1) {
        commonCouponId = selectCouponlist[p].id
      }
      if (selectCouponlist[p].couponType === 2) {
        platformCouponId = selectCouponlist[p].id
      }
    }
    if (cablist == '') {
      // 有优惠卷
      //满减卷、直减卷
      order.getOrder(
        baseUrl.waimaiUrl +
        '/client/' +
        memberId +
        '/order/' +
        storeid +
        '/confirm',
        {},
        {
          foodForms: test,
          orderType: that.data.currentflag,
          commonCouponId: commonCouponId,
          platformCouponId: platformCouponId,
          usePoints: false,
          lat: lat,
          lon: lon
        },
        '加载中',
        function (res) {
          var result = res.results
          that.confirmEnd(result)
          let newData = []
          newData.push({
            id: 0,
            latitude: result.storeLat,
            longitude: result.storeLon,
            iconPath:
              'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
            width: 35,
            height: 35
          })
          var testproduct = []
          var testspecid = []
          var productid = ''
          var specid = ''
          for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
            testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
            testspecid.push(result.orderConfirmFoodList[i].foodTemplateSkuId)
            productid = testproduct.join(',')
            specid = testspecid.join(',')
            if (result.orderConfirmFoodList[i].foodType == 2) {
              that.setData({
                seckillflag: true
              })
            }
          }
          that.setData({
            markers: newData,
            orderlist: result,
            orderfood: result.orderConfirmFoodList,
            address: result.memberAddresses,
            currentLo: result.storeLon,
            currentLa: result.storeLat,
            productIds: productid,
            specIds: specid,
            couponnum: result.couponPrice + result.platformCouponPrice
          })
        },
        function (err) {
          wx.showToast({
            title: '失败'
          })
        }
      )
    } else {
      order.getOrder(
        baseUrl.waimaiUrl +
        '/client/' +
        memberId +
        '/order/' +
        storeid +
        '/confirm',
        {},
        {
          foodForms: test,
          orderType: that.data.currentflag,
          commonCouponId: commonCouponId,
          platformCouponId: platformCouponId,
          usePoints: false,
          lat: lat,
          lon: lon
        },
        '加载中',
        function (res) {
          var result = res.results
          that.confirmEnd(result)
          let newData = []
          newData.push({
            id: 0,
            latitude: result.storeLat,
            longitude: result.storeLon,
            iconPath:
              'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/merchant.png',
            width: 35,
            height: 35
          })
          var testproduct = []
          var testspecid = []
          var productid = ''
          var specid = ''
          for (var i = 0; i < result.orderConfirmFoodList.length; i++) {
            testproduct.push(result.orderConfirmFoodList[i].foodTemplateId)
            testspecid.push(result.orderConfirmFoodList[i].foodTemplateSkuId)
            productid = testproduct.join(',')
            specid = testspecid.join(',')
            if (result.orderConfirmFoodList[i].foodType == 2) {
              that.setData({
                seckillflag: true
              })
            }
          }
          that.setData({
            markers: newData,
            orderlist: result,
            orderfood: result.orderConfirmFoodList,
            address: result.memberAddresses,
            currentLo: result.storeLon,
            currentLa: result.storeLat,
            productIds: productid,
            specIds: specid,
            couponnum: result.couponPrice + result.platformCouponPrice
          })
        },
        function (err) {
          wx.showToast({
            title: '失败'
          })
        }
      )
    }
  },
  // 获取所有餐次
  async getMeals() {
    const { results } = await fhGetMeals()
    const mealList = results.map(mealItem => {
        mealItem.startDiningTime = mealItem.startDiningTime.substr(0, 5)
        mealItem.endDiningTime = mealItem.endDiningTime.substr(0, 5)
      return mealItem
    })
    this.setData({
      mealList
    })
  },
  // 餐次时间
  hideMeals() {
    this.setData({
      showMeals: false
    })
  },
  showMeals() {
    this.setData({
      showMeals: true
    })
  },
  // 商品详情
  hideDates() {
    this.setData({
      showDates: false
    })
  },
  showDates() {
    this.setData({
      showDates: true
    })
  },
  onDateChange({detail}) {
    this.setData({
      currFoodList: this.data.allFoodList[detail]
    })
  },
  obtainAdvance: function () {
    var that = this
    let storeid = wx.getStorageSync('storeid')
    let merchantid = wx.getStorageSync('merchantid')
    if (that.data.currentflag == 1) {
      order.takeappointmentTime(
        baseUrl.waimaiUrl +
        `/client/merchants/${merchantid}/stores/${storeid}/appointment-time`,
        {
          fastestDeliveryTime: that.data.orderlist.expectedTime
        },
        {},
        '加载中',
        function (res) {
          if (res.code == 200) {
            var result = res.results
            if (result.advancelist.length == 0) {
              that.setData({
                advancelist: result.advancelist,
                isclose: result.isColse,
                storeType: result.storeType,
                advancetimeindex: 0,
                advancedayindex: 0,
                truedayindex: 0
              })
            } else {
              that.setData({
                appointexpect: result.advancelist[0].timelist[0].identifyTime,
                advancelist: result.advancelist,
                selectadvance: result.advancelist[0].dayid,
                isclose: result.isColse,
                storeType: result.storeType,
                advancetimeindex: 0,
                advancedayindex: 0,
                truedayindex: 0
              })
              if (
                that.data.advancelist[that.data.truedayindex].timelist[
                  that.data.advancetimeindex
                ].reserveflag == false
              ) {
                that.setData({
                  scheduleflag: false
                })
              } else {
                that.setData({
                  scheduleflag: true
                })
              }
              {
              }
            }
          }
        },
        function (err) {
          wx.showToast({
            title: '失败'
          })
        }
      )
    } else {
      order.takeappointmentTime(
        baseUrl.waimaiUrl +
        `/client/merchants/${merchantid}/stores/${storeid}/appointment-time`,
        {
          fastestDeliveryTime: that.data.orderlist.expectedTime
        },
        {},
        '加载中',
        function (res) {
          if (res.code == 200) {
            var result = res.results
            if (result.advancelist.length == 0) {
              // result.advancelist[0].timelist[0].times = that.data.scheduletime
              that.setData({
                advancelist: result.advancelist,
                // selectadvance: result.advancelist[0].dayid,
                isclose: result.isColse,
                storeType: result.storeType,
                advancetimeindex: 0,
                advancedayindex: 0,
                truedayindex: 0
              })
            } else {
              that.setData({
                advancelist: result.advancelist,
                appointexpect: result.advancelist[0].timelist[0].identifyTime,
                selectadvance: result.advancelist[0].dayid,
                isclose: result.isColse,
                storeType: result.storeType,
                advancetimeindex: 0,
                advancedayindex: 0,
                truedayindex: 0
              })
              if (
                that.data.advancelist[that.data.truedayindex].timelist[
                  that.data.advancetimeindex
                ].reserveflag == false
              ) {
                result.advancelist[0].timelist[0].times = that.data.scheduletime
                that.setData({
                  scheduleflag: false,
                  advancelist: result.advancelist
                })
              } else {
                that.setData({
                  scheduleflag: true
                })
              }
            }
          }
        },
        function (err) {
          wx.showToast({
            title: '失败'
          })
        }
      )
    }
  },
  // 餐具的积分规则
  takeRule: function () {
    var that = this
    var cardNumber = wx.getStorageSync('cardNumber')
    member.takePointsrule(
      baseUrl.baseUrl + '/mini/member-card/' + cardNumber + '/points-rule',
      {},
      {},
      '加载中',
      function (res) {
        var result = res.results
        if (!result && typeof result != 'undefined' && result != 0) {
          that.setData({
            ruleflag: false
          })
        } else {
          if (result.disable == 0 && result.isNoTablewareGifts == true) {
            that.setData({
              ruleflag: true,
              rulelist: result
            })
          } else {
            that.setData({
              ruleflag: false,
              rulelist: result
            })
          }
        }
      },
      function (err) {
        wx.showToast({
          title: '失败'
        })
      }
    )
  },
  takedistant: function () {
    var that = this
    wx.openLocation({
      //​使用微信内置地图查看位置。
      latitude: parseFloat(that.data.orderlist.storeLat), //要去的纬度-地址
      longitude: parseFloat(that.data.orderlist.storeLon) //要去的经度-地址
    })
  },
  // 微信支付
  payWechat: function () {
    var that = this

    return new Promise((resolve, reject) => {
      var memberId = wx.getStorageSync('memberId')
      order.takePayment(
        baseUrl.waimaiUrl +
        '/client/' +
        memberId +
        '/order/' +
        that.data.orderid +
        '/pay',
        {},
        {
          payType: 1
        },
        '加载中',
        function (res) {
          var result = res.results
          wx.requestPayment({
            timeStamp: result.timeStamp,
            nonceStr: result.nonceStr,
            package: result.prepayId,
            signType: result.signType,
            paySign: result.paySign,
            success: function (res) {
              that.payFlagShow = true
              wx.showToast({
                title: '支付成功',
                duration: 1000,
                mask: true,
                complete: function () {
                  setShoppingCart(that.data.storeCartKey, '')
                  setShoppingCart(
                    that.data.storeCartKey,
                    '',
                    _GLOBAL_UI_DATA_KEY
                  )
                  fhDeleteCartAll(memberId)
                  resolve()
                }
              })
              wx.requestSubscribeMessage(that.createNotifyOptions())
            },
            fail: function (res) {
              that.payFlagShow = true
              that.setData({
                payflag: false
              })
              wx.showToast({
                title: '取消支付',
                duration: 1000,
                success: function () { }
              })
              wx.reLaunch({
                url: '/order/list/index'
              })
              setShoppingCart(that.data.storeCartKey, '')
              setShoppingCart(that.data.storeCartKey, '', _GLOBAL_UI_DATA_KEY)
              fhDeleteCartAll(memberId)
              reject()
            }
          })
        },
        function (err) {
          that.payFlagShow = true
          const { message } = err
          wx.showToast({
            title: message || '您的网络开了个小差，请重新进入小程序后重试'
          })
          that.setData({
            payflag: false
          })
          reject()
        }
      )
    })
  },
  // 跳转备注
  goremrk: function () {
    var that = this
    wx.navigateTo({
      url: `/package/good/remarks/remarks?remarks=${that.data.remarker}`
    })
  },
  // 判断当前订单是不是群运营活动的
  computedActivityGroup() {
    const { from } = this.data
    return from === 'activityGroup'
  },
  // 友盟埋点
  umengTrack() {
    const { extraInfo = {} } = this.data
    const orders = wx.getStorageSync('groupFood') || [{}]
    const groupFlag = this.computedActivityGroup()
    const { focusGroupId } = extraInfo
    const { foodName, id, num } = orders[0]

    // 群运营订单提交订单
    if (groupFlag && focusGroupId && id) {
      wx.uma.trackEvent('click_dishe', {
        [`${focusGroupId}+${foodName}+${id}+submitOrder`]: num,
        submitOrder: `${focusGroupId}+${foodName}+${id}`
      })
      wx.uma.trackEvent('focus_group_submit_order', {
        focus_group_submit_order: `${focusGroupId}+${foodName}+${id}`,
        [`${focusGroupId}+${id}`]: num
      })
      const trackInfo = {
        focusGroupId,
        foodName,
        id
      }
      this.setData({ trackInfo })
    }
  },
  // 将两个地址合并
  assignAddress(oldAddr, newAddr) {
    newAddr = newAddr || {}
    const flag = this.computedActivityGroup()
    if (!newAddr && !flag) return
    const { addressDetail: houseNumber, id: sendId } = newAddr
    delete newAddr.addressDetail
    this.setData({
      'extraInfo.focusGroup': Object.assign({}, oldAddr, newAddr, {
        houseNumber,
        sendId
      })
    })
  },
  // 发送用户是否允许订阅消息
  async postWxMsg(accessTemplateIdList) {
    try {
      const { orderid } = this.data
      if (!orderid) return
      const memberId = wx.getStorageSync('memberId')
      await fhPostWxMsg(accessTemplateIdList, memberId, orderid)
    } catch (err) {
      console.log('axios postWxMsg error:', err)
    }
  },
  // 构建微信订阅消息的options
  createNotifyOptions() {
    const { notifyConfig } = wx.$env
    const { currentflag } = this.data
    const map = { 1: 'WAIMAI', 2: 'ZITI' }
    const tmplIds = notifyConfig[map[currentflag]]

    return {
      tmplIds,
      success: async res => {
        const acceptIds = _SUCCESS(res, tmplIds)
        if (typeof acceptIds !== 'string') {
          await this.postWxMsg(acceptIds)
        }
      },
      fail: _FAIL,
      complete: () => {
        wx.getSetting({
          withSubscriptions: true,
          success: async res => {
            const { subscriptionsSetting } = res
            const { mainSwitch, itemSettings } = subscriptionsSetting
            if (mainSwitch) {
              let tempIds = []
              for (let i in itemSettings) {
                if (itemSettings[i] === 'accept') {
                  tempIds.push(i)
                }
              }
              if (tempIds.length > 0) {
                await this.postWxMsg(tempIds)
              }
            }
          },
          complete: () => {
            this.navToSuccess()
          }
        })
      }
    }
  },
  // 下单成功后重定向
  navToSuccess() {
    setTimeout(() => {
      const { price, orderid, trackInfo } = this.data
      const other = `&from=activityGroup&trackInfo=${JSON.stringify(trackInfo)}`
      const flag = this.computedActivityGroup()
      //要延时执行的代码
      wx.reLaunch({
        url: `/package/good/successpage/successpage?price=${price}&orderid=${orderid}&type=shitang&${flag ? other : ''
          }`
      })
    }, 1000) //延迟时间
  },
  // 切换按钮状态
  switchChange({ currentTarget: { dataset }, detail }) {
    const { key } = dataset
    this.setData(
      {
        [key]: detail,
        extraInfo: {
          ...this.data.extraInfo,
          nurseDeliveryStatus: detail
        }
      },
      () => {
        this.onShow()
      }
    )
  },
  // 展示选择地址
  showAddressModal() {
    if (!this.data.address) {
      wx.$routerTo({
        url: '/pages/address/manage/index',
        query: {
          type: 'add'
        }
      })
      return
    }
    this.addressModal.showModal()
  },
  // 切换地址
  addressChange({ detail }) {
    wx.setStorageSync('addressid', detail.id)
    this.setData(
      {
        address: detail
      },
      () => {
        this.onShow()
      }
    )
  },
  // 确认订单请求结束
  confirmEnd(results) { },
  // 显示规则弹窗
  showRuleModal() {
    this.rulesModal.showPopup()
  },
  // 获取取货费减免活动信息
  async getReduceNurseDelivery() {
    try {
      const { results } = await fhGetReduceNurseDelivery()
      console.log('debug', results)
      // this.nurseDelivery = results
      this.setData({
        nurseDelivery: results
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  }
})
