<template>
  <div>
    <div class="cus-form" v-for="(field, key) in fields" v-if="!field.isHide">
      <!-- 输入表单组件 -->
      <co-field v-if="isInput(field.inputType)" :rows="field.rows" :label="field.name" :required="field.required" :placeholder="field.placeholder || ('请输入' + field.name)" :type="field.inputType" :state="field.state" :value="field.value" @input="(val) => { inputChange(val, key) }"></co-field>
      <!-- 选择表单组件 单选或者多选 -->
      <cus-form-select :options="field" :iconIndex="key" :value="field.value" v-if="isSelect(field.inputType)"  @input="(val) => { inputChange(val, key) }"></cus-form-select>
      <!-- 附件组件 -->
      <cus-form-appendix :options="field" :iconIndex="key" :value="field.value" v-if="field.inputType == 'appendix'"  @input="(val) => { inputChange(val, key) }"></cus-form-appendix>
      <!-- 地址选择或者调用原生能力 -->
      <cus-form-address :options="field" :iconIndex="key" :value="field.value" v-if="field.inputType == 'address'"  @input="(val) => { inputChange(val, key) }"></cus-form-address>
      <!-- 开关 switch -->
      <cus-form-switch :options="field" :iconIndex="key" :value="field.value" v-if="field.inputType == 'switch'"  @input="(val) => { inputChange(val, key) }"></cus-form-switch>
    </div>
  </div>
</template>

<script type="es6">

  export default {
    name: 'cus-form',
    data() {
      return {
        dateFormat: {
          'date': 'yyyy-MM-dd',
          'datetime': 'yyyy-MM-dd hh:mm',
          'yearmonth': 'yyyy-MM'
        }
      };
    },
    props: {
      fields: {
        type: Object,
        default: []
      }
    },
    methods: {
      isInput(type) {
        return !(this.isSelect(type) || type === 'appendix' || type === 'address' || type === 'switch');
      },
      isSelect(type) {
        return type === 'select' || type === 'multi' || this.isTime(type) || type === 'time' || type === 'year';
      },
      isTime(type) {
        return type === 'date' || type === 'datetime' || type === 'yearmonth';
      },
      inputChange(val, index) {
        let item = this.fields[index];
        if (item.inputType === 'select' || item.inputType === 'year') {
          this.fields[index].value = val.text;
          this.fields[index].valueCode = val.value;
        } else if (item.inputType === 'multi') {
          this.fields[index].value = val.map(x => x.text).join('，');
          this.fields[index].valueCode = val.map(x => x.value);
        } else if (this.isTime(item.inputType)) {
          this.fields[index].value = typeof val === 'object' ? val.format(this.dateFormat[item.inputType]) : val;
        } else if (item.inputType === 'address') {
          this.fields[index].value = val.address || '';
          this.fields[index].addressData = {
            'address': val.address || '',
            'province': val.province || '',
            'provinceCode': val.provinceCode || '',
            'city': val.city || '',
            'adname': val.adname || '',
            'adcode': val.adcode || '',
            'cityCode': val.cityCode || '',
            'longitude': val.longitude || '',
            'latitude': val.latitude || ''
          };
        } else {
          this.fields[index].value = val;
        }
        if (item.state) {
          this.validAndData('', index);
        }
        // 字段值修改时返回
        this.$emit('formInput', index, item);
      },
      validAndData(key, validIndex) {
        let fields = this.fields;
        let resultJson = {};
        let alertMessage = [];
        for (let field in fields) {
          let x = fields[field];
          if (validIndex && validIndex.length > 0) {
            if (field !== validIndex) {
              continue;
            }
          }
          if (x.isHide) {
            continue;
          }
          var value = x.value;
          var title = '请输入' + x.name;
          if (x.inputType === 'switch') {
            value = value || false;
          }
          if (x.inputType === 'select' || x.inputType === 'multi') {
            value = x.valueCode;
            title = '请选择' + x.name;
          }
          if (x.inputType === 'address') {
            value = x.addressData;
            title = '请选择' + x.name;
          }
          if (x.inputType === 'appendix') {
            value = x.value || [];
            title = '请上传' + x.name;
          }
          // 必填验证
          let isAlert = key === 'save' && alertMessage.length < 3;
          if (x.required === true && !(value && (value.length > 0 || value.address || value > 0)) && x.inputType !== 'switch') {
            isAlert && alertMessage.push('<p>' + (x.validHint || title) + '</p>'); // this.$messagebox.alert(x.validHint || title, '提示');
            this.fields[field].state = 'error';
            continue;
          }
          if ((x.inputType === 'textarea' || x.inputType === 'text' || x.inputType === 'tel' || x.inputType === 'number') && value && value.length > 0) {
            if (x.pattern && !new RegExp(x.pattern).test(value)) {
              isAlert && alertMessage.push('<p>' + (x.validHint || (x.name + '不符合验证规格，不能保存！')) + '</p>'); // this.$messagebox.alert(x.validHint || (x.name + '不符合验证规格，不能保存！'), '提示');
              this.fields[field].state = 'error';
              continue;
            } else {
              if (x.inputType === 'tel' && value && value.length > 0 && !(new RegExp('^([0-9]{1,})$').test(value))) {
                isAlert && alertMessage.push('<p>' + (x.validHint || (x.name + '只能为正整数，不能保存！')) + '</p>'); // this.$messagebox.alert(x.validHint || (x.name + '只能为1开头的数字，不能保存！'), '提示');
                this.fields[field].state = 'error';
                continue;
              }

              if (x.inputType === 'number' && value && value.length > 0 && !(new RegExp('^([0-9]{1,})$').test(value) || new RegExp('^([0-9]{1,}[.][0-9]*)$').test(value))) {
                isAlert && alertMessage.push('<p>' + (x.validHint || (x.name + '只能为正数，不能保存！')) + '</p>'); // this.$messagebox.alert(x.validHint || (x.name + '只能为正数，不能保存！'), '提示');
                this.fields[field].state = 'error';
                continue;
              }

              // 邮箱 、 身份证 、 。。。。。

              if (x.maxLength > 0 && value.length > x.maxLength) {
                isAlert && alertMessage.push('<p>' + (x.validHint || (x.name + '超过最大长度' + x.maxLength + '，不能保存！')) + '</p>'); // this.$messagebox.alert(x.validHint || (x.name + '超过最大长度' + x.maxLength + '，不能保存！'), '提示');
                this.fields[field].state = 'error';
                continue;
              }
            }
          }
          this.fields[field].state = 'success';
          resultJson[field] = value;
        }
        if (alertMessage.length > 0) {
          let alertMessageHtml = '';
          alertMessage.map(message => {
            alertMessageHtml += message;
          });
          this.$messagebox.alert(alertMessageHtml, '提示');
        }
        // true 为验证成功
        return alertMessage.length > 0 ? false : resultJson;
      },
      getFieldValue(field) {
        let item = this.fields[field];
        if (item.inputType === 'select' || item.inputType === 'year' || item.inputType === 'multi') {
          return item.valueCode;
        } else if (item.inputType === 'address') {
          return item.addressData;
        } else {
          return item.value;
        }
      },
      setFieldValue(field, value, cb) {
        // 单选 val = {'text': '', 'value': ''}
        // 多选 val = [{'text': '', 'value': ''}]
        // 地址 与地址类型中 addressData对象
        this.inputChange(value, field);
        if (typeof cb === 'function') {
          cb();
        }
      }
    }
  };
</script>
