<template>
  <div>
    <el-dialog
      title="宝宝信息"
      custom-class="customer-dialog baby-info-dialog"
      :visible.sync="visible"
      :close-on-click-modal="false"
      @close="cancel"
      width="480px"
      :picker-options="pickerOptions()"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="(item,index) in fieldsList"
          :key="index"
          :label="`宝宝${index + 1}${item['k20301'] ? `（${item['k20301']}）`: '' }`"
          :name="`${index}`"
        >
          <el-form
            ref="form"
            :model="item.form"
            label-width="122px"
          >
            <el-form-item v-for="item in babyConfigTemplate.template" :key="item.unifiedIdentification" :label="item.fieldName+ '：'" :prop="item.unifiedIdentification" :rules="getRules(item)">
              <el-input
                v-if="item.fieldType == 0"
                v-model="fieldsList[activeName].form[item.systemFieldId]"
                :placeholder="item.fieldDescription"
                type="text"
                :show-word-limit="item.unifiedIdentification == 'k20301'"
                :maxlength="item.limitCountMax"
                :class="{'baby-name': item.unifiedIdentification == 'k20301'}"
                :style="{width: item.unifiedIdentification == 'k20301' ? '300px' : '160px'}"
              />
              <el-date-picker
                v-if="item.fieldType == 4"
                :placeholder="item.fieldDescription"
                style="width: 160px;"
                value-format="yyyy-MM-dd"
                v-model="fieldsList[activeName].form[item.systemFieldId]"
                type="date"
                :picker-options="pickerOptions()"
              />
              <el-select v-if="item.fieldType == 2" :placeholder="item.fieldDescription" v-model="fieldsList[activeName].form[item.systemFieldId]" style="width: 160px;">
                <el-option v-for="(el, index) in JSON.parse(item.fieldContent.replaceAll('\'', '&quot;'))" :key="index" :label="el.name" :value="el.name" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button @click="$emit('update:dialogVisible', false)">取消</el-button>
        <el-button type="primary" @click="onSave" :loading="loading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { doFetch } from '../../axios/api';
