<template>
  <div>
    <Card style="height:100%">
      <Drawer
        placement="right"
        :closable="false"
        :mask-closable="false"
        v-model="showsearch"
        width="600"
      >
        <Forms ref="searchform" :fminfo="searchinfo" style="height:100%">
          <template v-slot:default="slotProps">
            <Button
              v-for="bt in searchbtns"
              :key="bt.key"
              :type="bt.type"
              :icon="bt.icon"
              @click="doquery(slotProps.fm,bt.key)"
            >{{ bt.title }}</Button>
          </template>
        </Forms>
      </Drawer>
      <div>
        <tables
          ref="tables"
          editable
          searchable
          search-place="top"
          :loading="tblloading"
          highlightRow
          v-model="tableData"
          :columns="colswithauth"
          @on-rapid-query="doquery"
          @on-exec="doexec"
          @on-select="onsels"
          @on-adv-search="advsearch"
          :formatCol="formatCol"
          :isMulti="isMulti"
        >
          <template v-slot:tblbtnarea="slotProps">
            <Button
              v-for="bt in onlistbtns"
              :key="bt.key"
              :type="bt.type"
              :icon="bt.icon"
              @click="doexec(bt.key)"
            >{{ bt.title }}</Button>
          </template>
        </tables>
        <div style="text-align:center">
          <Page
            :total="pageInfo.total"
            :page-size-opts="[15,30,50,100,200,500]"
            :current.sync="pageInfo.pageNo"
            :page-size="pageInfo.pageSize"
            show-sizer
            @on-page-size-change="onsizeChange"
            @on-change="onpagechange"
          />
        </div>
      </div>
      <!-- <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为Csv文件</Button> -->
      <Drawer
        ref="eddrawer"
        placement="right"
        :closable="false"
        :mask-closable="false"
        v-model="showedform"
        width="70"
        @on-visible-change="ondrawvisable"
   
      >
        <Forms
          ref="edform"
          :fminfo="forminfo"
          style="height:100%"
          :refvalidatemethod="refvalidatemethod"
          v-if="showedform"
        >
          <template v-slot:default="slotProps">
            <Button
              v-for="bt in formbtns"
              :key="bt.key"
              :type="bt.type"
              :icon="bt.icon"
              @click="doexec(bt.key,slotProps.fm)"
            >{{ bt.title }}</Button>
          </template>
        </Forms>
      </Drawer>
    </Card>

    <Modal v-model="isdel" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>删除提示</span>
      </p>
      <div style="text-align:center">
        <p>您真的要删除当前选中的记录吗？</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modal_loading" @click="delpost">Delete</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import Forms from "./forms/forms";
