<template>
  <div>
    <div class="detail-layout" ref="detaillayout">
      <div class="detail-header">
        <div class="c-title">确认订单</div>
        <i v-if="fromList" @click="backHandle" class="iconfont icon-shang"></i>
        <i @click="closeHandle" class="iconfont right icon-cuowu"></i>
      </div>
      <edit
        :name="'收货信息'"
        @clickOper="handleOper('addressStatus')"
        :oper="addressStatus?'编辑':'收起'"
        :isActive="addressStatus"
        class="edit-item"
      >
        <div class="address show-address" slot="show">
          <img :src="`${$cdn}images/address-icon.png`" alt>
          <template v-if="address.shipName">
            <div>
              <p>{{address.shipName}}</p>
              <p class="p-desc">{{`${address.shipAreaPath}${address.shipAddress}`}}</p>
            </div>
          </template>
          <template v-else>
            <div class="p-desc no-info">暂无信息</div>
          </template>
        </div>
        <div class="address edit-address" slot="edit">
          <div class="input-con">
            <input type="text" v-model="editAdd.shipName" :placeholder="'姓名'">
            <input type="text" v-model="editAdd.shipMobile" :placeholder="'电话'">
          </div>
          <div class="input-con">
            <citySelect :areaPath="editAdd.shipAreaPath" @currentVal="getCurrentSelect"/>
          </div>
          <div class="input-con address-input">
            <input
              type="text"
              v-model="editAdd.shipAddress"
              :placeholder="'详细地址'"
            >
          </div>
          <div class="btn parmary" @click="uAddress">保存</div>
        </div>
      </edit>
      <edit
        :name="'我的发票抬头'"
        @clickOper="handleOper('invoiceStatus')"
        :oper="invoiceStatus?'编辑':'收起'"
        :isActive="invoiceStatus"
        class="edit-item"
        style="padding:0 30px 20px"
      >
        <div class="invoice invoice-address" slot="show">
          <div class="select-con">
            <div :class="{'tag-active':invoice==='noinvoice'}" @click="invoice='noinvoice'">
              <span>不需要发票</span>
              <img :src="`${$cdn}images/tag-icon.png`" alt>
            </div>
            <div :class="{'tag-active':invoice==='normal'}" @click="invoice='normal'">
              <span>增值税普票（电子发票）</span>
              <img :src="`${$cdn}images/tag-icon.png`" alt>
            </div>
            <div :class="{'tag-active':invoice==='zengzhi'}" @click="invoice='zengzhi'">
              <span>增值税专用发票</span>
              <i></i>
              <img :src="`${$cdn}images/tag-icon.png`" alt>
            </div>
          </div>
          <div class="invoice-detail" v-if="invoice==='normal'">
            <template v-if="!invoice2.title">
              <p class="p-desc">暂无信息</p>
            </template>
            <template v-else>
              <p>{{invoice2.title}}</p>
              <p class="p-desc">{{invoice2.code}}</p>
              <p class="p-desc">{{invoice2.emailAddress}}</p>
            </template>
          </div>
          <div class="invoice-detail" v-if="invoice==='zengzhi'">
            <template v-if="!invoice3.title">
              <p class="p-desc">暂无信息</p>
            </template>
            <template v-else>
              <p>{{invoice3.title}}</p>
              <p class="p-desc">{{invoice3.code}}</p>
              <p class="p-desc">{{invoice3.organizedAddress}}</p>
              <p class="p-desc">{{invoice3.registerPhone}}</p>
              <p class="p-desc">{{invoice3.bankName}}</p>
              <p class="p-desc">{{invoice3.bankAccount}}</p>
            </template>
          </div>
        </div>
        <div class="invoice edit-invoice" slot="edit">
          <div class="select-con">
            <div :class="{'tag-active':invoice==='normal'}" @click="invoice='normal'">
              <span>增值税普票（电子发票）</span>
              <img :src="`${$cdn}images/tag-icon.png`" alt>
            </div>
            <div :class="{'tag-active':invoice==='zengzhi'}" @click="invoice='zengzhi'">
              <span>增值税专用发票</span>
              <i></i>
              <img :src="`${$cdn}images/tag-icon.png`" alt>
            </div>
          </div>
          <div class="invoice-input" v-if="invoice==='normal'">
            <div class="input-con">
              <input type="text" placeholder="请输入发票抬头" maxlength="20" v-model="editInvoice2.title">
              <input type="text" placeholder="请输入18位税务登记号" oninput="value=value.replace(/[^\w\.\/]/ig,'')" maxlength='18' v-model="editInvoice2.code">
            </div>
            <div class="input-con">
              <input type="text" placeholder="请输入电子邮箱" maxlength="30" v-model="editInvoice2.emailAddress">
            </div>
          </div>
          <div class="invoice-input" v-if="invoice==='zengzhi'">
            <div class="input-con">
              <input type="text" v-model="editInvoice3.title" maxlength="20" placeholder="请输入发票抬头">
              <input type="text" maxlength='18' v-model="editInvoice3.code" oninput="value=value.replace(/[^\w\.\/]/ig,'')" placeholder="请输入18位税务登记号">
            </div>
            <div class="input-con">
              <input type="text" maxlength="100" v-model="editInvoice3.organizedAddress" placeholder="注册地址">
              <input type="text" maxlength="20" oninput="value=value.replace(/[^\d\-]/g,'')" v-model="editInvoice3.registerPhone" placeholder="注册电话">
            </div>
            <div class="input-con">
              <input type="text" maxlength="40" v-model="editInvoice3.bankName" placeholder="开户银行">
              <input type="text" maxlength="40" v-model="editInvoice3.bankAccount" placeholder="银行账户">
            </div>
          </div>
            <div @click="saveInvoice(invoice)" class="btn parmary">保存</div>
        </div>
      </edit>
      <div class="express-type">
        <div class="title">物流方式</div>
        <img class="express-img" :src="`${$cdn}images/sf-express.png`" alt>
      </div>
      <div class="product-type">
        <div class="title">商品信息</div>
        <div class="p-info" v-for="(item,i) in sku" :key="i">
          <div class="p-img">
            <div class="pi-con">
              <img :src="pictures[item.goodsId]">
            </div>
          </div>
          <div class="p-params">
            <h3>{{cameraName[item.goodsId]}}</h3>
            <ul>
              <li v-for="(sub,i) in detail[item.goodsId]" :key="i">
                <span>{{sub}}</span>
                <span style="margin-left:5px;">x{{item.goodsCount}}</span>
              </li>
            </ul>
          </div>
          <div>
            <div class="numAP">
              <i :class="{fobid:item.goodsCount<=1}" @click="operNum(item,'-')">-</i>
              <span>{{item.goodsCount}}</span>
              <i @click="operNum(item,'+')">+</i>
            </div>
            <div v-if="cannotdel['id']===item.goodsId&&cannotdel['status']" class="error-txt"><span>至少要购买1件</span></div>
          </div>
          <div class="oper">
            <span @click="rmItem(item)">移除</span>
          </div>
          <div class="p-price"><span>￥ {{item.price*item.goodsCount}}</span></div>
        </div>
        <div class="p-detail">
          <div>
            <span>商品总价：</span>
            <span>￥{{getSum()[1]}}</span>
          </div>
          <div>
            <span>税费及其他费用：</span>
            <span>￥0</span>
          </div>
          <div>
            <span>运费：</span>
            <span>￥0</span>
          </div>
          <div>
            <span>合计：</span>
            <span>￥{{getSum()[1]}}</span>
          </div>
        </div>
        <div class="p-pay">
          <div class="agree" @click="handleCluse">
            <span>
              <img v-if="showCluse" :src="`${$cdn}images/icon-click.png`" alt="">
            </span>
            <!-- <router-link class="jump-a" target="_blank" :to="{name: 'service_list', params: {id: 'clause', active: 'pro'}}">同意四维看看销售协议</router-link> -->
            <span>同意四维看看销售协议</span>
          </div>
          <div class="c-button purchase" :style="{backgroundColor:showCluse?'#1fe4dc':'#e2e2e2'}" @click="pay">付款</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import vcenter from '@/components/vcenter'
