import Vue from 'vue'
import {isBlank} from "@/utils/common";
export default {
  props: {
    label: {
      type: String,
      default: ''
    },
    prop: {
      type: String
    },
    required: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    readonly: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String
    },
    formModel: {
      type: Object
    },
    suffix: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: ''
    },
    editLabel:{
      type:String,
    }
  },
  data(){
    return {
      parent: null
    }
  },
  methods: {
    requireRule(required, label, type,trigger) {
      if(!trigger){
        trigger = 'blur'
      }
      const rules =  [{
        required: this.$parent.disabled? false:required,
        message: (!isBlank(this.editLabel)?this.editLabel:this.$t(label))+this.$t('common.requiredMsg'),
        trigger: [trigger]
      }]

      const regRule = {message: `${this.$t(label)}格式不正确`, trigger: ['blur','change']}
      if (type === 'phone') {
        regRule.pattern = /^[1][3,4,5,7,8][0-9]{9}$/
        rules.push(regRule)
      } else if (type === 'idCard') {
        regRule.pattern = /^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$/
        rules.push(regRule)
      }  else if (type === 'email') {
        regRule.pattern = /^[a-z0-9]+([._-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        rules.push(regRule)
      } else if (type === 'password'){
        regRule.pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}(?:(?!.*(\w)\1{2,}).)*(?:(?!.*sany).)*$/
        rules.push(regRule)
      }
      return rules
    }
  },
  created() {
    const getParent =(e)=>{
      if(e){
        return e.validate ? e : getParent(e.$parent)
      }
    }
    const parent = getParent(this.$parent)
    if(parent){
      this.parent = parent
      // 确保所有Form属性都是响应式的
      Vue.set(parent.model, this.prop, parent.model[this.prop]);
    }

  },
}
