<template>
  <div class="info-layout">
    <edit
      :name="langAccount.info"
      @clickOper="handleOper('infoStatus')"
      :oper="infoStatus?langAccount.edit:langAccount.show"
      :isActive="infoStatus"
      class="container"
    >
      <div class="info" :class="{'info-en':language==='en'}" slot="show">
        <div class="s-tx">
          <p>{{langAccount.avatar}}</p>
          <div class="card-img avatar" :style="{backgroundImage: info.head? `url(${info.head})`:`#e6e6e6`}"></div>
        </div>
        <p><span>{{langAccount.account}}</span><span>{{info.userName||'--'}}</span></p>
        <p><span>{{langAccount.nickname}}</span><span>{{info.nickName||'--'}}</span></p>
        <p><span>{{langAccount.email}}</span><span>{{info.email||'--'}}</span></p>
      </div>
      <div class="info edit-info" :class="{'edit-en':language==='en','info-en':language==='en'}" slot="edit">
        <div class="info-left">
          <div class="i-tx">
            <p>{{langAccount.avatar}}</p>
            <div class="itx-con">
            <div class="card-img avatar" :style="{backgroundImage: info.head?`url(${info.head})`:'#e6e6e6'}"></div>
              <div class="btn choose">
                <input class="el-upload" ref="uploadInput" name="file" type="file" @change="update" alt="sadasdasd">
                <span>{{langAccount.select}}</span>
              </div>
              <p class="p-desc" v-for="(item,i) in langAccount.sinfo" :key="i">{{item}}</p>
            </div>
          </div>
          <p><span>{{langAccount.account}}</span><span>{{info.userName}}</span></p>
          <p>
            <span>{{langAccount.nickname}}</span>
            <input
              autofocus
              v-model="editinfo.nickName"
              :placeholder="langAccount.placeholder.nickname"
              class="nickname"
              maxlength="10"
              type="text"
            >
          </p>
          <p>
            <span>{{langAccount.email}}</span>
            <input
              autofocus
              v-model="editinfo.email"
              :placeholder="langAccount.placeholder.email"
              class="nickname"
              maxlength="40"
              type="text"
            >
          </p>
          <label class="check-con" @click="isReceive=!isReceive">
            <span class="check-box">
              <span class="checkbox-inner" :class="{'checkbox-inner-checked':isReceive}"></span>
            </span>
            <span style="font-size:14px;color:#000;" v-html="langAccount.isReceive"></span>
          </label>
          <div @click="saveNickName" class="btn parmary">{{langAccount.save}}</div>
        </div>
      </div>
    </edit>

    <edit
      :name="langAccount.address"
      @clickOper="handleOper('addressStatus')"
      :oper="addressStatus?langAccount.edit:langAccount.show"
      :isActive="addressStatus"
    >
      <div class="address" slot="show">
        <template v-if="address.shipName">
          <p>
            <span>{{address.shipName}}</span>
            <span>{{address.shipMobile}}</span>
          </p>
          <p class="p-desc">{{`${address.shipAreaPath}${address.shipAddress}`}}</p>
        </template>
        <template v-else>
          <p class="p-desc">{{language==='en'?'Not filled':'暂无信息'}}</p>
        </template>
      </div>
      <div class="address edit-address" slot="edit">
        <div class="input-con">
          <input type="text" maxlength="10" v-model="editAdd.shipName" :placeholder="langAccount.placeholder.name">
          <input type="text"  oninput="value=value.replace(/[^\d\-]/g,'')" maxlength='11' v-model="editAdd.shipMobile" :placeholder="langAccount.placeholder.phone">
        </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"
            maxlength="50"
            :placeholder="langAccount.placeholder.address"
          >
        </div>
        <div class="btn parmary" @click="uAddress">{{langAccount.save}}</div>
      </div>
    </edit>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import edit from '@/components/edit'
