<template>
  <div class="mobile-modal" v-if="showSayPriceBox">
    <div class="mobile-modal-box">
      <div class="mobile-modal-header">发布求购<i class="icon-guanbi iconfont" @click="cancel"></i></div>
      <div class="publish-seek">
        <div class="content-line">
          <span><i>*</i>型号：</span>
          <input type="text" v-model="applyObj.code" placeholder="请勿填中文符号">
        </div>
        <div class="content-line">
          <span><i>*</i>品牌：</span>
          <input type="text" v-model="applyObj.brand" placeholder="请勿填中文符号">
        </div>
        <div class="content-line">
          <span><i>*</i>截止日期：</span>
          <input type="date" v-model="applyObj.deadline" @change="deadlineChange">
        </div>
        <div class="content-line">
          <span>币种：</span>
          <a v-text="applyObj.currency" @click="showCurrencyList = !showCurrencyList"></a>
          <img v-if="!showCurrencyList" src="/images/mobile/@2x/applyPurchase/currency-arrow-down.png" alt="">
          <img v-if="showCurrencyList" src="/images/mobile/@2x/applyPurchase/currency-arrow-up.png" alt="">
          <ul v-if="showCurrencyList">
            <li @click="setCurrency('不限')">不限</li>
            <li @click="setCurrency('RMB')">RMB</li>
            <li @click="setCurrency('USD')">USD</li>
          </ul>
        </div>
        <div class="content-line">
          <span>数量：</span>
          <input type="number" v-model="applyObj.amount">
        </div>
        <div class="content-line">
          <span>生产日期：</span>
          <input type="text" v-model="applyObj.produceDate">
        </div>
        <a @click="goPublish">确认发布</a>
      </div>
    </div>
  </div>
