<template>
  <div>
    <!-- 封装后的表格 -->
    <el-table
      class="list-main"
      :header-cell-style="getRowClass"
      ref="singleTable"
      :data="table_data"
      height="calc(100% - 48px)"
      max-height="calc(100% - 48px)"
      border
      stripe
      :cell-style="{ padding: '2px 0' }"
      header-row-class-name="list-main-header"
      highlight-current-row
      @selection-change="handleSelectionChange"
      @current-change="handleCurrentChangeRow"
    >
      <el-table-column label="系统" header-align="center" :width="fix_width" fixed="left">
        <template v-if="is_check">
          <el-table-column type="selection" width="50" header-align="center" align="center" v-if="isCheckALL"></el-table-column>
        </template>
        <el-table-column v-if="is_number" label="序号" type="index" width="100" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ (page_index - 1) * page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <!--  -->

      <template v-for="column in columns" :header-align="column.header_align">
        <el-table-column
          sortable
          :header-align="column.header_align"
          :key="column.flame_id"
          :width="column.width"
          :align="column.cell_align"
          :fixed="column.is_fixed ? column.fixed_position : false"
          v-if="column.is_fk === true"
          :show-overflow-tooltip="true"
          :prop="column.field_name"
          :formatter="formatDefault"
          :label="column.field_description"
        >
          <template>
            <el-table-column
              v-for="col in column.children"
              :header-align="col.header_align"
              :key="col.flame_id"
              :width="col.width"
              :align="col.cell_align"
              :show-overflow-tooltip="true"
              :prop="col.field_name"
              :formatter="formatDefault"
              :label="col.field_description"
            >
              <template slot-scope="scope">
                <span>{{ scope.row['ref_' + column.field_name] !== undefined ? scope.row['ref_' + column.field_name][col.field_name] : '' }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          :header-align="column.header_align"
          :key="column.flame_id"
          :width="column.width"
          :align="column.cell_align"
          v-else-if="column.field_name !== 'flame_id'"
          :fixed="column.is_fixed ? column.fixed_position : false"
          :show-overflow-tooltip="true"
          :prop="column.field_name"
          :formatter="formatDefault"
          :label="column.field_description"
        ></el-table-column>
      </template>

      <el-table-column label="操作" width="150" align="center" header-align="center" fixed="right" v-if="isOperation">
        <template slot-scope="scope">
          <el-button @click="handleClick_Watch(scope.row)" v-if="is_watch" type="text">查看</el-button>
          <el-button @click="handleClick_Edit(scope.row)" v-if="is_edit" type="text">编辑</el-button>
          <el-button @click="handleClick_Delete(scope.row)" type="text" v-if="is_delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="bottom">
      <div class="bottom-batch" v-if="is_check">
        <div class="batch" v-if="isCheckALL">
          <el-checkbox class="checkbox" @change="CheckAll" v-model="checked_all">全选</el-checkbox>
          <el-select v-model="batch_operation_value" placeholder="扩展操作" @change="handBatchChange" size="small">
            <el-option v-for="item in batch_operation_list" :key="item.action" :label="item.display_name" :value="item.action"></el-option>
          </el-select>
        </div>
      </div>
      <div class="bottom-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page_index"
          :page-sizes="page_sizes"
          :page-size="page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total_number"
        ></el-pagination>
      </div>
    </div>
    <DrawerWatch v-if="is_sheet" :show_dialog="dialog_watch" :col_num="3" :flame_id="current_id" :table_name="table_name" @dialogClose="watchDiaglogClose"></DrawerWatch>
    <DialogEdit :table_name="table_name" :flame_id="current_id" :col_num="2" :show_dialog="dialog_edit" @dialogClose="editDiaglogClose"></DialogEdit>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import system from '../../api/system.js';
export default {
  name:'table-grid-sheet',
  components: {},
  props: {
    // 外面传入的过滤条件
    filter_data: {
      type: Array
    },
    // 每页显示数据的大小（数量）
    // page_size: {
    //   type: Number,
    //   default: 15
    // },
    // 数据排序
    order_by: {
      type: String,
      default: ''
    },
    ref_level: {
      type: Number,
      default: 1
    },
    is_check: {
      type: Boolean,
      default: false
    },
    // 是否显示序号
    is_number: {
      type: Boolean,
      default: true
    },
    is_dialog: {
      type: Boolean,
      default: false
    },
    // 是否有查询的功能
    is_watch: {
      type: Boolean,
      default: true
    },
    is_edit: {
      type: Boolean,
      default: true
    },
    isCheckALL: {
      type: Boolean,
      default: true
    },
    is_delete: {
      type: Boolean,
      default: true
    },
    is_sheet:{
      type:Boolean,
      default:false
    },
    // 要操作的表名 navication
    table_name: {
      type: String,
      required: true
    },
    batch_operation_list: {
      type: Array
      // default: [{ action: "01", display_name: "批量删除" }]
    }
  },
  data() {
    return {
      table_height: null,
      table_data: [],
      columns: [],
      refColumns: [],
      page_size: 15,
      page_index: 1,
      total_number: 0,
      checked_all: false,
      // 多选列表
      multipleSelection: [],
      batch_operation_value: null,
      // batch_operation_list: [{ action: "01", display_name: "批量删除" }],
      dialog_watch: false,
      dialog_edit: false,
      current_id: 0,
      formEditData: null,
      currentRow: null,
      conditions: {}
      // page_sizes:[this.page_size,15,30,50,100]
    };
  },
  watch: {
    immediate: true,
    flameTableInfoItems(val) {
      let that = this;
      console.log('table_name', that.table_name);
      this.getField();
    },
    table_name(newV, oldV) {
      let that = this;
      if (newV != '') {
        that.getField();
      }
    }
  },
  computed: {
    ...mapGetters('global', ['getOneTableInfoByTableName', 'flameTableInfoItems', 'getOneTableInfoItemByTableName']),

    page_sizes: function() {
      let that = this;
      if (that.page_size != 15 && that.page_size != 30 && that.page_size != 50 && that.page_size != 100) {
        return [this.page_size, 15, 30, 50, 100];
      } else {
        return [15, 30, 50, 100];
      }
    },
    // 序号与勾选的宽问题
    fix_width: function() {
      let w = 150;
      let that = this;
      if (that.is_check === true) {
        if (that.is_number === true) {
          w = 150;
        } else {
          w = 50;
        }
      } else {
        if (that.is_number === true) {
          w = 100;
        } else {
          w = 0;
        }
      }

      return w;
    },
    isOperation: function() {
      if (this.is_delete || this.is_watch || this.is_edit) {
        return true;
      } else {
        return false;
      }
    },
    // 总记录数
    dataRecord: function() {
      let that = this;
      return that.total_number;
    },
    // 页面大小
    realPageSize: function() {
      let that = this;
      return that.page_size;
    },
    // 当前页
    realPageIndex: function() {
      let that = this;
      return that.page_index;
    },
    // 查询数据的过滤条件
    realFilterData: function() {
      let that = this;
      let default_filter_data = {
        field_name: 'id',
        field_operation: 'like',
        field_value: '%',
        link_type: 'or'
      };
      if (that.filter_data.length > 0) {
        default_filter_data = that.filter_data;
      }
      return default_filter_data;
    }
  },
  created() {
    // this.getTableHeight();
  },
  mounted() {
    let that = this;
    console.log('table_name', that.table_name);
    this.getField();
  },
  methods: {
    handleCurrentChangeRow(val) {
      let that = this;
      that.currentRow = val;
      console.log('handleCurrentChangeRow', val);
      that.$emit('handleCurrentChangeRow', val);
    },
    getTableHeight() {
      let that = this;
      that.table_height = window.innerHeight - 250;
    },
    // 显示时数据转换
    formatBoolean: function(row, column, cellValue, index) {
      var ret = cellValue; //你想在页面展示的值
      // console.log("typeof(cel)=====", typeof cellValue);
      if (typeof cellValue === 'boolean')
        if (cellValue === true) {
          ret = '是'; //根据自己的需求设定
        } else if (cellValue === false) {
          ret = '否';
        }
      return ret;
    },
    // 将日期格式化为YYYY-MM-DD格式，没有时间
    formatDate: function(row, column, cellValue, index) {
      var ret = cellValue; //你想在页面展示的值
      // this.$dayjs('2019/06/17 14:00:00').startOf('hour').fromNow(); //1小时前
      let that = this;
      return that.$dayjs(ret).format('YYYY-MM-DD'); //2019年08月01日
      // this.$dayjs(new Date()).format('YYYY年MM月DD日 HH时mm分ss秒');  //2019年08月01日 19时50分20秒
      // //计算两个日期的天数
      // let days = this.$dayjs('2019/06/17 14:00:00').diff(this.$dayjs('2019/06/20 14:00:00'), 'days');

      // //比较两个日期的大小
      // let flag = this.$dayjs('2019/06/17 14:00:00').isBefore('2019/06/17 14:00:00');
    },
    // 将日期格式化为YYYY-MM-DD HH:mm:ss格式，有时间
    formatDateTime: function(row, column, cellValue, index) {
      var ret = cellValue; //你想在页面展示的值
      // this.$dayjs('2019/06/17 14:00:00').startOf('hour').fromNow(); //1小时前
      let that = this;
      return that.$dayjs(ret).format('YYYY-MM-DD HH:mm:ss'); //2019年08月01日 19时50分20秒
      // this.$dayjs(new Date()).format('YYYY年MM月DD日 HH时mm分ss秒');  //2019年08月01日 19时50分20秒
      // //计算两个日期的天数
      // let days = this.$dayjs('2019/06/17 14:00:00').diff(this.$dayjs('2019/06/20 14:00:00'), 'days');
      // //比较两个日期的大小
      // let flag = this.$dayjs('2019/06/17 14:00:00').isBefore('2019/06/17 14:00:00');
    },
    // 将日期格式化为 HH:mm:ss格式，有时间
    formatTime: function(row, column, cellValue, index) {
      var ret = cellValue; //你想在页面展示的值
      // this.$dayjs('2019/06/17 14:00:00').startOf('hour').fromNow(); //1小时前
      let that = this;
      return that.$dayjs(ret).format('HH:mm:ss'); //2019年08月01日 19时50分20秒
      // this.$dayjs(new Date()).format('YYYY年MM月DD日 HH时mm分ss秒');  //2019年08月01日 19时50分20秒
      // //计算两个日期的天数
      // let days = this.$dayjs('2019/06/17 14:00:00').diff(this.$dayjs('2019/06/20 14:00:00'), 'days');
      // //比较两个日期的大小
      // let flag = this.$dayjs('2019/06/17 14:00:00').isBefore('2019/06/17 14:00:00');
    },
    // 将数据格式化为百分比形式
    formatInteger(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('0,0');
      return str;
    },
    // 将数据格式化为百分比形式
    formatPercentage(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('0.00%');
      return str;
    },
    // 将数据格式化货币并保留1位小数
    formatCurrency1(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('$0,0.0');
      return str;
    },

    // 将数据格式化货币并保留2位小数
    formatCurrency2(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('$0,0.00');
      return str;
    },

    // 将数据格式化货币并保留3位小数
    formatCurrency3(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('$0,0.000');
      return str;
    },

    // 将数据格式化货币并保留4位小数
    formatCurrency4(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('$0,0.0000');
      return str;
    },
    // 将数据格式化货币并保留两位小数
    formatCurrency5(row, column, cellValue, index) {
      var numeral = require('numeral');
      var number = numeral(cellValue);
      // console.log('格式化千分位',number.format('0,0'));
      // console.log('货比格式',number.format('$0000000,0.000000'));
      // console.log('只保留整数部分',number.format(',0'));
      // console.log('百分比', number.format('0.00%'));
      let str = number.format('$0,0.00000');
      return str;
    },

    formatDefault: function(row, column, cellValue, index) {
      var ret = cellValue; //你想在页面展示的值
      let that = this;
      let field_name = column.property;
      let col = that.columns.find(t => t.field_name === field_name);

      if (col !== null) {
        if (col.str_format === 'formatDateTime') {
          return that.formatDateTime(row, column, cellValue, index);
        } else if (col.str_format === 'formatTime') {
          return that.formatTime(row, column, cellValue, index);
        } else if (col.str_format === 'formatDate') {
          return that.formatDate(row, column, cellValue, index);
        } else if (col.str_format === 'formatBoolean') {
          return that.formatBoolean(row, column, cellValue, index);
        } else if (col.str_format === 'formatCurrency5') {
          console.log('col', col);
          return that.formatCurrency5(row, column, cellValue, index);
        } else {
          return ret;
        }
      } else {
        return ret;
      }
    },

    // 查看功能
    handleClick_Watch(row) {
      let that = this;
      that.dialog_watch = true;
      that.current_id = row.flame_id;
      console.log('row', row);
    },

    // 关闭查看对话框显示
    watchDiaglogClose(value) {
      let that = this;
      that.dialog_watch = false;
    },

    // 打开编辑功能
    handleClick_Edit(row) {
      let that = this;
      that.dialog_edit = true;
      that.current_id = row.flame_id;
      console.log('row', row);
    },
    // 关闭编辑功能
    editDiaglogClose(value) {
      let that = this;
      that.dialog_edit = false;
      if (value === true) {
        that.getData();
      }
    },
    // 表格明细中单条数据删除功能
    handleClick_Delete(row) {
      let that = this;
      that.current_id = row.flame_id;
      that
        .$confirm('此操作将删除数据, 是否继续?', '删除数据提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          system.singleDelete(that.table_name, { key: that.current_id }, res => {
            console.log('delete res =', res);
            // 如果删除成功，要刷新表格的数据
            if (res.result === true) {
              that.getData();
            }
          });
        });
    },
    // 得到表格需要显示的字段
    getField() {
      let that = this;
      console.log('getField====table_name', that.table_name);
      let temp = that.getOneTableInfoItemByTableName(that.table_name);
      // that.columns = temp
      that.columns = [];
      for (let i = 0; i < temp.length; i++) {
        let element = temp[i];
        if (that.is_dialog === false) {
          if (element.is_display === true) {
            that.columns.push(element);
          }
        } else if (that.is_dialog === true) {
          if (element.is_display_dialog === true) {
            that.columns.push(element);
          }
        }
        element['children'] = [];
        // 动态处理引用字段的显示问题
        if (element.is_fk === true) {
          console.log('is_fk', element);
          // 获取ref 相关信息
          let fk_table_name = element.fk_table_name;
          let fk_table_display_field_name = element.fk_table_display_field_name;
          let fk_table_ref_display_fields = element.fk_table_ref_display_fields;
          let fk_table_name_field = element.fk_table_name_field;

          if (fk_table_name !== null && fk_table_name !== '') {
            let fk_table_info_item = that.getOneTableInfoItemByTableName(fk_table_name);
            let ref_field_list = [];
            if (fk_table_info_item !== null && fk_table_info_item !== undefined) {
              if (fk_table_ref_display_fields !== null) {
                ref_field_list = fk_table_ref_display_fields.split(',');
              } else {
                ref_field_list.push(fk_table_display_field_name);
              }
            }

            ref_field_list.forEach(e => {
              for (let k = 0; k < fk_table_info_item.length; k++) {
                if (fk_table_info_item[k].field_name === e) {
                  element.children.push(fk_table_info_item[k]);
                  break;
                }
              }
            });
          }
          console.log('is_fk_children', element.children);
        }
      }
      console.log('getOneTableInfoItemByTableName===:', that.columns);
      that.getData();
    },
    // 重新加载表的数据数据，页码归1
    reloadData(is_page_first) {
      let that = this;
      if (is_page_first === true) {
        that.page_index = 1;
      }
      that.getData();
    },
    // 得到控件自已的查询条件
    getCommitData() {
      let that = this;
      let commit_Data = { page_size: that.page_size, page_no: that.page_index, ref_level: that.ref_level };
      if (that.order_by !== '') {
        commit_Data['order_by'] = that.order_by;
      }

      commit_Data['conditions'] = {};

      for (let i = 0; i < that.filter_data.length; i++) {
        let filter = that.filter_data[i];
        commit_Data['conditions'][filter.field_name] = filter.field_value;
      }
      return commit_Data;
    },
    // 获取分页数据
    getData() {
      let that = this;
      let filter_data = that.getFilterData();
      that.setDataByFilter(filter_data);
    },
    // 获取gird控件要的数据
    getGridData(commit_Data) {
      let that = this;
      console.log('getGridData===>commitData', commit_Data);
      system.pageSearch(that.table_name, commit_Data, res => {
        that.table_data = res.items;
        that.page_size = res.page_size;
        that.total_number = res.total_results;
      });
    },
    // 得到查询条件这个地方导出时要用到
    getFilterData() {
      let that = this;
      return that.conditions;
    },
    // 外面传入额外的过滤条件，获取数据
    setDataByFilter(filter_data) {
      let that = this;
      let commit_Data = that.getCommitData();
      console.log('组件自代的filter_data', commit_Data);
      console.log('传入的filter_data', filter_data);

      for (let i = 0; i < filter_data.length; i++) {
        let filter = filter_data[i];
        // 如果存在固定的查询条件不覆盖(比如：系统要求查询表字段为:XXX的值，在自定义查询条件用户用选择了，将会忽烈用户自行选择的条件)
        if (!commit_Data.hasOwnProperty(filter.field_name)) {
          commit_Data['conditions'][filter.field_name] = filter.field_value;
        }
      }
      that.conditions = commit_Data['conditions'];
      console.log('commit_Data', commit_Data);
      that.getGridData(commit_Data);
    },
    // 分页的页码大小发生变化时
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page_size = val;
      this.page_index = 1;
      this.getData();
    },
    // 页面发生变化时
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      let that = this;
      that.page_index = val;
      that.getData();
    },
    //
    toggleRowSelection(row, selected) {
      let that = this;
      that.$refs.singleTable.toggleRowSelection(row, selected);
    },
    CheckAll() {
      let that = this;
      if (that.multipleSelection.length !== 0) {
        that.$refs.singleTable.clearSelection();
        that.checked_all = false;
      } else {
        that.table_data.forEach(row => {
          that.$refs.singleTable.toggleRowSelection(row);
        });
        that.checked_all = true;
      }
    },

    // 得到选择的行的列表
    getSelectionChangeData() {
      let that = this;
      return that.multipleSelection;
    },
    // 表格选择中勾时
    handleSelectionChange(rows) {
      let that = this;
      that.multipleSelection = [];
      rows.forEach(e => {
        that.multipleSelection.push(e.flame_id);
        that.currentRow = e;
      });

      if (rows.length === that.page_size) {
        that.checked_all = true;
      } else {
        that.checked_all = false;
      }
      that.$emit('handleSelectionChange', rows);
    },
    handBatchChange() {
      let that = this;
      console.log('批指操作选择的值:', that.batch_operation_value);
      if (that.multipleSelection.length == 0) {
        that.batch_operation_value = null;
        that.$message({
          type: 'error',
          message: '请选择您要操作的数据，至少选择一条数据'
        });
      } else {
        that.$emit('batchoperation', that.batch_operation_value, that.multipleSelection);
      }
    },
    // 修改表格的表头样式
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0  ) {
         return 'color:#606266;font-size:12px;height:35px; padding: 0 0 ';
      } else if ( rowIndex === 1 ) {
         return 'color:#919398;font-size:12px;height:35px; padding: 0 0 ';
      } else {
        return '';
      }
    },
    change(form) {
      let that = this;
      console.log('Form:', form);
      that.formEditData = form;
    },
    OkCommitEdit() {
      let that = this;
      that.dialog_edit = false;
      let commitData = {};
      console.log('xxxxxxxxxxxx------------');
      that.formEditData.field_list.forEach(e => {
        commitData[e.field_name] = e.field_value;
      });
      console.log('commitData', commitData);
      that.$post('/api?app_id=xxx&method=' + that.model_Name + '.single_update', commitData).then(res => {
        that.getData();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.filter {
  display: flex;
  justify-content: space-between;
}
.from {
  position: relative;
}

.bottom {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  // position: fixed;
  // margin-bottom: 0px;
  bottom: 0;
  .bottom-batch {
    .batch {
      display: flex;
      padding: 8px;
      .checkbox {
        margin-top: 8px;
        margin-right: 8px;
      }
    }
  }
  .bottom-pagination {
  }
}
.el-button--text  {
  padding: 0;
}
</style>
