<template>
  <section class="ces-table-page">
    <!-- 数据表格 -->
    <section class="ces-table">
      <div class="ces_toolbar">
        <el-button
          v-if="addRowBtn"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="addRow()"
          class="ces_toolbar_btn"
        >新增</el-button>
        <el-input
          prefix-icon="el-icon-search"
          v-if="searchShow"
          v-model="search"
          placeholder="请输入账号、中文名"
          style="max-width:180px;"
          size="mini"
          @input="searchVal"
          class="ces_toolbar_inp"
        ></el-input>
      </div>
      <el-table
        :data="selectedTabsPage"
        :size="size"
        :border="border"
        @select="select"
        @select-all="selectAll"
        :defaultSelections="defaultSelections"
        element-loading-text="加载中..."
        :empty-text="emptyText"
        :stripe="stripe"
        ref="cesTable"
        :class="radius?'table_radius':''"
        v-cloak
      >
        <el-table-column v-if="isSelection" type="selection" align="center"></el-table-column>
        <!-- 序号 -->
        <el-table-column v-if="isIndex" type="index" :label="indexLabel" width="80" align="center"></el-table-column>

        <!-- 数据栏 -->
        <el-table-column
          v-for="(item,index) in headers"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :align="item.align"
          :render-header="item.require?renderHeader:null"
        >
          <template slot-scope="scope">
            <!-- 操作按钮 -->
            <span v-if="item.type==='Button'">
              <b v-for="(btn,key) in item.btnList" :key="key">
                <em
                  v-if="btn.label == '删除' || btn.label == '移除'"
                  :class="btn.type"
                  @click="handleRemove(scope.row,btn.label)"
                >{{btn.label}}</em>
                <em v-else :class="btn.type" @click="handleClick(btn.type, scope.row)">{{btn.label}}</em>
                <em v-if="btn.line" style="padding:0 20px;color:#edf0ff">{{btn.line}}</em>
              </b>
            </span>
            <!--href 链接-->
            <v-cloud-table-umhref
              v-else-if="item.type =='href'"
              :header="item"
              :row="scope.row"
              :detailsUrl="detailsUrl"
            ></v-cloud-table-umhref>
            <!-- could edit -->
            <v-cloud-table-input
              v-else-if="item.type==='input'"
              :item="helper.GetProperty(scope.row, item.prop)"
              :header="item.prop"
              :rowId="scope.$index"
              @changeInputValue="changeInputValue"
            ></v-cloud-table-input>
            <!-- 其他 -->
            <span
              v-else
              :class="scope.row.spec && scope.row.spec.disable && scope.row.spec.disable == true? 'disture':'disfail'"
            >{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <!-- 分页 -->
    <section class="ces-pagination" v-if="paginationShow">
      <div class="ces_page_total">共 {{ pagination.total }} 个条目</div>
      <div class="ces_page_num" v-if="pageSizeShow">
        <div class="ces_page_num_sel">
          <el-select
            v-model="pagination.rowsPerPage"
            placeholder="请选择"
            size="mini"
            @change="handleSizeChange"
          >
            <el-option
              v-for="item in pageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div>条 / 页</div>
      </div>
      <div class="ces_page_control">
        <el-button
          icon="el-icon-arrow-left"
          circle
          size="mini"
          @click="handleCurrentChange(-1)"
          :disabled="pagination.page==1"
        ></el-button>
        第{{ pagination.page }}页 / 共{{ Math.ceil(pagination.total / pagination.rowsPerPage) }}页
        <el-button
          icon="el-icon-arrow-right"
          circle
          size="mini"
          @click="handleCurrentChange(1)"
          :disabled="pagination.page==Math.ceil(pagination.total / pagination.rowsPerPage)"
        ></el-button>
      </div>
    </section>
    <!-- 删除弹窗 -->
    <d-confirm
      v-if="isDialog"
      :confirmModalOptions="confirmOptions"
      :delSelect="delSelect"
      ref="myConfirm"
      @refreshuseList="refreshuseList"
    ></d-confirm>
  </section>
</template>

<script>
import services from "@/services";
import tableInput from "@/components/table-input";
import helper from "@/services/helper";
import DConfirm from "@/components/dialog-remove";
import tableUmhref from "@/components/table-umhref";
export default {
  components: {
    "v-cloud-table-input": tableInput,
    "v-cloud-table-umhref": tableUmhref,
    "d-confirm": DConfirm
  },
  props: {
    // 表格型号：mini,medium,small
    size: { type: String, default: "medium" },
    loading: { type: Boolean, default: false },
    // 表格数据
    headers: { type: Array, default: () => [] },
    // 表格列配置
    // tableData: { type: Array, default: () => [] },
    // 是否显示表格复选框
    isSelection: { type: Boolean, default: false },
    defaultSelections: { type: [Array, Object], default: () => null },
    // 是否显示表格索引
    isIndex: { type: Boolean, default: false },
    indexLabel: { type: String, default: "序号" },
    // 是否显示分页
    // isPagination: { type: Boolean, default: true },
    // // 分页数据
    // pagination: {
    //   type: Object,
    //   default: () => ({ pageSize: 10, pageNum: 1, total: 0 })
    // },
    searchShow: {
      type: Boolean,
      default: false
    },
    url: {
      type: String,
      default: ""
    },
    detailsUrl: {
      type: String,
      default: ""
    },
    rowprop: {
      type: String,
      default: ""
    },
    ready: {
      type: Boolean,
      default: false
    },
    addRowBtn: {
      type: Boolean,
      default: false
    },
    // 是否显示删除弹窗
    isDialog: { type: Boolean, default: false },
    confirmOptions: {
      type: Object,
      default: () => {
        return {
          title: "提示", //提示
          message: "", //""
          btnCancelText: "取消", //取消
          btnSubmitText: "确定"
        };
      }
    },
    refreshInit: { type: Boolean },
    sortBy: {
      type: String,
      default: ""
    },
    searchNoName: { type: Boolean, default: false },
    emptyText: {
      type: String,
      default: "暂无数据"
    },
    autoAdd: {
      type: Boolean,
      default: false
    },
    border: {
      type: Boolean,
      default: false
    },
    stripe: {
      type: Boolean,
      default: false
    },
    radius: {
      type: Boolean,
      default: false
    },
    pageSizeShow: {
      type: Boolean,
      default: false
    },
    paginationShow: {
      type: Boolean,
      default: false
    },
    couldEditStyle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      all_url: "",
      pagination: {
        rowsPerPage: 10,
        page: 1,
        total: 0
      },
      delSelect: null,
      helper: helper,
      label: null,
      selectedTabsPage: [],
      pageOptions: [
        {
          value: "10",
          label: "10"
        },
        {
          value: "20",
          label: "20"
        },
        {
          value: "50",
          label: "50"
        }
      ],
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
          id: "ssss222"
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
          id: "ssss222"
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
          id: "ssss222"
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
          id: "ssss222"
        }
      ],
      search: "",
      times: null
    };
  },
  mounted() {
    this.getDataFromApiSync();
  },
  watch: {
    refreshInit: {
      handler(val) {
        if (val) {
          this.getDataFromApiSync();
        }
      }
    },
    url: {
      handler(val) {
        this.getDataFromApiSync();
      },
      deep: true
    }
  },
  methods: {
    // get data
    getDataFromApiSync() {
      console.log("get data >>>");
      if (this.url == "") {
        this.selectedTabsPage = this.tableData;
        this.pagination.total = this.selectedTabsPage.length;
        if (this.autoAdd) {
          this.addRow();
        }
      } else {
        this.getDataFromApi().then(
          data => {
            this.selectedTabsPage = JSON.parse(JSON.stringify(data.newArr));
            this.pagination.total = data.total;
            if (this.autoAdd) {
              this.addRow();
            }
          },
          err => {
            console.log("失败" + err);
          }
        );
      }
    },
    // get data from api
    getDataFromApi() {
      return new Promise((resolve, reject) => {
        const { page, rowsPerPage } = this.pagination;
        this.all_url = `${this.url}`;
        this.$http
          .get(this.all_url)
          .then(response => {
            let newArr = response.data[this.rowprop];
            let total = response.data.listMeta.totalItems;
            resolve({ newArr, total });
          })
          .catch(function(response) {
            // this.loading = false;
            reject(response);
          });
      });
    },
    // search debonce 500ms
    searchVal() {
      if (this.times !== null) clearTimeout(this.times);
      this.times = setTimeout(() => {
        this.getDataFromApiSync();
      }, 500);
    },
    // 表格勾选
    select(rows, row) {
      this.$emit("select", rows, row);
    },
    // 全选
    selectAll(rows) {
      this.$emit("select", rows);
    },
    handleCurrentChange(val) {
      this.pagination.page += val;
      this.$emit("refresh");
    },
    handleSizeChange(val) {
      this.pagination.rowsPerPage = val;
      this.$emit("refresh");
    },
    renderHeader(h, obj) {
      console.log(obj.column);
      return h("span", { class: "ces-table-require" }, obj.column.label);
    },
    handleRemove(row, label) {
      this.$refs.myConfirm.showModel();
      this.delSelect = row;
      this.delSelect.label = label;
      this.label = label;
    },
    refreshuseList() {
      this.$message({
        showClose: true,
        message: this.label + "成功",
        type: "success"
      });
    },
    switchChange(val) {
      this.$emit("handleSwitch", val);
    },
    reftableList() {},
    // another button in options
    handleClick(type, val) {
      this.$emit(type, val);
    },
    // 表格编辑修改数据
    changeInputValue(val) {
      // You can delete the row when the row of data is empty, but I didn't do that
      // console.log(this.$refs.cesTable)
      this.selectedTabsPage[val.rowId][val.header] = val.inputValue;
      if (
        this.autoAdd &&
        val.inputValue != "" &&
        val.rowId + 1 == this.selectedTabsPage.length
      ) {
        this.addRow();
      }
    },
    // 新增表格行
    addRow() {
      // at first, you should promise all colum in your table could be edit
      // this code is low level, you could make it stronger
      // use tableData[0] as template to edit
      let newRow = {};
      for (var item in this.selectedTabsPage[0]) {
        newRow[item] = "";
      }
      this.selectedTabsPage.push(newRow);
    }
  }
};
</script>
<style>
.ces-table .el-table::before {
  height: 0 !important;
}
.ces-table .el-table th.gutter {
  display: table-cell !important;
}
.ces-table .el-table colgroup.gutter {
  display: table-cell !important;
}
.ces-table .el-table td,
.ces-table .el-table th.is-leaf {
  border-bottom: none !important;
}
.ces-table .el-table--border td,
.ces-table .el-table th.is-leaf {
  border-bottom: 1px solid #ebeef5 !important;
}
/* .ces-table .el-table--enable-row-hover, */
.ces-table .el-table tbody tr:hover > td {
  background-color: #e4ecf8 !important;
  /* border-top: 1px solid #b9cefa !important;
  border-bottom: 1px solid #b9cefa !important; */
}
.ces-table .theme--light.el-table tbody tr:not(:last-child) {
  border-bottom: none;
}
.ces-table .el-table th > .cell {
  color: #1a2236;
}
.ces-table .el-table th > .cell,
.ces-table .el-table td > .cell {
  /* text-align: center; */
  font-size: 14px;
}
.ces-table .el-table tr {
  color: #58617a;
}
.ces-table .el-table__empty-text {
  color: #58617a;
  font-size: 14px;
}
em {
  font-style: normal;
}
.ces-table .el-table--mini td,
.ces-table .el-table--mini th {
  padding: 11px 0 !important;
}
.ces-table .el-table--border::after,
.ces-table .el-table--group::after,
.ces-table .el-table::before {
  background: #fff;
}
.ces-table .switchStyle .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
.ces-table .switchStyle .el-switch__label--left {
  z-index: 9;
  left: 6px;
  top: -1px;
}
.ces-table .switchStyle .el-switch__label--right {
  z-index: 9;
  left: -14px;
  top: -1px;
}
.ces-table .switchStyle .el-switch__label.is-active {
  display: block;
}
.ces-table .switchStyle.el-switch .el-switch__core,
.ces-table .el-switch .el-switch__label {
  width: 50px !important;
}
.ces-table .el-switch__core {
  background: #f8f9fd !important;
  border: 1px solid #8890a7 !important;
}
.ces-table .el-switch__core:after {
  background: #8890a7 !important;
}
.ces-table .el-switch.is-checked .el-switch__core {
  background: #f8f9fd !important;
  border: 1px solid #5c82ff !important;
}
.ces-table .el-switch.is-checked .el-switch__core:after {
  background: #5c82ff !important;
}
.ces-table .el-switch__label * {
  font-size: 10px !important;
  font-weight: 800;
}
.ces-table .el-switch .el-switch__label {
  color: #8890a7 !important;
}
.ces-table .el-switch.is-checked .el-switch__label {
  color: #5c82ff !important;
}
.ces-table .el-switch:hover {
  opacity: 0.8;
}
.chName.is-dark {
  background: #5c82ff !important;
}
.chName[x-placement^="top"] .popper__arrow,
.chName[x-placement^="top"] .popper__arrow::after {
  border-top-color: #5c82ff !important;
}
.ces-table .disfail {
  color: #58617a !important;
}
.ces-table .disture {
  color: #bcc1d0 !important;
}
.el-table__row--striped td {
  background: #f8f9fd !important;
}
/* .el-table th>.cell {
  padding-left: 14px;
} */
.could_edit {
  background-color: #5c82ff;
}
</style>
<style scoped>
.ces-table {
  position: relative;
}
.ces_toolbar {
  position: absolute;
  top: -40px;
  right: 20px;
}
.ces_toolbar .ces_toolbar_btn {
  margin-right: 10px;
}
.ces_toolbar .ces_toolbar_inp {
  margin-right: 10px;
}
.ces-pagination {
  margin-top: 20px;
  padding-bottom: 20px;
  font-size: 14px;
  padding: 0 5%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.ces_page_total {
}
.ces_page_num {
  width: 120px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.ces_page_num_sel {
  width: 66px;
}
.table_radius {
  border-radius: 10px;
}
</style>