<template>
  <div class="aos-table-form clearfix" ref="AosTableFormContainer">
    <aos-form
      ref="form"
      v-if="showAddForm"
      :data="copyFormData"
      :edit="true"
      :formTemplate="copyFormTemplate">
      <div slot="footer" class="aos-table-form-add-footer">
        <el-button @click="handleTableFormAddCancel">取消</el-button>
        <el-button type="primary" @click="handleTableFormAddClick">确认</el-button>
      </div>
    </aos-form>
    <el-table
      class="aos-table-form-table"
      :data="tableData"
      ref="table"
      stripe
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @expand-change="handleExpandChange">
      <el-table-column
        v-if="tableFormTemplate.selection && tableFormTemplate.selection.showSelection"
        type="selection"
        :selectable="selectable"
        :width="tableFormTemplate.selection.width">
      </el-table-column>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <aos-form
            ref="expandForm"
            :data="scope.row"
            :edit="expandEdit"
            :formTemplate="copyFormTemplate">
            <div slot="footer">
              <el-button v-if="showExpandButton && !expandEdit" type="primary" @click="handleTableFormItemEdit(scope)">编辑</el-button>
              <el-button v-if="showExpandButton && expandEdit" @click="handleTableFormItemCancel(scope)">取消</el-button>
              <el-button v-if="showExpandButton && expandEdit" type="primary" @click="handleTableFormItemClick(scope)">确认</el-button>
            </div>
          </aos-form>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in copyTabelTemplate"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :min-width="item.minWidth || '100px'"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :sortable="item.sortable">
        <template slot-scope="scope" >
          <slot v-if="item.showSlot" :name="item.prop + '-slot'" :scope="scope"></slot>
          <template v-else-if="item.type === 'defdoc'">
            <aos-defdoc
              :value="scope.row[item.prop]"
              :editable="false"
              :defCode="item.defCode"
              :tag="item.tag"
              :multiple="item.multiple"
              :no-def-code="item.noDefCode"
              :orm-code="item.ormCode"
              :orm-name="item.ormName"
              :orm-status="item.ormStatus"
              :orm-data="item.ormData"
              :customerUrl="item.customerUrl"></aos-defdoc>
          </template>
          <template v-else-if="item.type === 'rule-defdoc'">
            <aos-rule-defdoc :value="scope.row[item.prop]" :editable="false" :defCode="item.attrs.defCode" :multiple="item.attrs.multiple"></aos-rule-defdoc>
          </template>
          <template v-else-if="item.type === 'ref'">
            <aos-ref :value="scope.row[item.prop]" :editable="false" :refCode="item.attrs.refCode" :filters="item.filters" :multiple="item.attrs.multiple" :onlyTranslate="true" :translateRefValueLable="scope.row[item.prop + 'Label']"></aos-ref>
          </template>
          <template v-else-if="item.type === 'money'">
            <aos-money :editable="false" v-model="scope.row[item.prop]" :decimal="item.decimal || 2" :suffixString="item.suffixString"></aos-money>
          </template>
          <template v-else-if="item.type === 'city'">
            <aos-city :templateValue="scope.row" :edit="false" :province="item.province" :city="item.city" :county="item.county"></aos-city>
          </template>
          <template v-else-if="item.type === 'date-picker'">
            <span>{{ $time.formatTime(scope.row[item.prop], ((item.attrs && item.attrs.format) || ''))}}</span>
          </template>
          <span v-else :title="scope.row[item.prop]">{{scope.row[item.prop]}}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableFormTemplate.operationColumn && tableFormTemplate.operationColumn.showOperation"
        :fixed="tableFormTemplate.operationColumn.fixed"
        :label="tableFormTemplate.operationColumn.label"
        :width="tableFormTemplate.operationColumn.width || '50'">
        <template slot-scope="scope">
          <div class="aos-table-form-operation">
            <slot v-if="tableFormTemplate.operationColumn.showOperationSlot" name="operation-slot" :scope="scope"></slot>
            <i v-for="icon in tableFormTemplate.operationColumn.iconList" 
              :key="icon.code" 
              class="aos-table-form-icon"
              :class="'el-icon-'+icon.icon" 
              :title="icon.title"
              @click="handleIconClick(icon.code,scope)"></i>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="aos-table-form-pagination"
        v-if="showPagination && total > 5"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page="currentPage"
        :page-sizes="[5,10,20,30,40,50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
