<template>
  <div id="arr">
    <el-row>
      <el-col :span="24">
        <el-form-item :label="label" v-bind="$attrs">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">添加</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="22" :offset="2">
        <el-table :data="value" border>
          <el-table-column align="center" v-for="(i, index) in children" :key="`${model}-column-${index}`" :label="i.label" :prop="i.model"></el-table-column>
          <el-table-column align="center" label="操作">
            <template v-slot="{ row, $index }">
              <el-link type="danger" :underline="false" size="mini" @click="toDelete($index)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="dialog" center width="40%" title="信息" destroy-on-close @close="handleClose">
      <el-form label-position="left" label-width="130px">
        <template v-for="(f, fi) in children">
          <template v-if="!f.type || f.type === 'input'">
            <inputs :key="`${model}-inputs-${fi}`" :label="f.label" v-model="form[f.model]" :label-width="f.labelWidth"></inputs>
          </template>
          <template v-if="f.type === 'select'">
            <selects
              :key="`${model}-selects-${fi}`"
              :label="f.label"
              v-model="form[f.model]"
              :list="f.list"
              v-bind="$attrs"
              :label-width="f.labelWidth"
            ></selects>
          </template>
        </template>
        <el-row type="flex" justify="center">
          <el-col :span="4">
            <el-button type="primary" size="mini" @click="toSave">保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
const _ = require('lodash');
import inputs from './inputs.vue';
import selects from './selects.vue';
import { mapState, createNamespacedHelpers } from 'vuex';
export default {
  name: 'arr',
  props: {
    label: String,
    model: String,
    children: Array,
    value: { type: Array },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  components: { inputs, selects },
  data: function() {
    return {
      dialog: false,
      form: {},
    };
  },
  created() {},
  methods: {
    toAdd() {
      this.dialog = true;
    },
    toSave() {
      const dup = _.cloneDeep(this.form);
      this.value.push(dup);
      this.handleClose();
    },
    toDelete(index) {
      this.value.splice(index, 1);
    },
    handleClose() {
      this.dialog = false;
      this.form = {};
    },
  },
  computed: {
    ...mapState(['user', 'menuParams']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped></style>