import {
  getTableData,
  saveFormData,
  deleteData,
  bulkDeleteData
} from "@/api/data";
export default {
  name: "biztables",
  components: {
    Tables,
    Forms
  },
  props: {
    isLazy: Boolean,
    isChildList: Boolean,
    initWhere: {
      type: Object,
      default() {
        return {};
      }
    },
    initPropZIndex: {
      type: Number,
      default: 1100
    },
    packageName: String,
    modelName: String,
    metaName: {
      type: String,
      default: "user_info"
    },
    isMulti: Boolean,
    sumfields: {
      type: Array,
      default() {
        return [];
      }
    },
    avgfields: {
      type: Array,
      default() {
        return [];
      }
    },
    calcfields: {
      type: Array,
      default() {
        return [];
      }
    },
    formatCol: {
      type: Function,
      default() {
        return (row, key, index) => row[key];
      }
    },
    refvalidatemethod: {
      type: Function
      // default() {
      //   return (rule, value, callback) => {
      //     return callback();
      //   };
      // }
    }
  },
  data() {
    return {
      tblloading: false,
      metainfo: this.$store.getters[this.metaName],
      tableData: [],
      isdel: false,
      modal_loading: false,
      currentRow: null,
      currentSels: [],
      pageInfo: {
        pageNo: 1,
        pageSize: 10,
        total: 100
      },
      searchModel: {},
      showsearch: false,
      showedform: false,
      fm_status: "normal",

      sum_fields: this.sumfields ? this.sumfields : [],
      avg_fields: this.avgfields ? this.avgfields : [],
      calcdata: this.calcfields
        ? this.calcfields
        : [{ label: "余额", value: 1000 }],
      sumdata: {},
      avgdata: {},
      clickcount: { save: 0 },
      isrowdel: true,
      initZIndex: this.initPropZIndex
    };
  },
  methods: {
    ondrawvisable(v) {
      if (v) {
        this.initZIndex = this.initZIndex;
        $("div.ivu-drawer-wrap:even").map((index, item) => {
          $(item).css("z-index", "" + this.initZIndex++);
        });
      }
    },
    setFormCtlVisable(prop, isShow) {
      this.$refs.edform.setCtlVisable(prop, isShow);
    },
    deepclone(objin) {
      let rtnstr = JSON.stringify(objin);
      return JSON.parse(rtnstr);
    },
    onpagechange() {
      this.fetchData();
    },
    buildQuery(qobj) {
      let rtn = {};
      if (qobj) {
        rtn.search = qobj;
      } else {
        rtn.search = this.$refs.searchform.formModel;
      }
      if (this.initWhere) {
        rtn.search = Object.assign(rtn.search, this.initWhere);
      }
      console.log("..................rtn.search", rtn.search);
      rtn.aggsinfo = { sum: this.sum_fields, avg: this.avg_fields };
      rtn.pageInfo = {
        pageSize: this.pageInfo.pageSize,
        pageNo: this.pageInfo.pageNo
      };
      return rtn;
    },
    advsearch() {
      this.showsearch = true;
    },
    onsizeChange(s) {
      this.pageInfo.pageSize = s;
      this.fetchData();
    },
    onsels(sels, lastsel) {
      this.currentSels = sels;
    },
    delpost() {
      let url = "";
      if (this.isrowdel) {
        //行删除
        let url = this.buildUrl("delete");
        let data = { id: this.currentRow.id };
        deleteData(url, data).then(res => {
          let rtn = res.data;
          if (rtn.status == 0) {
            this.$Message.success("当前记录已经成功删除.");
            this.fetchData();
          } else {
            this.$Message.success("当前记录删除失败，请重试或联系管理员.");
          }
        });
      } else {
        //多行删除
        let url = this.buildUrl("bulkDelete");
        let ids = this.currentSels.map(item => {
          return item.id;
        });
        bulkDeleteData(url, ids).then(res => {
          if (res.data.data.status == 0) {
            this.$Message.success("批量删除已经成功完成.");
            this.currentSels = [];
            this.fetchData();
          } else {
            this.$Message.success("当前删除失败，请重试或联系管理员.");
          }
        });
      }
      this.modal_loading = true;
      setTimeout(() => {
        this.isdel = false;
        this.modal_loading = false;
        this.currentRow = null;
      }, 500);
    },
    doexec(key, row, btninfo) {
      if (key == "delete") {
        this.currentRow = row;
        this.isdel = true;
        this.isrowdel = true;
      }
      if (key == "deletes") {
        if (this.currentSels.length == 0) {
        } else {
          this.isdel = true;
          this.isrowdel = false;
        }
      }
      if (key == "edit") {
        this.fm_status = "edit";
        this.showedform = true;
        this.$emit("onedit");
        this.$nextTick(() => {
          this.$refs.edform.formModel = this.deepclone(row);
          this.$refs.edform.activeChildTables(false);
        });
      }
      if (key == "create") {
        this.fm_status = "create";
        this.showedform = true;
        this.$refs.edform.activeChildTables(true);
        this.$emit("onnew");
      }
      if (key == "save") {
        console.log("beforevalid.........................");
        this.$refs.edform.validate(valid => {
          console.log("valid.........................", valid);
          if (valid) {
            if (this.clickcount["save"] == 0) {
              console.log("before.......savbeformdata...............1");
              this.clickcount["save"] = this.clickcount["save"] + 1;
              let url = "";
              let msg = "";
              if (this.fm_status == "edit") {
                url = this.buildUrl("update");
                msg = "当前的更新操作已成功.";
              }
              if (this.fm_status == "create") {
                url = this.buildUrl("create");
                msg = "当前的新增操作已成功.";
                if (this.isChildList) {
                  //如果当前列表是作为表单子列表，那么需要设置当前新增对象的所属表单id
                  row = Object.assign(row, this.initWhere);
                }
              }
              console.log("before.......savbeformdata...............2");
              saveFormData(url, row).then(res => {
                let rtn = res.data;
                console.log(rtn);
                if (rtn.status == 0) {
                  this.$refs.edform.resetForm();
                  this.fm_status = "normal";
                  this.showedform = false;
                  this.clickcount["save"] = this.clickcount["save"] - 1;
                  this.$Message.success(msg);

                  this.fetchData();
                } else {
                  this.fm_status = "normal";
                  this.showedform = false;
                  this.$Message.error("当前操作失败，请稍后重试或联系管理员.");
                  this.fetchData();
                }
              });
            } else {
              this.$Message.warning("当前进行了重复的无效操作.");
            }
          } else {
            console.log("validate not pass.......");
          }
        });
      }
      if (key == "cancel") {
        this.fm_status = "normal";
        this.showedform = false;
        this.$refs.edform.resetForm();
        if (this.clickcount["save"] == 1) {
          this.clickcount["save"] = this.clickcount["save"] - 1;
        }
      }
      if (key == "export") {
        this.exportExcel();
      }
      if (key == "adv-search") {
        this.advsearch();
      }
      this.$emit("onexec", key, row, btninfo);
      console.log(key, row, "ddddddddddddddddddddddddddddddd");
    },
    doquery(q, k) {
      if (k == "cancel-search") {
        this.$refs.searchform.resetForm();
        this.showsearch = false;
        return;
      }
      if (k == "start-search") {
        this.showsearch = false;
      }
      this.fetchData(q);
    },
    exportExcel() {
      this.$refs.tables.exportCsv({
        filename: `table-${new Date().valueOf()}.csv`
      });
    },
    buildUrl(methodName) {
      let modelname = this.modelName
        ? this.modelName
        : this.metaName.split("_")[0];
      let url =
        "/web/" + this.packageName + "/" + modelname + "Ctl/" + methodName;

      return url;
    },
    fetchData(q) {
      let url = this.buildUrl("findAndCountAll");
      let query = this.buildQuery(q);
      this.tblloading = true;
      getTableData(url, query).then(res => {
        let rtn = res.data;
        if (rtn.status == 0) {
          console.log(res.data);
          this.tableData = rtn.data.results.rows;
          this.pageInfo.total = rtn.data.results.count;
          this.tblloading = false;
        } else {
          //this.$Message.error("查询数据有问题，请稍后重试或联系管理员");
          this.tblloading = false;
        }
      });
    }
  },
  mounted() {
    //从缓存中恢复查询条件
    if (!this.isLazy) {
      this.fetchData();
    }
  },
  created() {},
  computed: {
    searchinfo() {
      return this.metainfo["search"];
    },
    forminfo() {
      return this.metainfo["form"];
    },
    formbtns() {
      return this.metainfo["auths"].filter(bt => {
        return bt.isOnForm;
      });
    },
    searchbtns() {
      return this.metainfo["auths"].filter(bt => {
        return bt.isInSearch;
      });
    },
    onlistbtns() {
      return this.metainfo["auths"].filter(bt => {
        return bt.isOnGrid;
      });
    },
    colswithauth() {
      let listbtns = this.metainfo["auths"].filter(bt => {
        return bt.isInRow;
      });
      this.metainfo["list"].forEach(c => {
        if (c.key == "handle") {
          c.button = [];
          c.button.push(...listbtns);
        }
      });

      return this.metainfo["list"];
    }
  }
};
</script>

<style>
</style>