import edit from '@/components/edit'
import citySelect from '@/components/citySelect'
import { mapState } from 'vuex'
import { reg } from '@/util'

var cloneObj = function (obj) {
  var newObj = {}
  if (obj instanceof Array) {
    newObj = []
  }
  for (var key in obj) {
    var val = obj[key] || ''
    newObj[key] = typeof val === 'object' ? cloneObj(val) : val
  }
  return newObj
}

let cameraName = {
  7: `四维看看 三脚架套装`,
  1: `四维看看 Lite二目相机`,
  4: `四维看看 Pro八目相机`
}

let cameraNameEn = {
  7: `4D KanKan Pro Tripod Set`,
  1: `四维看看 Lite二目相机`,
  4: `4DKanKan Pro Camera`
}
let detail = {
  7: ['四维看看 三脚架套装(标准色)'],
  1: [
    '四维看看 Lite二目相机(静谧黑)',
    '容量套餐(5G)',
    '四维看看 Lite专用三脚架(标准色)'
  ],
  4: ['四维看看 Pro八目相机(静谧黑)', '容量套餐(10G)']
}
let detailEn = {
  7: ['4D KanKan Pro Tripod Set (Standard)'],
  1: [
    '四维看看 Lite二目相机(静谧黑)',
    '容量套餐(5G)',
    '四维看看 Lite专用三脚架(标准色)'
  ],
  4: ['4DKanKan Pro Camera (Night Sky Black)', 'Storage Plan (10G)']
}
export default {
  props: ['psku', 'fromList', 'active'],
  data () {
    let pictures = {
      7: `${this.$cdn}images/zhijia.png`,
      1: `${this.$cdn}images/withzhijia.png`,
      4: `${this.$cdn}images/banner_pro.png`
    }

    return {
      showCluse: true,
      pictures,
      addressStatus: true,
      tempSelect: '',
      invoiceStatus: true,
      invoice: 'noinvoice',
      paytype: 0,
      cannotdel: {
        id: '',
        status: false
      }
    }
  },
  components: {
    vcenter,
    edit,
    citySelect
  },
  watch: {
    active (newVal) {
      this.$refs.detaillayout.scroll(0, 0)
    }
  },
  computed: {
    ...mapState({
      cameraName: state => {
        return state.language.current === 'en' ? cameraNameEn : cameraName
      },
      detail: state => {
        return state.language.current === 'en' ? detailEn : detail
      },
      invoice2: state => {
        let type = Object.prototype.toString.call(state.user.invoice2)
        if (type === '[object Object]') {
          return state.user.invoice2
        }
        let condition = state.user.invoice2 && state.user.invoice2 !== 'null' && type !== '[object Array]'
        return (condition ? JSON.parse(state.user.invoice2) : {})
      },
      editInvoice2: state => {
        let type = Object.prototype.toString.call(state.user.invoice2)
        if (type === '[object Object]') {
          return state.user.invoice2
        }
        let condition = state.user.invoice2 && state.user.invoice2 !== 'null' && type !== '[object Array]'
        return cloneObj(condition ? JSON.parse(state.user.invoice2) : {})
      },
      invoice3: state => {
        let type = Object.prototype.toString.call(state.user.invoice3)
        if (type === '[object Object]') {
          return state.user.invoice3
        }
        let condition = state.user.invoice3 && state.user.invoice3 !== 'null' && type !== '[object Array]'

        return (condition ? JSON.parse(state.user.invoice3) : {})
      },
      editInvoice3: state => {
        let type = Object.prototype.toString.call(state.user.invoice3)
        if (type === '[object Object]') {
          return state.user.invoice3
        }
        let condition = state.user.invoice3 && state.user.invoice3 !== 'null' && type !== '[object Array]'
        return cloneObj(condition ? JSON.parse(state.user.invoice3) : {})
      },
      token: state => state.user.token,
      address: state => state.user.address || {},
      langToast: state => state.language.home.toast,
      editAdd: state => cloneObj(state.user.address) || {},
      language: state => state.language.current
    }),
    sku () {
      return this.psku
    }
  },
  methods: {
    handleCluse () {
      this.showCluse = !this.showCluse
      this.$bus.$emit('openClause', {
        show: this.showCluse,
        type: 'cart'
      })
    },
    rmItem (item) {
      let arr = []
      this.sku.forEach(sub => {
        if (sub.goodsId !== item.goodsId) {
          arr.push(sub)
        }
      })
      arr.length <= 0 ? this.$toast.show('warn', this.langToast['14']) : this.$toast.showConfirm('warn', this.langToast['15'], () => {
        this.$emit('fixSku', arr)
      })
    },
    operNum (item, type) {
      if (item.goodsCount <= 1 && type === '-') {
        this.cannotdel = {
          id: item.goodsId,
          status: true
        }
      } else {
        let arr = []
        this.sku.forEach(sub => {
          if (sub.goodsId === item.goodsId) {
            sub['goodsCount'] = type === '+' ? ++item.goodsCount : --item.goodsCount
          }
          arr.push(sub)
        })
        this.cannotdel = {
          id: item.goodsId,
          status: false
        }
        this.$emit('fixSku', arr)
      }
    },
    backHandle () {
      this.$emit('backList')
    },
    closeHandle () {
      this.$bus.$emit('hideAside')
    },
    handleOper (type) {
      if (type === 'invoiceStatus') {
        this.invoice === 'noinvoice' ? this[type] = true : this[type] = !this[type]
      } else {
        this[type] = !this[type]
      }
    },
    uAddress () {
      this.editAdd.province = this.tempSelect[0]
      this.editAdd.city = this.tempSelect[1]
      this.editAdd.shipAreaPath = this.tempSelect.join(',')
      let {
        shipAddress,
        shipAreaPath,
        province,
        city,
        shipMobile,
        shipName
      } = this.editAdd
      let params = {
        shipAddress,
        shipAreaPath,
        province,
        city,
        shipMobile,
        shipName
      }
      this.$http
        .post('/user/updateAddress', params, {
          headers: {
            token: this.token
          }
        })
        .then(data => {
          this.addressStatus = true
          this.$store.dispatch('getInfo', {
            url: '/user/getReceiverInfo',
            name: 'address'
          })
        })
    },
    getCurrentSelect (data) {
      this.tempSelect = data
    },
    getSum () {
      let sum = 0
      let count = 0
      this.sku.forEach(item => {
        sum += item.goodsCount * item.price
        count += item.goodsCount
      })
      return [count, sum]
    },
    async pay () {
      if (!this.showCluse) {
        return
      }
      if (!this.invoiceStatus) {
        return this.$toast.show('warn', this.langToast['17'])
      }
      if (!this.addressStatus) {
        return this.$toast.show('warn', this.langToast['18'])
      }

      if (this.invoice === 'normal' && !this.invoice2.title) {
        return this.$toast.show('warn', this.langToast['20'])
      }

      if (this.invoice === 'zengzhi' && !this.invoice3.title) {
        return this.$toast.show('warn', this.langToast['20'])
      }

      if (!this.address.shipName) {
        return this.$toast.show('warn', this.langToast['19'])
      }

      let invoice = this.invoice === 'normal' ? this.invoice2 : this.invoice === 'zengzhi' ? this.invoice3 : null
      if (invoice) {
        invoice['invoiceType'] = invoice['type']
      }
      let params = {
        goods: this.sku,
        receiver: this.address,
        invoice: invoice,
        payType: this.paytype,
        abroad: this.language === 'en' ? 1 : 0
      }
      let res = await this.$http
        .post('user/order/placeOrder', params, {
          headers: {
            token: this.token
          }
        })
      this.$bus.$emit('hideAside')
      this.$store.dispatch('getCart')
      this.$router.push({name: 'pay',
        params: {
          payType: this.paytype,
          orderId: res.data.data.id,
          orderType: 0,
          orderSn: res.data.data.orderSn
        }})
    },
    saveInvoice (cInvoice) {
      let isObject = function (obj) {
        return JSON.stringify(obj) === '{}' ? '' : obj
      }
      let params = {}
      let invoiceType = ''
      let check = value => {
        for (let i = 0, len = value.length; i < len; i++) {
          if (!value[i].val) {
            return this.$toast.show('warn', (this.language === 'en' ? value[i].En : value[i].name) + this.langToast['7'])
          }
        }
        return true
      }

      if (cInvoice === 'normal') {
        invoiceType = 2

        let title = isObject(this.editInvoice2.title)
        let code = isObject(this.editInvoice2.code)
        let emailAddress = isObject(this.editInvoice2.emailAddress)

        if (code && code.length !== 18) {
          return this.$toast.show('warn', this.langToast['21'])
        }
        if (!reg.email.test(emailAddress)) {
          return this.$toast.show('warn', this.langToast['8'])
        }
        params = {
          invoiceType,
          title,
          code,
          emailAddress
        }

        let checkStr = [
          {
            name: '发票抬头',
            En: 'Title',
            val: title
          },
          {
            name: '电子邮箱',
            En: 'Email',
            val: emailAddress
          }
        ]
        if (!check(checkStr)) {
          return
        }
      } else {
        let {title: title1, code: code1, organizedAddress: organizedAddress1, registerPhone: registerPhone1, bankName: bankName1, bankAccount: bankAccount1} = this.editInvoice3
        invoiceType = 3
        let title = isObject(title1)
        let code = isObject(code1)
        let organizedAddress = isObject(organizedAddress1)
        let registerPhone = isObject(registerPhone1)
        let bankName = isObject(bankName1)
        let bankAccount = isObject(bankAccount1)

        params = {
          invoiceType,
          title,
          code,
          organizedAddress,
          registerPhone,
          bankName,
          bankAccount
        }
        let checkStr = [
          {
            name: '发票抬头',
            En: 'Title',
            val: title
          },
          {
            name: '税务登记号',
            En: 'Code',
            val: code
          },
          {
            name: '注册地址',
            En: 'Organized Address',
            val: organizedAddress
          },
          {
            name: '注册电话',
            En: 'Register Phone',
            val: registerPhone
          },
          {
            name: '开户银行',
            En: 'Bank Name',
            val: bankName
          },
          {
            name: '银行账号',
            En: 'Bank Account',
            val: bankAccount
          }
        ]
        if (!check(checkStr)) {
          return
        }
        if (!code || code.length !== 18) {
          return this.$toast.show('warn', this.langToast['21'])
        }

        if (!reg.guhua.test(registerPhone)) {
          return this.$toast.show('warn', this.langToast['22'])
        }
      }

      this.$http
        .post('user/invoice/save', params, {
          headers: {
            token: this.token
          }
        })
        .then(data => {
          this.invoiceStatus = true
          this.$store.dispatch('getInvoice', {
            type: invoiceType,
            params: {
              invoiceType: invoiceType
            }
          })
        })
    }
  },
  mounted () {
    this.$bus.$on('isAgree', data => {
      this.showCluse = data
    })
    if (this.address && Object.keys(this.address).length > 0) return
    this.$store.dispatch('getInfo', {
      url: '/user/getReceiverInfo',
      name: 'address'
    })
  }
}
</script>

<style lang="scss" scoped>
@import "./detail.scss";
</style>
