import HTTP from "../../../../requestFn/Api";
const app = getApp();
Page({

  data: {
    car_list: []
  },
  onLoad() {

  },
  onShow(options) {
    const {
      garden_id
    } = app.globalData;
    if (garden_id) {
      this.setData({
        garden_id
      })
      this.getMyCar()
    }
  },
  getMyCar() {
    const that = this;
    const {
      garden_id
    } = that.data;
    HTTP.GetuserCar({
      garden_id
    }).then(res => {
      wx.getStorage({
        key: "car_list",
        success(e) {
          if (res.list.length > e.data.length) {
            let id;
            e.data.map(item => {
              if (item.selected) {
                id = item.id
              }
            })
            const result = res.list.map(item => {
              if (item.id == id) {
                return {
                  ...item,
                  selected: true,
                  detail: `${item.brand}${item.seat}坐（${item.displacement}${item.displacement_unit}）`
                }
              } else {
                return {
                  ...item,
                  selected: false,
                  detail: `${item.brand}${item.seat}坐（${item.displacement}${item.displacement_unit}）`
                }
              }
            })
            that.setData({
              car_list: result
            })
            wx.setStorage({
              data: result,
              key: "car_list"
            })
          } else {
            that.setData({
              car_list: e.data
            })
          }
        },
        fail() {
          const result = res.list.map((item, index) => {
            if (index == 0) {
              return {
                ...item,
                selected: true,
                detail: `${item.brand}${item.seat}坐（${item.displacement}${item.displacement_unit}）`
              }
            } else {
              return {
                ...item,
                selected: false,
                detail: `${item.brand}${item.seat}坐（${item.displacement}${item.displacement_unit}）`
              }
            }
          })
          that.setData({
            car_list: result
          })
          wx.setStorage({
            data: result,
            key: "car_list"
          })
        }
      })

    })
  },
  myCar(e) {
    const {
      id
    } = e.currentTarget;
    const {
      car_list
    } = this.data;
    let newArr = car_list.map(item => {
      if (item.id == id) {
        return {
          ...item,
          selected: true
        }
      } else {
        return {
          ...item,
          selected: false
        }
      }
    })
    wx.setStorage({
      data: newArr,
      key: "car_list"
    })
    this.setData({
      car_list: newArr
    })
  },
})