<template>
  <div
    id="productBuilder"
    class="flex between stretch wrap">
    <template v-if="detail.id">
      <step1
        :loading="loading"
        :detail="detail"
        :priceData="priceData"
        :form2="form2"
        :preData="preData"
        @update-form="$event => updateForm($event, 1)"
        ref="step1"></step1>
      <step2
        :loading="loading"
        :detail="detail"
        :priceData="priceData"
        :cycle="form1.cycle"
        :preData="preData"
        @update-form="$event => updateForm($event, 2)"
        ref="step2"></step2>
      <step3
        :loading="loading"
        :detail="detail"
        :priceData="priceData"
        :weightInfo="weightInfo"
        :cycle="form1.cycle"
        :model="form1.model"
        :buyForm="form1.autoForm"
        :form2="form2"
        @check="checkForm"
        @update-form="$event => updateForm($event, 3)"
        ref="step3"></step3>
    </template>
    <div
      class="flex-auto flex center"
      v-else>
      <el-empty description="No Data"></el-empty>
    </div>
  </div>
</template>

<script>
import step1 from '@/components/product-builder/step-1'
import step2 from '@/components/product-builder/step-2'
import step3 from '@/components/product-builder/step-3'

export default {
  name: 'PageProductBuilder',
  components: {
    step1,
    step2,
    step3,
  },
  layout: 'product_builder_layout',
  async asyncData({ $axios, params }) {
    const detail = await $axios
      .get(`/au/goods/detail/${params.code}`)
      .catch(e => {
        console.log(e)
        return {}
      })
    let priceData = {}
    if (detail.result && detail.result.id) {
      priceData = await $axios
        .post('/quote/price', {
          id: detail.result.id,
        })
        .catch(e => {
          console.log(e)
        })
    }
    return {
      detail: detail.result || {},
      priceData: priceData.result || {},
    }
  },
  data() {
    return {
      // 商品详情数据
      detail: {},
      priceData: {},
      loading: false,
      // 用于3个step组件间互通数据
      form1: {},
      form2: {},
      form3: {},
      weightInfo: {},
      preData: {},
    }
  },
  head() {
    return {
      title: this.detail.product_name
        ? `Product Builder: ${this.detail.product_name}`
        : 'PromoCollection',
      meta: [
        { name: 'keywords', content: this.detail.main?.keywords },
        { name: 'description', content: this.detail.main?.seo_title },
      ],
    }
  },
  computed: {},
  beforeMount() {
    const preData = localStorage.getItem(
      `product-user-select-${this.$route.params.code}`
    )
    if (preData) {
      this.preData = JSON.parse(preData)
    }
  },
  mounted() {
    // 从页脚组件抄过来的. 运费计算需要里面的一些数据
    this.$axios.post('home/indexConfigWebsite', { site: 1 }).then(res => {
      this.$store.commit('config/setConfigInfo', res.result)
    })
    if (!this.detail.id) return
    this.$axios.post('/quote/weight', { id: this.detail.id }).then(res => {
      this.weightInfo = res.result
    })
  },
  methods: {
    checkForm(type) {
      this.loading = true
      Promise.all([
        this.$refs.step1.checkForm(),
        this.$refs.step2.checkForm(),
        this.$refs.step3.checkForm(),
      ])
        .then(res => {
          if (type === 2) {
            this.sendEnquiry(res)
          } else {
            this.addToProject(res)
          }
          // 点击按钮后删除从product页面带过来的数据
          this.preData = {}
          localStorage.removeItem(
            `product-user-select-${this.$route.params.code}`
          )
          this.loading = false
        })
        .catch(e => {
          console.log(e)
          this.$message.closeAll()
          this.$message.error('Please make sure to fill in the required fields')
          this.loading = false
        })
    },
    addToProject(res) {
      const temp = {
        cycle_id: res[0].cycle,
        price_unit_id: res[0].model,
        label_type: res[2].job,
        goods_id: this.detail.id,
        // 这个字段从product页面抄过来的, 本来就是空的, 不知道用来干嘛.
        decoration_id: '',
        // 以下3字段在后续逻辑赋值
        addition_ids: '',
        packaging_addition_ids: '',
        decoration_methods: [],
      }
      if (Array.isArray(res[1].packaging)) {
        temp.packaging_addition_ids = res[1].packaging.join(',')
      }
      if (Array.isArray(res[1].addon)) {
        temp.addition_ids = res[1].addon.join(',')
      }
      for (const key in res[1]) {
        if (/\d+/.test(key)) {
          const t = res[1][key].colorForm.filter(
            i => i.id === res[1][key].printService
          )

          temp.decoration_methods.push({
            colours_number: t.length ? t[0].colorNumber : 1,
            decoration_id: res[1][key].printService,
            price_unit_id: res[1][key].id,
          })
        }
      }

      this.$axios
        .post('/goods_cart/cartAdd', temp)
        .then(res => {
          console.log(res)
          if (res.code === 1) {
            this.$notify({
              title: 'success',
              message: 'Submitted successfully',
              type: 'success',
              duration: 3000,
            })
            // 天坑. 本页面用了不同的layout, 如果直接用router.push跳转会导致页面空白...
            location.href = location.origin + '/home/projects'
          }
        })
        .catch(e => {
          console.log(e)
        })
    },
    sendEnquiry(res) {
      const result = {
        product_code: this.detail.product_code,
        cycle_id: res[0].cycle,
        price_unit_id: res[0].model,
        supply_chain: res[0].supplyChain,
        decorated_in: res[0].decorated,
        address_id: res[2].defaultAddr.id,
        freight_type: res[2].freight_type || 1,
        // 目前没这功能, 暂时写死固定值
        transit_time: '2 Days',
        job_name: res[2].job || 'default_job',
        note: res[2].note || '',
        item: [],
        // addon: [], // 在后续逻辑赋值
        // decoration: [],
        // packaging: [],
      }
      const priceData = this.$refs.step3.computedPriceTableData
      result.item = res[0].autoForm.map(i => {
        const temp = {
          qty: i.value,
          colour: i.color,
          colour_type: 1,
          model: res[0].model,
          unit: priceData[0][`${i.value}_value`],
          set_up: priceData[1][`${i.value}_value`],
          print_option: priceData[2][`${i.value}_value`],
          addon: priceData[3][`${i.value}_value`],
          packaging: priceData[4][`${i.value}_value`],
          fright: priceData[5][`${i.value}_value`],
          sub_total: priceData[6][`${i.value}_value`],
        }
        if (i.color === 'Unspecified') temp.colour_type = 3
        if (i.color === 'PMS') {
          temp.colour_type = 2
          temp.colour = res[0].colorPmsText
        }
        if (i.colorId >= 0) temp.colour_id = i.colorId
        return temp
      })
      if (this.priceData.additionList) {
        if (this.priceData.additionList.addon) {
          const tempAddon = this.priceData.additionList.addon
            .filter(item => res[1].addon.includes(item.id))
            .map(item => {
              return {
                addition_id: item.id,
                addition_config: item.addition_code,
                addition_config_id: item.addition_config_id,
                image: '',
                name: item.name,
              }
            })
          if (tempAddon.length) result.addon = tempAddon
        }
        if (this.priceData.additionList.packaging) {
          const tempPackaging = this.priceData.additionList.packaging
            .filter(item => res[1].packaging.includes(item.id))
            .map(item => {
              return {
                addition_id: item.id,
                addition_config: item.addition_code,
                addition_config_id: item.addition_config_id,
                image: '',
                name: item.name,
              }
            })
          if (tempPackaging.length) result.packaging = tempPackaging
        }
      }
      const tempPrint = []
      for (const key in res[1]) {
        const target = res[1][key]
        if (/\d+/.test(key) && target.enable) {
          const v = {
            point: target.point,
            decoration_id: target.printService,
          }

          const decoration = target.decorationList.filter(
            i => i.id === target.printService
          )
          if (decoration.length) {
            v.price_type_id = decoration[0].price_type_id
            v.price_type_name = decoration[0].pricetype.name || ''
          }

          const formItem = target.colorForm.filter(
            i => i.id === target.printService
          )
          if (formItem.length) {
            v.pms = formItem[0].pmsColorText || ''
            v.max_color_count = formItem[0].colorNumber || 0
          }
          tempPrint.push(v)
        }
      }
      if (tempPrint.length) result.decoration = tempPrint
      // console.log(result)
      this.$axios
        .post('/order/add', result)
        .then(res => {
          console.log(res)
          if (res.code === 1) {
            this.$notify({
              title: 'success',
              message: 'Submitted successfully',
              type: 'success',
              duration: 3000,
            })
            // 对应的跳转页面还没开发.
            location.href = location.origin + '/product/' + `${this.detail.product_code}`
          }
        })
        .catch(e => {
          console.log(e)
        })
    },
    updateForm(data, step) {
      switch (step) {
        case 1:
          this.form1 = data
          break
        case 2:
          this.form2 = data
          break
        case 3:
          this.form3 = data
          break
      }
    },
  },
}
</script>

<style lang="scss" scoped>
#productBuilder {
  position: relative;
  width: 100%;
  div {
    box-sizing: border-box;
  }
}
</style>