<template>
  <basic-container>
    <basic-container>
      <el-select v-model="value" filterable placeholder="請選擇" @change="selectTable">
        <el-option
          v-for="(item, idx) in tableList"
          :key="idx"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </basic-container>

    <div v-if="show">
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger"
                     size="small"
                     icon="el-icon-delete"
                     plain
                     v-if="permission.autodata_delete"
                     @click="handleDelete">刪 除
          </el-button>
        </template>
      </avue-crud>
    </div>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/bank/autodata";
  import {mapGetters} from "vuex";
  import {getList as getTables} from "@/api/bank/autostruct";
  import {opStr2opObj} from "../../api/bank/autostruct";

  export default {
    data() {
      return {
        show: false,
        value: '',
        tableList: [],

        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.autodata_add, false),
          viewBtn: this.vaildData(this.permission.autodata_view, false),
          delBtn: this.vaildData(this.permission.autodata_delete, false),
          editBtn: this.vaildData(this.permission.autodata_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      // let data = {column:[{type:'input',label:'姓名',span:12,display:true,prop:'name',required:true,rules:[{required:true,message:'姓名必須填寫'}]},{type:'input',label:'年齡',span:12,display:true,prop:'age'},{type:'input',label:'手機號',span:12,display:true,prop:'phone',maxlength:11},{type:'input',label:'住址',span:12,display:true,prop:'address'}],labelPosition:'right',labelSuffix:'：',labelWidth:120,gutter:0,menuBtn:true,submitBtn:true,submitText:'提交',emptyBtn:true,emptyText:'清空',menuPosition:'center'};
      // this.option = data;
      this.initTableList();
    },
    methods: {
      initTableList(){
        getTables(1, 500, {}).then(res => {
          const data = res.data.data;
          this.tableList = data.records;
          if (this.tableList.length > 0){
            this.value = this.tableList[0].id;
            this.selectTable(this.value)
          }
        });
      },
      selectTable(value){
        let _this = this;
        this.show = false;
        let table = this.getItemById(value);
        this.option = opStr2opObj(table.columns);
        setTimeout(() => {
          _this.show = true;
          _this.onLoad(this.page)
        }, 50)

      },
      getItemById(id){
        for (let i = 0; i < this.tableList.length; i++) {
          let item = this.tableList[i];
          console.log(i)
          if (item.id == id){
            return item;
          }
        }
      },
      beforeSave(row){
        let  keys = Object.keys(row);
        let form = {}
        for(let i = 0; i < keys.length; i++){
          let item = {};
          item['' + keys[i]] = row[''+keys[i]];
          form['params'+(i+1)] = JSON.stringify(item);
        }
        form.tableId = this.value;
        return form;
      },
      rowSave(row, done, loading) {
        let form = this.beforeSave(row)
        add(form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        let formTem = this.deepClone(row);
        delete formTem.$index,delete formTem.createDept,delete formTem.createTime,delete formTem.createUser,delete formTem.id;
        let form = this.beforeSave(formTem);
        form.id = row.id;
        update(form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          /*getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });*/
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      initData(data){
        let newData = [];
        for (let i = 0; i < data.length; i++) {
          let row = data[i];
          let form = {};
          form.id = row.id, form.createUser = row.createUser, form.createTime = row.createTime, form.createDept = row.createDept;
          let keys = Object.keys(row);
          for (let j = 0; j < keys.length; j++) {
            let key = keys[j];
            if (key.indexOf("params") != -1){
              let value = row['' + key];
              if (value != ''){
                let item = JSON.parse(value);
                Object.assign(form, item);
              }
            }
          }
          newData.push(form)
        }
        return newData;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        params.tableId = this.value;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = this.initData(data.records);
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
