<template>
  <div 
    :class="['bx-price',{'bx-price--deleted':deleted}]" 
    :style="fontStyle"
    >
    <span :style="frontFontStyle">{{ priceTextFront }}</span>
    <span>{{ priceTextEnd }}</span>
  </div>
</template>
<script>
import { create } from '../utils'

export default create({
  name: 'price',
  props: {
    // 价格数额
    price: {
      default: '0',
    },
    // 价格后缀单位
    suffix: {
      type: String,
      default: '元',
    },
    // 价格类型，默认1:1
    type: {
      type: String,
      default: 'normal',
    },
    // 是否精确到小数点后两位显示
    precise: {
      type: Boolean,
      default: true,
    },
    // 价格前缀
    prefix: {
      type: String,
      default: '',
    },
    // 字体大小
    fontsize: {
      type: String,
      default: '20',
    },
    // 颜色
    color: {
      type: String,
      default: '',
    },
    // 删除线
    deleted: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {}
  },
  computed: {
    priceText() {
      const val = parseFloat(this.price) || 0
      return this.toFixed(val)
    },
    priceTextFront() {
      return this.prefix + this.priceText.split('.')[0]
    },
    priceTextEnd() {
      const val = this.precise ? `.${this.priceText.split('.')[1] || '00'}` : ''
      return val + this.suffix
    },
    fontStyle() {
      const size = Number.isNaN(Number(this.fontsize))
        ? this.fontsize
        : `${this.fontsize}px`
      const color = this.deleted ? '' : this.color
      return {
        'font-size': size,
        color,
      }
    },
    frontFontStyle() {
      if (this.type === 'big') {
        const size = parseFloat(this.fontsize) * 2
        const fontsize = Number.isNaN(Number(this.fontsize))
          ? size + this.fontsize.replace(/[0-9.]/g, '')
          : `${this.fontsize * 2}px`
        return {
          'font-size': fontsize,
        }
      }
      return ''
    },
  },
  methods: {
    toFixed(value, decimal = 2) {
      // 四舍五入
      const symbol = value < 0 ? -1 : 1
      /* eslint-disable */
      const times = Math.pow(10, decimal)
      /* eslint-enable */
      let des = symbol * value * times + 0.5
      des = (symbol * parseInt(des, 10)) / times
      des = des.toFixed(decimal)
      return des
    },
  },
})
</script>
<style>
@import './index.css';
</style>