</div>
</template>
<script>
import ElTable from '../../table';
import ElPagination from '../../pagination';
import AosForm from '../../aos-form'
import cloneDeep from 'lodash/cloneDeep'
// import {addResizeListener,removeResizeListener} from 'aos-element/src/utils/resize-event.js'
export default {
  name: 'AosTableForm',
  components: {
    ElTable,
    ElPagination,
    AosForm
  },
  props:{
    // form绑定的数据
    formData: {
      type: Object,
      required: true
    },
    // table绑定的数据
    tableData: {
      type: Array,
      required: true,
      default: function(){
        return []
      }
    },
    // table构成列属性
    tableFormTemplate: {
      type: Object,
      required: true
    },
    // 是否显示分页
    showPagination: {
      type: Boolean,
      default: true
    },
    // 分页的当前页
    currentPage: {
      type: Number,
      default: 1
    },
    // 分页的页的数量
    pageSize: {
      type: Number,
      default: 10
    },
    // 当前table数据总共的数量
    total: {
      type: Number,
      default: 0
    },
    // 是否显示新增的表单
    showAddForm: {
      type: Boolean,
      default: false
    },
    // 是否显示行内表单的操作按钮
    showExpandButton: {
      type: Boolean,
      default: true
    },
    // 展开行表单的编辑状态
    expandEdit: {
      type: Boolean,
      default: false
    },
    // 当使用复选框是设置复选框是否可选
    selectable: {
      type: Function,
      default: function () {
        return function () { return true }
      }
    }
  },
   computed: {
    copyFormData: {
      get: function(){
        this.currentAddFormData = JSON.parse(JSON.stringify(this.formData));
        return this.formData;
      },
      set: function(){
      },
    },
    // tableData: {
    //   get: function(){
    //     return this.tableData;
    //   },
    //   set: function(){}
    // },
    copyFormTemplate () {
      let formTemplate = []
      this.tableFormTemplate.tableFormItem.forEach(item => {
        if (item.formShow === undefined || item.formShow) {
          formTemplate.push(item)
        }
      })
      return formTemplate
    },
    copyTabelTemplate () {
      let tableTemplate = []
      this.tableFormTemplate.tableFormItem.forEach(item => {
        if (item.tableShow === undefined || item.tableShow) {
          tableTemplate.push(item)
        }
      })
      return tableTemplate
    },
    refPropList () {
      let refPropList = []
      if (this.copyTabelTemplate) {
        this.copyTabelTemplate.forEach(item => {
          if (item.type === 'ref') {
            refPropList.push(item)
          }
        });
      }
      return refPropList
    }
  },
  watch: {
    tableData: {
      handler: function(val, oldVal) {
        if (val && Array.isArray(val)) {
          this.translateRef(val)
        }
      },
      deep: true,
      immediate: true
    }
  },
  data(){
    return {
      currentAddFormData: {},
      currentTableItemData: {},
      tableHeight: 0,
      refValueDataListObject: {}
    }
  },
  methods: {
    // 多选框选择事件
    handleSelectionChange(data){
      this.$emit('table-form-selection-change',data);
    },
    handleRowClick(row,column,event){
      this.currentRowData = JSON.parse(JSON.stringify(row));
      this.$emit('table-form-row-click',row,column,event);
    },
    // 抛出操作列点击按钮
    handleIconClick(type,scope){
      this.$emit('table-form-'+type+'-click',scope)
    },
    // 当前数量改变
    handleSizeChange(size){
      this.$emit('table-form-size-change',size);
    },
    // 当前页数改变
    handleCurrentChange(page){
      this.$emit('table-form-current-change',page);
    },
    // 点击上一页
    handlePrevClick(page){
      this.$emit('table-form-prev-click',page);
    },
    // 点击下一页
    handleNextClick(page){
      this.$emit('table-form-next-click',page);
    },
    // table 详细编辑
    handleTableFormItemEdit(scope){
      this.$emit('update:expandEdit',true);
      this.$emit('table-form-expand-edit',scope);
    },
    // table 详细取消
    handleTableFormItemCancel(scope){
      this.$emit('update:expandEdit',false);
      this.tableData[scope.$index] = JSON.parse(JSON.stringify(this.currentTableItemData));
      this.$emit('table-form-expand-cancel',scope);
    },
    // table 详细保存
    handleTableFormItemClick(scope){
      this.$emit('table-form-expand-confirm',scope);
    },
    // table-form form新增取消
    handleTableFormAddCancel(){
      this.$emit('table-form-add-cancel',this.copyFormData);
    },
    // table-form form新增确定
    handleTableFormAddClick(){
      this.$emit('table-form-add-confirm',this.copyFormData);
    },
    // table-form 列展开
    handleExpandChange(row,expandedRows){
      if(expandedRows.length > 1){
        expandedRows.shift();
      }
      this.currentTableItemData = JSON.parse(JSON.stringify(row));
    },
    resizeTableHeight(){
      this.$nextTick(() => {
        let boxHeight = this.$refs.AosTableFormContainer.parentElement.parentElement.offsetHeight;
        if(boxHeight < 600){
          this.tableHeight  = boxHeight - 99
        } else {
          this.tableHeight  = 600;
        }
      })
    },
    translateRef (val) {
      if (val.length > 0 && this.refPropList.length > 0) {
        // 拿到对应prop列的值
        this.refPropList.forEach(item => {
          this.$set(this.refValueDataListObject, item.prop, {})
          val.forEach((dataItem, index) => {
            if (dataItem && !dataItem[item.prop + 'Label']) {
              this.$set(dataItem, item.prop + 'Label', '');
            }
            if (!this.refValueDataListObject[item.prop].valueList) {
              this.$set(this.refValueDataListObject[item.prop], 'valueList', [])
            }
            if (!this.refValueDataListObject[item.prop].labelValueList) {
              this.$set(this.refValueDataListObject[item.prop], 'labelValueList', [])
            }
            if (!this.refValueDataListObject[item.prop].labelValueObject) {
              this.$set(this.refValueDataListObject[item.prop], 'labelValueObject', {})
            }
            if (dataItem[item.prop]) {
              this.refValueDataListObject[item.prop].valueList.push(dataItem[item.prop])
            }
          });
        });
        let allGetLabel = []
        this.refPropList.forEach(item => {
          // this.getRefLabel(item.refCode, this.refValueDataListObject[item.prop])
          allGetLabel.push(this.getRefLabel(item.attrs.refCode, this.refValueDataListObject[item.prop]))
        })
        window.Promise.all(allGetLabel).then(() => {
          this.refPropList.forEach(item => {
            val.forEach((dataItem, index) => {
              if (this.refValueDataListObject[item.prop].labelValueObject[dataItem[item.prop]]) {
                dataItem[item.prop + 'Label'] = this.refValueDataListObject[item.prop].labelValueObject[dataItem[item.prop]]
              } else {
                dataItem[item.prop + 'Label'] = dataItem[item.prop]
              }
            });
          });
          this.$emit('update: tableData', val)
        })
      }
    },
    getRefLabel(refCode, refValueDataListObject) {
      if (!refCode) {
        this.$message({
          type: 'error',
          message: '参照对应的 refCode 不能为空.'
        });
        return;
      }
      const paramsData = refValueDataListObject.valueList.join(',')
      if (!paramsData) {
        return;
      }
      return this.$optimizeHttp({
        url: '/core/api/ref/translate/' + refCode,
        method: 'get',
        params: {
          code: paramsData
        }
      }).then(res => {
        refValueDataListObject.labelValueList = cloneDeep(res.data);
        refValueDataListObject.labelValueObject = this.arrayToObject(refValueDataListObject.labelValueList)
      })
    },
    arrayToObject (array) {
      if (!array && !Array.isArray(array))  return {}
      let object = {}
      array.forEach(item => {
        object[item.code] = item.value
      })
      return object
    },
  },
  
  // mounted(){
  //   addResizeListener(this.$refs.AosTableFormContainer,this.resizeTableHeight);
  // },
  // beforeDestroy(){
  //   removeResizeListener(this.$refs.AosTableFormContainer,this.resizeTableHeight);
  // }
}
</script>

