const util = require('../../utils/util')

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    goods: { // 商品
      type: Object
		}
  },

  data: {
		curSpec: {},
		specName: [],
		specValue: []
  },

	observers: {
    goods: function(val) {
			if (val) {
				const { products, curSpec } = val
				let result = []
				const specs = products.map(p => p.specifications.join())
				const specName = specs[0].split(',').map(s => s.split(':')[0])
				const vList = specs.map(sp => sp.split(',').map(s => s.split(':')[1] ))
				
				vList.forEach(v => {
					v.forEach((d, i) => {
						const a = (result[i] = result[i] || [])
						if (a.findIndex(a => a == d) == -1) a.push(d)
					})
				})
				const curSpecValue = curSpec.specifications[0].split(',').map(s => s.split(':')[1])
				
				const specValue = result.map(res => res.map(name => ({ name, is_active: curSpecValue.findIndex(c => c == name) != -1 ? true : false })))
				this.setData({ specName, specValue, curSpec })
			}
		}
	},

  methods: {
    prevent() {
      return false
		},
		
		changeSpec({ currentTarget }) {
			const { index, nameindex } = currentTarget.dataset
			this.data.specValue[nameindex].map((spec, spec_i) => {
				spec.is_active = spec_i == index ? true : false
				return spec
			})
			this.setData({ specValue: this.data.specValue })

			const spec = this.data.specName.map((name, spec_index) => name + ':' + this.data.specValue[spec_index].filter(val => val.is_active)[0].name).join(',')
			const i = this.data.goods.products.findIndex(p => p.specifications.join() == spec)

			this.setData({ curSpec: this.data.goods.products[i] })
		},

    hideSpec() {
			this.setData({ goods: this.data.goods })
			this.triggerEvent('hideSpec')
		}
  }
})