import url from '../../axios/url';
export default {
  name: 'BabyinfoDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    childFieldsList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    babyConfigTemplate: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      visible: false,
      fieldsList: [],
      activeName: '0',
      loading: false,
      pickerOptions() {
        // let pickerMinDate;
        return {
          onPick(obj) {
            // pickerMinDate = obj.minDate;
          },
          disabledDate(time) {
            let start = new Date();
            start.setFullYear(start.getFullYear() - 20);
            start.setDate(start.getDate() + 1);
            start = new Date(`${start.getFullYear()}-${start.getMonth() + 1}-${start.getDate()}`);
            let end = new Date();
            end = new Date(`${end.getFullYear()}-${end.getMonth() + 1}-${end.getDate()} 23:59:59`);
            return time.getTime() < start.getTime() || time.getTime() > end;
          }
        };
      }
    };
  },
  watch: {
    dialogVisible (n, o) {
      this.visible = n;
      if (n) {
        const fieldList = this.childFieldsList.map(el => {
          el.form = {
            'k20301': '',
            'k20302': '',
            'k20303': '',
            'k20304': '',
            'k20305': '',
            'k20306': '',
          };
          el.sonFields.forEach(field =>  {
            el.form[field.unifiedIdentification] = field.fieldValue || '';
            el[field.unifiedIdentification] = field.fieldValue || '';
          });
          return el;
        });
        this.fieldsList = JSON.parse(JSON.stringify(fieldList));
        let formRef = this.$refs.form
        if(Array.isArray(formRef)) {
          formRef.forEach(el => {
            el.clearValidate();
          })
        } else if(formRef) {
          formRef.clearValidate();
        }
      }
    },
  },
  methods: {
    async onSave() {
      let formRefs = this.$refs.form;
      if(Array.isArray(formRefs)) {
        for(let i = 0; i < formRefs.length; i++) {
          let valid = await formRefs[i].validate().catch(() => {
            this.$message.error(`宝宝${i+1}信息填写错误`);
          })
          if(!valid) return;
        }
      } else if(formRefs) {
        let valid = await formRefs.validate();
        if(!valid) return;
      }
      let params = {
        fieldValueId: this.babyConfigTemplate.fieldValueId,
        memberId: this.babyConfigTemplate.memberId,
        enterpriseOpencardFieldId: this.babyConfigTemplate.enterpriseOpencardFieldId,
        systemFieldId: this.babyConfigTemplate.systemFieldId,
        unifiedIdentification: this.babyConfigTemplate.unifiedIdentification,
        fieldName: this.babyConfigTemplate.fieldName,
        fieldType: this.babyConfigTemplate.fieldType,
        fieldContent: this.babyConfigTemplate.fieldContent,
        fieldCode: this.babyConfigTemplate.fieldCode,
        fieldValue: this.babyConfigTemplate.fieldValue,
      }
      let babyTemplates = this.babyConfigTemplate.template;
      let child = this.fieldsList.map(el => {
        let value = [];
        for(let key in el.form) {
          if(el.form[key]) {
            let findItem = babyTemplates.find(e => e.unifiedIdentification == key);
            let fieldValue = el.form[key];
            if(findItem.fieldType == 4) {
              fieldValue = fieldValue.replaceAll('-', '');
            }
            value.push({enterpriseOpencardFieldId: findItem.enterpriseOpencardFieldId, unifiedIdentification: findItem.unifiedIdentification, fieldValue, systemFieldId: findItem.systemFieldId});
          }
        }
        return value;
      })
      params.child = child;
      this.loading = true;
      doFetch(url.updateBabyInfo, Object.assign({}, params)).then(() => {
        this.$emit('update:dialogVisible', false);
        this.$parent.initData();
      }).finally(() => {
        this.loading = false;
      })
    },
    getRules(item) {
      let ruleReg = new RegExp(item.ruleContent)
      let validatePass = null
      if(item.fieldType == 0) {
        validatePass = (rule, value, callback) => {
          if (value === '' || ruleReg.test(value)) {
            callback();
          } else {
            callback(new Error('请输入正确的内容'));
          }
        }
        return { validator: validatePass, trigger: 'blur' }
      } 
      else if(item.unifiedIdentification == 'k20303') {
        let rule = JSON.parse(item.fieldContent.replaceAll('\'', '"'));
        let time = rule.timeLong
        validatePass = (rule, value, callback) => {
          if (value === '' || value === null) {
            callback();
          } else if (new Date().getFullYear() - new Date(value).getFullYear() > parseInt(time)) {
            callback(new Error(`超过当前日期时间之前${time}年`));
          } else if(new Date(value) > new Date()) {
            callback(new Error(`超过当前日期时间`));
          } else  {
            callback();
          }
        }
        return { validator: validatePass, trigger: 'blur' }
      } else {
        return null
      }
    },
    cancel () {
      this.$emit('update:dialogVisible', false);
    },
  },
};

</script>
<style lang="less">
// 去除dailog-footer上边框
.baby-name {
  .el-input__inner {
    padding-right: 45px;
  }
}
.customer-dialog .el-dialog__footer {
  padding-top: 0;
  padding-bottom: 20px;
  border-top: none !important;
}
.customer-dialog .el-dialog__body {
  padding-bottom: 0;
  .el-tabs__header {
    margin-bottom: 30px;
    .el-tabs__item {
      max-width: 190px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .el-form-item__label {
    padding-right: 0;
  }
  .el-tabs__content {
    overflow: initial !important;
  }
}
.customer-dialog.baby-info-dialog .el-dialog__body{
  padding-top: 5px;
  padding-bottom: 30px;
  .el-form--inline{
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    >div{
      margin: 0;
    }
  }
}
</style>
