
<template>
  <div class="form mb-4 last:mb-0" :style="options.style">
    <div class="mb-4">
      <component :is="getComponent(item)" :key="index" :options="item" :value.sync="formData[item.field]" v-for="(item, index) in options.children"></component>
    </div>
    <v-button :disable="success" :options="buttonOptions" @click="submit"></v-button>
  </div>
</template>
<script>
import Base from '../base';
import Dialog from 'vant/lib/dialog';
import 'vant/lib/dialog/style';
import { fetch } from '@/api/page.js'

export default {
  name: 'v-form',
  extends: Base,
  data(){
    return {
      formData: {},
      loading: false,
      success: false,
    }
  },
  computed: {
    buttonOptions() {
      const { submit = {} } = this.options || {};
      return {
        text: '提交',
        ...submit,
      }
    }
  },
  created(){
    let {uuid} = this.$route.params;
    let param = localStorage.getItem(uuid);
    let jsonObj = {};
    if( param ){
      jsonObj= JSON.parse(param);
    }
    var data = {};
    this.options.children.forEach(item => {
      item.value = jsonObj[item.field]||'';
      data[item.field] = jsonObj[item.field]||undefined;
    });
    this.formData = data||{};
  },
  methods: {
    submit(){
      let errmsg;
      this.options.children.find(item => {
        if(!errmsg && item.required && !this.formData[item.field]) {
          errmsg = item.label;
        }
      })
      if(errmsg) {
        return Dialog.alert({
          message: `请填写${errmsg}`,
        })
      }
      let {uuid} = this.$route.params;
      if(this.loading) return;
      this.loading = true;
      const { formId, formName, formAction} = this.options;
      let param = Object.assign({formId, formName, formAction, uuid}, this.formData );
      localStorage.setItem( uuid, JSON.stringify(param) );
      fetch(formAction || '', param ).then(() => {
        this.loading = false;
        this.success = true;
        Dialog.alert({
          message: '提交成功',
        })
      }).catch((err) => {
        console.log("err", err)
        this.loading = false;
        Dialog.alert({
          message: err.message,
        })
      })
    },
    getComponent(node){
      return node.type ? `v-${node.type}` : 'div';
    },
    handleValue(key, value){
      this.formData[key] = value;
    }
  }
}
</script>
<style lang="less" scoped>
.form {
  background: rgba(255, 255, 255, 0.25);
  padding: 0.75rem 1rem;
  border: 1px solid rgba(255, 255, 255, 0.55);
  border-radius: 0.5rem;
  /deep/ .form-label {
    width: 5rem;
    padding: 0.5rem 0;
    font-size: 1rem;
    line-height: 1;
  }
}
</style>
