<template>
  <div>
    <div
      id="showAuditData"
      class="container-fluid"
    >
      <div class="row">
        <div class="col-md-12">
          <p>创建人：{{ baseData.createdUser }} - {{ baseData.createdDate }}</p>
          <p>更新人：{{ baseData.updatedUser }} - {{ baseData.updatedDate }}</p>
          <p>数据类型：{{ tab.tabDataSource.className }}</p>
          <p>数据ID：{{ modelData.id }}</p>
          <p>数据UUID：{{ baseData.uuid }}</p>
        </div>
      </div>
      <!-- <div class="row">		
				<div class="col-md-12">
					<div>
						<button type="button" class="btn btn-success" @click="compare()">对比</button>
						<button type="button" class="btn btn-primary" @click="$router.go(-1)">返回到{{tab.name}}</button> 
					</div>
				</div>
			</div> -->
      <div class="row">
        <div class="col-md-12">
          <div class="table-div">
            <table
              class="fixed-table table-striped table-bordered "
              :width="tableWidth"
              height="40px"
            >
              <thead>
                <tr height="40px">
                  <th width="50px" />
                  <th width="100px">版本号</th>
                  <th
                    v-for="item in gridFieldItems"
                    :key="item.fieldName + '_' + item.entityFieldIndex"
                    :width="item.width"
                  >
                    {{ item.displayName }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="modelDataItem in gridData.dataList"
                  :key="modelDataItem.id"
                  height="40px"
                >
                  <td>
                    <input
                      v-model="modelDataItem.select"
                      autocomplete="off"
                      type="checkbox"
                      @change="checkboxChanged(modelDataItem,index)"
                    />
                  </td>
                  <td>{{ modelDataItem.data["version"].displayValue[0] }}</td>
                  <td
                    v-for="fieldItem in gridFieldItems"
                    :key="fieldItem.fieldName + '_' + fieldItem.entityFieldIndex + '_' + modelDataItem.id"
                  >
                    {{ displayValue(modelDataItem, fieldItem) }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div>
        <AntdPagination
          ref="paginationRef"
          :pagination="pagination"
          @get-page-params="getPageParams"
        />
      </div>
    </div>
    <!-- <div class="container-fluid" id="compareAuditData">
			<div class="row">
				<div class="col-md-12">
					<h2>{{tab.name}}审计数据对比</h2>
				</div>
			</div>
			<div class="row">		
				<div class="col-md-12">
					<div class="btn-group" role="group">
						<button type="button" class="btn btn-primary" @click="showAuditData()">返回</button>
					</div>
				</div>
			</div>
			<div class="row">			
				<table class="table" id="compareTable">
					<tr style="color : red;">
						<td><strong>版本号</strong></td>
						<td v-for="item in selectVersions">{{item}}</td>
					</tr>
					<tr v-for="(item,index) in showCompareData" :style="item.isSame==false?'color : red':''">
						<td width="100px" ><h5>{{item.name}} </h5></td>
						<td v-for="itemName in item.data"  > {{itemName}} </td>
					</tr>
				</table>
			</div>
		</div> -->
  </div>
</template>

<script>	
import Common from '../../common/Common.js';

import { Notify, Uuid } from 'pc-component-v3';
import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';

export default {

  components: {
    
  },
  
  props: {
    windowNo: {
      type: String,
      default: null,
    },
    tabIndex: {
      type: Number,
      default: null,
    },
    tab: {
      type: Object,
      default : function(){
        return null;
      },
    },
    modelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
  },



  data: function () {
    return {
      'gridData': [],
      'checkedDataList': [],
      'showCompareData': [],    //显示对比审计数据
      'selectVersions': [], //所选数据的版本号数组
      'pagination': {
        total: 0,
        per_page: Common.pageSize,    // required
        current_page: 1, // required
        last_page: 10,    // required
        from: 1,
        to: 10,           // required
      },
      baseData: {},
      gridFieldItems: [],
    };
  },

  computed: {
    tableWidth: function () {
      var totalWidth = 50;
      if (this.gridFieldItems != undefined) {
        this.gridFieldItems.forEach(function (gridFieldItem) {
          if(gridFieldItem.width != null && gridFieldItem.width > 0){
            totalWidth += gridFieldItem.width;
          }
        });
      }
      return totalWidth + 'px';
    },
  },

  watch: {
    modelData: function () {
      this.loadBaseData();
      this.audit();
    },

    tab: function () {
      this.init();
    },
  },
  mounted: function () {
    $('#compareAuditData').hide();
    this.init();
    this.loadBaseData();
    this.audit();
  },

  methods: {
    /**
         * 初始化界面
         */
    init: function () {
      if (this.tab != null && this.tab.tabGridView != null) {
        this.gridFieldItems = this.tab.tabGridView.tabGridFields;
      }
    },

    audit: function () {
      var _self = this;
      var tabQueryParam = {
        windowNo: _self.windowNo,
        tabIndex: _self.tabIndex,
        recordId: _self.modelData.id,
        range: {
          start: (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
      };
      $.ajax({
        url: Common.getApiURL('AuditResource/AuditData'),
        type: 'POST',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(tabQueryParam),
        success: function (data) {
          console.log(JSON.stringify(data));
          _self.gridData = data;
          _self.gridData.dataList.forEach(function (item) {
            item.select = false;
          });
          _self.pagination.total = data.totalSize;
          _self.pagination.last_page = Math.ceil(data.totalSize / data.range.length);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });

    },
    loadBaseData: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TabResource/loadBaseClientEntityDto'),
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: {
          className: _self.tab.tabDataSource.className,
          recordId: _self.modelData.id,
        },
        success: function (data) {
          _self.baseData = data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 页数改变
    getPageParams: function (page, pageSize) {
      this.pagination.current_page = page;
      this.pagination.per_page = pageSize;
      this.queryGridData();
    },

    queryGridData: function () {
      this.audit();
    },
    compare: function () {
      var _self = this;
      _self.checkedDataList = [];
      _self.gridData.dataList.forEach(function (modelData) {
        if (modelData.select) {
          _self.checkedDataList.push(modelData);
        }
      });
      if (_self.checkedDataList.length < 2) {
        Notify.error('未选择数据', '请至少选择两个要对比的数据。', false);
        return;
      } else {
        _self.setShowCompareData();
        $('#showAuditData').hide();
        $('#compareAuditData').show();
      }
    },
    showAuditData: function () {
      $('#showAuditData').show();
      $('#compareAuditData').hide();
    },
    //将选择的数据格式化为竖向排列
    setShowCompareData: function () {
      let _self = this;
      _self.showCompareData = [];
      _self.selectVersions = [];
      //首先填入版本号
      for (let i = 0, len = _self.checkedDataList.length; i < len; i++) {
        _self.selectVersions.push(_self.checkedDataList[i].data['version'].displayValue[0]);
      }

      //对每一列的字段进行处理
      for (var i = 0, len1 = _self.tab.fields.length; i < len1; i++) {
        _self.showCompareData[i] = {
          'name': _self.tab.fields[i].name,
          'fieldName': _self.tab.fields[i].fieldName,
          'entityFieldIndex': _self.tab.fields[i].entityFieldIndex,
          'data': [],
          'isSame': true                };
        //讲该列需要审计的所有结果放入showCompareData的data中，并判断该列数据是否发生过变化,isSame=true表示未发生过变化
        for (var j = 0, len2 = _self.checkedDataList.length; j < len2; j++) {
          if (_self.checkedDataList[j].data[_self.showCompareData[i].fieldName] != undefined) {
            _self.showCompareData[i].data.push(_self.checkedDataList[j].data[_self.showCompareData[i].fieldName].displayValue[_self.showCompareData[i].entityFieldIndex]);
          }
          else {
            _self.showCompareData[i].data.push('');
          }
          //该列数据是否发生过变化等价于所有数据都和第一项数据相同
          if (_self.showCompareData[i].data[j] != _self.showCompareData[i].data[0]) {
            _self.showCompareData[i].isSame = false;
          }
        }
      }
    },
    checkboxChanged: function (modelData, index) {
      this.gridData.dataList[index]=modelData;
    },
        
    displayValue: function (modelData, field) {
      var fieldName = field.fieldName;
      if (modelData.data[fieldName] != undefined && modelData.data[fieldName].displayValue != undefined
                && modelData.data[fieldName].displayValue.length > 0) {
        return modelData.data[fieldName].displayValue[field.entityFieldIndex];
      }
      return '';
    },

  },
};

</script>

<style scoped>
.table-div {
    overflow: scroll;
}

.fixed-table {
    table-layout: fixed;
    /* width: 1200px !important; */
}

table.fixed-table tr th {
    text-align: center;
}

table.fixed-table td {
    text-align: center;
    word-wrap: break-word;
    word-break: normal;
}
#compareTable {
    border-collapse: collapse;
}
#compareTable tr td {
    border-bottom: 1px solid #dedede;
    text-align: center;
}
h5 {
    font-weight: bold;
}
.table-footer-right {
    float: right;
}
</style>