</template>
<script>
  let formatDate = function (date, fmt) {
    if (typeof date === 'string') {
      date = new Date(Date.parse(date.replace(/-/g, '/')))
    }
    let o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': 23, // 小时
      'm+': 59, // 分
      's+': 59, // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      'S': date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  }
  let getRealLen = function (str) {
    let len = 0
    for (let i = 0; i < str.length; i++) {
      if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
        len += 2
      } else {
        len++
      }
    }
    return len
  }
  export default {
    props: ['showSayPriceBox'],
    data () {
      return {
        applyObj: {
          code: '',
          brand: '',
          unitPrice: '',
          currency: '不限',
          encapsulation: '',
          produceDate: '',
          amount: '',
          deadline: ''
        },
        showCurrencyList: false
      }
    },
    computed: {
      user () {
        return this.$store.state.option.user
      }
    },
    methods: {
      cancel: function () {
        this.$emit('cancelAction')
      },
      emptyForm: function () {
        for (let attr in this.applyObj) {
          this.applyObj[attr] = attr === 'currency' ? 'RMB' : ''
        }
      },
      setRemindText: function (str) {
        this.$emit('remindAction', str)
      },
      goPublish: function () {
        if (this.checkAll()) {
          let inquiry = {}
          let inquiryItem = {}
          if (this.user.data.enterprise) {
            inquiry.enUU = this.user.data.enterprise.uu
          }
          let date = new Date()
          inquiry.recorderUU = this.user.data.userUU
          inquiry.code = 'MALL' + date.getTime()
          inquiry.date = date
          inquiry.recorder = this.user.data.userName
          inquiry.endDate = formatDate(this.applyObj.deadline, 'yyyy-MM-dd hh:mm:ss')
          inquiry.sourceapp = 'MALL'
          inquiry.amount = 1
          inquiryItem.prodTitle = this.applyObj.code
          inquiryItem.userUU = this.user.data.userUU
          inquiryItem.source = 'MALL'
          inquiryItem.userName = this.user.data.userName
          inquiryItem.userTel = this.user.data.userTel
          inquiryItem.needquantity = this.applyObj.amount
          inquiryItem.inbrand = this.applyObj.brand
          inquiryItem.currency = this.applyObj.currency === '不限' ? null : this.applyObj.currency
          inquiryItem.cmpCode = (this.applyObj.code).toUpperCase()
          inquiryItem.unitPrice = this.applyObj.unitPrice
          inquiryItem.produceDate = this.applyObj.produceDate
          inquiryItem.date = date
          inquiryItem.endDate = this.applyObj.deadline
          inquiryItem.encapsulation = this.applyObj.encapsulation
          let inquiryItems = []
          inquiryItems.push(inquiryItem)
          inquiry.inquiryItems = inquiryItems
          this.$http.post('/inquiry/buyer/save', inquiry)
            .then(response => {
//              this.$message.success('发布成功')
              this.setRemindText('发布成功')
              //                this.showRemindBox = true
              this.emptyForm()
              //                this.validObj.deadline = true
              this.$emit('reloadAction')
              this.cancel()
            }, error => {
              console.log(error)
//              this.$message.error('发布失败')
              this.setRemindText('发布失败')
            })
        }
      },
      setCurrency: function (type) {
        this.applyObj.currency = type
        this.showCurrencyList = false
      },
      isValidDate: function (date) {
        let now = new Date().getTime()
        let time = new Date(formatDate(date, 'yyyy-MM-dd hh:mm:ss')).getTime()
        return !time || (time >= now && time <= now + 1000 * 60 * 60 * 24 * 91)
      },
      deadlineChange: function () {
        if (!this.isValidDate(this.applyObj.deadline)) {
//          this.$message.error('日期需不小于今天且在90天以内')
          this.setRemindText('日期需不小于今天且在90天以内')
          this.applyObj.deadline = ''
        }
      },
      checkAll: function () {
        return this.checkCode() && this.checkBrand() && this.checkDeadLine() && this.checkAmount() && this.checkProduceDate()
      },
      checkCode: function () {
        if (!this.applyObj.code) {
//          this.$message.error('型号不能为空')
          this.setRemindText('型号不能为空')
          return false
        } else if ((/[^\x00-\xff]/g).test(this.applyObj.code)) {
//          this.$message.error('型号不能包含中文及中文字符')
          this.setRemindText('型号不能包含中文及中文字符')
          return false
        } else if (getRealLen(this.applyObj.code) > 100) {
//          this.$message.error('型号不能超过100个字符')
          this.setRemindText('型号不能超过100个字符')
          return false
        } else {
          return true
        }
      },
      checkBrand: function () {
        let chineseIndex = -1
        if ((/[^\x00-\xff]/g).test(this.applyObj.brand)) {
          for (let i = 0; i < this.applyObj.brand.length; i++) {
            if ((/[^\x00-\xff]/g).test(this.applyObj.brand.charAt(i)) && !(/[\u4e00-\u9fa5]/).test(this.applyObj.brand.charAt(i))) {
              chineseIndex = i
              break
            }
          }
        }
        if (!this.applyObj.brand) {
//          this.$message.error('品牌不能为空')
          this.setRemindText('品牌不能为空')
          return false
        } else if (chineseIndex !== -1) {
//          this.$message.error('品牌不能包含中文字符')
          this.setRemindText('品牌不能包含中文字符')
          return false
        } else if (getRealLen(this.applyObj.brand) > 50) {
//          this.$message.error('品牌不能超过50个字符')
          this.setRemindText('品牌不能超过50个字符')
          return false
        } else {
          return true
        }
      },
      checkDeadLine: function () {
        if (!this.applyObj.deadline) {
//          this.$message.error('截止日期不能为空')
          this.setRemindText('截止日期不能为空')
        }
        return this.applyObj.deadline
      },
      checkAmount: function () {
        if (typeof this.applyObj.amount === 'undefined' || this.applyObj.amount === '') {
          return true
        } else {
          if (!(/^[0-9]*$/).test(this.applyObj.amount)) {
//            this.$message.error('请输入正确的数量')
            this.setRemindText('请输入正确的数量')
            return false
          } else if (this.applyObj.amount.length > 9) {
//            this.$message.error('数量不能大于999999999')
            this.setRemindText('数量不能大于999999999')
            return false
          } else {
            return true
          }
        }
      },
      checkProduceDate: function () {
        if (typeof this.applyObj.produceDate === 'undefined' || this.applyObj.produceDate === '') {
          return true
        } else {
          if (getRealLen(this.applyObj.produceDate) > 12) {
//            this.$message.error('生产日期不能大于12个字符')
            this.setRemindText('生产日期不能大于12个字符')
            return false
          } else {
            return true
          }
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .mobile-modal {
    .mobile-modal-box {
      .publish-seek {
        background: #fff;
        padding-top: .1rem;
        padding-bottom: .4rem;
        .content-line {
          height: .8rem;
          line-height: .8rem;
          font-size: .26rem;
          text-align: left;
          border-bottom: .02rem solid #b7d5fe;
          position: relative;
          input {
            width: 3.49rem;
            height: .52rem;
            padding-left: .19rem;
            border: .02rem solid #7e7e7e;
          }
          > span {
            display: inline-block;
            width: 1.76rem;
            text-align: right;
            i {
              color: #ff0000;
              margin-right: .05rem;
              font-style: normal;
            }
          }
          > a {
            font-size: .26rem;
            color: #666;
          }
          > img {
            width: .12rem;
            height: .06rem;
            margin-left: .04rem;
          }
          > ul {
            position: absolute;
            top: .6rem;
            left: 1.16rem;
            z-index: 1;
            width: 1.75rem;
            background: #fff;
            text-align: center;
            border-radius: .1rem;
            border: .02rem solid #dfdfdf;
            -webkit-box-shadow: 0 0 .12rem .02rem #e2d9d975;
            -moz-box-shadow:  0 0 .12rem .02rem #e2d9d975;
            box-shadow:  0 0 .12rem .02rem #e2d9d975;
            li {
              height: .52rem;
              line-height: .52rem;
              border-bottom: .02rem solid #dfdfdf;
              &:hover, &:active {
                background: #dedede;
              }
            }
          }
        }
        > a {
          display: block;
          width: 5.19rem;
          height: .84rem;
          text-align: center;
          line-height: .84rem;
          font-size: .38rem;
          margin: .3rem auto 0;
          background: #3f84f6;
          color: #fff;
          border-radius: .08rem;
        }
      }
    }
  }
</style>