import { reg } from '@/util'
import citySelect from '@/components/citySelect'
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
}
export default {
  components: { edit, citySelect },
  computed: {
    ...mapState({
      info: state => state.user.info,
      langAccount: state => state.language.home.manage.account,
      language: state => state.language.current,
      langToast: state => state.language.home.toast,
      editinfo: state => cloneObj(state.user.info),
      token: state => state.user.token,
      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) : {})
      },
      address: state => state.user.address || {},
      editAdd: state => cloneObj(state.user.address) || {}
    })
  },
  data () {
    return {
      infoStatus: true,
      addressStatus: true,
      invoiceStatus: true,
      cInvoice: 'normal',
      tempSelect: '',
      isReceive: true,
      addre: []
    }
  },
  methods: {
    handleOper (type) {
      this[type] = !this[type]
    },
    getCurrentSelect (data) {
      this.tempSelect = data
    },
    async saveNickName () {
      if (!this.editinfo.nickName.trim()) {
        return this.$toast.show('warn', this.langToast['35'])
      }

      if (this.editinfo.email.trim() && !reg.email.test(this.editinfo.email)) {
        return this.$toast.show('warn', this.langToast['8'])
      }
      let res = await this.$http
        .post(
          '/user/updateUserDetail',
          {
            nickName: this.editinfo.nickName,
            email: this.editinfo.email || null,
            isNotice: Number(this.isReceive)
          },
          {
            headers: {
              token: this.token
            }
          }
        )
      let data = res.data
      if (data.code === 0) {
        this.infoStatus = true
        this.$store.dispatch('getInfo', {url: '/user/getUserInfo', name: 'info'})
      } else {
        this.$toast.show('warn', this.langToast[data.code], async () => {
          if (data.code === 3004) {
            await this.$store.dispatch('logout')
            this.$router.push({name: 'home'})
          }
        })
      }
    },

    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)
        params = {
          invoiceType,
          title,
          code
        }

        let checkStr = [
          {
            name: '发票抬头',
            En: 'Title',
            val: title
          },
          {
            name: '税务登记号',
            En: 'Code',
            val: code
          }
        ]
        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
        }
      }
      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
            }
          })
        })
    },
    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,
        id
      } = this.editAdd

      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
      }
      let checkStr = [
        {
          name: '详细地址',
          En: 'Detailed address',
          val: shipAddress
        },
        {
          name: '电话',
          En: 'Phone number',
          val: shipMobile
        },
        {
          name: '姓名',
          En: 'Name',
          val: shipName
        }
      ]
      if (!check(checkStr)) {
        return
      }

      let params = {
        shipAddress,
        shipAreaPath,
        province,
        city,
        shipMobile,
        shipName,
        id
      }
      this.$http
        .post('/user/updateAddress', params, {
          headers: {
            token: this.token
          }
        })
        .then(data => {
          this.addressStatus = true
          this.$store.dispatch('getInfo', {
            url: '/user/getReceiverInfo',
            name: 'address'
          })
        })
    },
    update (e) {
      let file = e.target.files[0]
      let type = file.type.toLowerCase()
      if (type !== 'image/jpeg' && type !== 'image/png') {
        return this.$toast.show('warn', this.langToast['36'])
      }

      let token = this.token
      let config = {
        headers: {
          token
        }
      } // 添加请求头
      var reader = new FileReader()
      reader.onload = async e => {
        let imgdata = e.target.result
        this.$http.post('/user/uploadHead', { imgdata }, config).then(data => {
          this.info.head = data.data.msg
          localStorage.setItem('info', JSON.stringify(this.info))
        })
      }
      reader.readAsDataURL(file)
    }
  },
  watch: {},
  mounted () {
    this.$store.dispatch('getInfo', {
      url: '/user/getReceiverInfo',
      name: 'address'
    })
    Object.keys(this.invoice2).length === 0 && this.$store.dispatch('getInvoice', {
      type: 2,
      params: {
        invoiceType: 2
      }
    })
    Object.keys(this.invoice3).length === 0 && this.$store.dispatch('getInvoice', {
      type: 3,
      params: {
        invoiceType: 3
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.info-layout {
  $theme-color: #1fe4dc;
  $border-color: #e7e7e7;
  $info-width: 120px;

  width: 90%;
  padding-bottom: 100px;
  input {
    appearance: none;
    line-height: 36px;
    height: 36px;
    border: solid 1px $border-color;
    padding-left: 10px;
    &:focus {
      border: solid 1px $theme-color;
    }
  }
  .btn {
    text-align: center;
    cursor: pointer;
  }
  .parmary {
    background-color: $theme-color;
    width: 126px;
    height: 36px;
    line-height: 36px;
    margin-top: 20px;
  }
  .choose {
    background-color: #ddd;
    color: #2d2d2d;
    width: 100px;
    line-height: 26px;
    height: 26px;
    font-size: 12px;
    margin: 12px 0 20px;
    &:hover{
      background: #1fe4dc;
    }
  }
  .info,
  .address,
  .invoice {
    margin-top: 20px;
    p {
      line-height: 36px;
      span {
        padding-right: 10px;
      }
    }
    .p-desc {
      color: #a0a0a0;
      line-height: 24px;
    }
    .card-img{
      font-size: 0;
      display: inline-block;
      cursor: pointer;
      background-position: center;
      background-size: auto 100%;
    }
    .avatar {
      width: 68px;
      height: 68px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.4);
      margin: 5px 0;
      background-size: cover;
      background-repeat: no-repeat;

    }
    .nickname {
      width: 250px;
    }
  }

  .info{
    .s-tx{
      position: relative;
      &>p{
        position: absolute;
        left: 0;
        top: 0;
      }
      .avatar{
        margin-left: 80px
      }
    }
    p{
      span{
        display: inline-block;
        &:first-of-type{
          width: 80px;
        }
      }
    }
  }

  .info-en{
    .s-tx{
      .avatar{
        margin-left: $info-width;
      }
    }
    p{
      span{
        &:first-of-type{
          width: $info-width;
        }
      }
    }
  }

  .edit-info {
    display: flex;
    .info-left {
      &>p{
        margin: 10px 0;
      }
      min-width: 210px;
      .i-tx{
        position: relative;
        &>p{
          position: absolute;
          left: 0;
          top: 0;
        }
        .itx-con{
          margin-left: 80px;
          font-size: 14px;
        }
      }
    }
    .choose {
      cursor: pointer;
      position: relative;
      .el-upload {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        line-height: 1;
        cursor: pointer;
        height: 100%;
        z-index: 10;
        width: 100%;
        padding: 0;
        margin: 0;
        font-size: 0;
        display: inline-block;
      }
      span {
        cursor: pointer;
      }
    }
  }

  .edit-en{
     .info-left {
      .i-tx{
        .itx-con{
          margin-left: $info-width;
        }
      }
    }
  }
  .edit-address {
    .input-con {
      input {
        width: 200px;
        line-height: 36px;
        height: 36px;
        margin: 10px 25px 10px 0;
      }
    }
    .address-input {
      input {
        width: 660px;
      }
    }
  }
  .edit-invoice {
    .select-con {
      div {
        position: relative;
        cursor: pointer;
        min-width: 230px;
        line-height: 36px;
        height: 36px;
        margin: 10px 25px 10px 0;
        border: solid 1px $border-color;
        color: #a0a0a0;
        padding: 0 10px;
        display: inline-block;
        img {
          display: none;
          position: absolute;
          bottom: 0;
          right: 0;
        }
      }
      .tag-active {
        border: solid 1px $theme-color;
        color: #000;
        img {
          display: inline-block;
        }
      }
    }
    .input-con {
      input {
        width: 316px;
        line-height: 36px;
        height: 36px;
        margin: 10px 25px 10px 0;
      }
    }
  }
}
@media screen and (min-width: 2000px) {
  .edit-layout {
    max-width: 75%!important;
  }
}
</style>
