<template>
	<c-fullbox>
		<el-input
			:id="id"
			ref="form-item"
			class="m-input-currency"
			:style="{'border-bottom': isShowRed ? `1px solid ${isShowRed}` : ''}"
			v-model="model"
			v-bind="$attrs"
			v-on="$listeners"
			v-bind:disabled="isDisable"
			:maxlength="maxlength"
			@blur="onBlur"
			@focus="focus"
			@change="handleChange"
		/>
		<template slot="footer" v-if="isShow.show">
			<el-tooltip :content="isShow.warning" placement="bottom" effect="light" popper-class="tooltip">
				<i :class="isShow.show ? 'el-icon-warning' : ''" style="margin-left: 10px;color: red;font-size: 16px;cursor: pointer;"></i>
			</el-tooltip>
		</template>
	</c-fullbox>
</template>

<script>
import BigNumber from "bignumber.js";
import commonDepend from "~/mixin/commonDepend.js";
import markSetShowRed from "~/components/business/componentMixins/markSetShowRed.js";

export default {
  inject: {
    root: {
      default: () => null
    }
  },
  mixins: [commonDepend, markSetShowRed],
  props: {
    value: {
      type: [String, Number, BigNumber],
      default: undefined
    },
    currency: {
      type: [String, Number],
      default: "ZH"
    },
    precision: {
      type: Number,
      default: 2
    },
    max: {
      type: [Number, String],
      default: 0
    },
    min: {
      type: [Number, String],
      default: 0
    },
    maxlength: {
      type: Number,
      default: 18
    },
    disabled: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ""
    },
    // 此对象为markset或者modifySet所在的对象,如果传了此对象可以标记当前对象下的字段为红色下划线
    markSetData: {
      type: Object,
      default: () => null
    },
    customModifykey: {
      type: String,
      default: null
    },
    isShow: {
      type: Object,
      default: () => ({
        show: false,
        warning: ""
      })
    }
  },
  data() {
    return {
      isOnBlur: true
    };
  },
  computed: {
    model: {
      get() {
        let orignalValue = this.value;

        // format currency
        let formatCurrencyValue = this.formatCurrency(orignalValue);

        return formatCurrencyValue;
      },
      set(newVal) {
				let newValFormat = this.formatValue(newVal);

				let formatNaNvalue = this.formatNaN(newValFormat);
				this.$emit('input', formatNaNvalue)
      }
    },
    mode() {
      return this.$store.state.Status.mode;
    },
    highlight() {
      return this.$store.state.Status.highlights.indexOf(this.id) !== -1;
    },
    isDisable() {
      return this.mode === "display" || this.disabled;
    },
		curPrecision() {
			if (this.currency === "KRW" || this.currency === "JPY") {
				return 0
			} else {
				return this.precision
			}
		}
  },
  watch: {
    disabled(newVal) {
      if (newVal) {
        this.resetValidate()
      }
    }
  },
  methods: {
    handleChange(newVal) {
      if (!this.customModifykey) {
        // 添加isModify属性
        this.changeModify();
      }
    },
    onBlur() {
      this.isOnBlur = true;
      // 此处为了解决当什么都没填时,默认给0.00
      if (typeof this.model === "undefined" || this.model.trim() === "") {
        this.model = "0";
      }
			this.model = this.formatCurrency(this.value);
			// 处理change事件回调
			let newValFormat = this.formatValue(this.value);
			let formatNaNvalue = this.formatNaN(newValFormat);
			this.$emit('change', formatNaNvalue)
			this.$emit('handleChange', formatNaNvalue)
    },
    focus() {
      this.isOnBlur = false;
    },
    formatCurrency(value) {
      if (
        value !== null &&
        value !== undefined &&
        (value === "" || value.toString())
      ) {
        if (this.isOnBlur) {
          if (value === "") {
            value = "0";
          }
          value = this.formatValue(value.toString());
          // 最大值和最小值判断
          if (this.max || this.min) {
            let valueNum = new BigNumber(value);
            if (this.max) {
              let max = this.max.toString();
              let maxNum = new BigNumber(max);
              if (valueNum.comparedTo(maxNum) == 1) {
                value = max;
              }
            }
            if (this.min) {
              let min = this.min.toString();
              let minNum = new BigNumber(min);
              if (valueNum.comparedTo(minNum) == -1) {
                value = min;
              }
            }
          }
          let sign = true;
          let array = [];
          if (value.charAt(0) == "-") {
            sign = false;
            array = value.slice(1).split(".");
          } else {
            array = value.split(".");
          }
          // 增加逗号
          var temp = "";
          while (array[0].length > 3) {
            temp =
              "," +
              array[0].substring(array[0].length - 3, array[0].length) +
              temp;
            array[0] = array[0].substring(0, array[0].length - 3);
          }
          temp = array[0] + temp;
          if (this.curPrecision == 0) {
            this.model = sign ? temp : "-" + temp;
            return sign ? temp : "-" + temp;
          }
          if (this.curPrecision <= 0) {
            temp = temp;
          } else if (array.length === 1) {
            // 没有小数位数,补全 0
            temp += ".";
            for (var i = 0; i < this.curPrecision; i++) {
              temp += "0";
            }
          } else if (array[1].length < this.curPrecision) {
            temp += "." + array[1];
            // 精度不足补全 0
            for (var i = array[1].length; i < this.curPrecision; i++) {
              temp += "0";
            }
          } else {
            temp += "." + array[1].substring(0, this.curPrecision);
          }
          // this.model = sign ? temp : "-" + temp;
          return sign ? temp : "-" + temp;
        } else {
          return this.formatValue(value);
        }
      }
      return this.value;
    },
    formatValue(value) {
      if (
        value !== null &&
        value !== undefined &&
        (value === "" || value.toString())
      ) {
        var temp = value
          .toString()
          .split(",")
          .join("");
        // 取出正负符号
        let sign = true;
        if (temp.charAt(0) == "-") {
          sign = false;
          temp = temp.slice(1);
				}
        // 以小数点开头的前面加 0
        if (temp.charAt(0) === ".") temp = "0" + temp;
        // 以0 为开头且后面不是小数点的去掉前面的 0
        if (temp.charAt(0) === "0" && temp.length > 1 && temp.charAt(1) !== ".")
					temp = temp.substring(1);
        // 日元只保留前面的数字
        if (this.curPrecision == 0) {
          var i = 0;
          while (i < temp.length) {
            if (!(temp.charAt(i) >= "0" && temp.charAt(i) <= "9")) break;
            i++;
          }
          temp = temp.substring(0, i);
        } else {
					// 输入整数位到最大整数位,不输入小数点,不允许输入
					let ind = this.maxlength - 1 - this.curPrecision;
					if (temp.charAt(ind) && temp.indexOf('.') == -1 ) {
						temp = temp.slice(0, ind)
					}
          // 其他币种取出前面整数和小数部分
          var i = 0;
          while (i < temp.length) {
            if (!((temp.charAt(i) >= "0" && temp.charAt(i) <= "9") || temp.charAt(i) === "."))
              break;
            	i++;
          }
          temp = temp.substring(0, i);
					var array = temp.split(".");
          if (this.curPrecision <= 0) {
            temp = array[0];
          } else if (array.length > 1 && array[1].length > 0) {
            temp = array[0] + "." + array[1].substring(0, this.curPrecision);
          } else if (array.length > 1 && array[1].length === 0) {
            temp = array[0] + "."; // 原来有小数点的地方也保留小数
          } else {
            temp = array[0];
          }
        }
        return sign ? temp : "-" + temp;
      }
      return value;
    },
		// 处理非数字或者是小数点后的0不够的时候补0
    formatNaN(value) {
      // if value is empty or it is a Not a Number, then set '0'
      if (!value || isNaN(value) || value === '-0.00') {
				value = '0'
			}
			value = this.formatPrecision(value)
      return value;
		},
		formatPrecision (value) {
			let valArr = value.split('.')
			let precis0 = valArr[0] ? valArr[0] : '0'
			let precis1 = valArr[1] ? valArr[1] : ''
			let val = ''
			if (this.curPrecision == 0) {
				val = precis0
			} else {
				if (precis1.length >= this.curPrecision) {
					val = precis0 + "." + precis1.substring(0, this.curPrecision);
				} else {
					val = precis0 + "." + precis1 + '0'.repeat(this.curPrecision - precis1.length)
				}
			}
			return val
		},
		formatSetValue(value) {
			// 判断小数点结束
			if (value.endsWith('.')) {
				if (this.currency === "KRW" || this.currency === "JPY") {
					value = value.substring(0, value.lastIndexOf('.'))
				} else {
					value = value + '00'
				}
			}
			// 判断小数点后一位结束的
			if (value.indexOf('.') > -1 && value.split('.').pop().length === 1) {
				if (this.currency === "KRW" || this.currency === "JPY") {
					value = value.substring(0, value.lastIndexOf('.'))
				} else {
					value = value + '0'
				}
			}
			// 判断小数点后一位结束的
			if (value.indexOf('.') === -1) {
				if (this.currency !== "KRW" && this.currency !== "JPY") {
					value = value + '.00'
				}
			}
      return value;
    }
  }
};
</script>

<style scpoed>
/* .el-input.highlight .el-input__inner{
      border-color: red;
    } */
.el-input.m-input-currency .el-input__inner {
  text-align: left;
}

.input-currency-left.el-input.m-input-currency .el-input__inner {
  text-align: left;
}
</style>