<template>
  <div class="by-table">
    <vxe-table
      ref="table"
      :data="value"
      :size="attrs.size?attrs.size:'small'"
      sync-resize
      auto-resize
      :edit-rules="attrs.editRules"
      :height="attrs.height"
      :max-height="attrs.maxHeight"
      :stripe="attrs.stripe"
      :border="attrs.border"
      :align="attrs.align"
      :tree-config="{transform: attrs.transform, rowField: attrs.rowField, parentField: attrs.parentField}"
      :row-config="{isHover: true}"
      :tooltip-config="{showAll: true}"
      :radio-config="{trigger: attrs.triggerRowCheck}"
      :checkbox-config="{ checkMethod: attrs.checkMethod, visibleMethod: attrs.visibleMethod,trigger: attrs.triggerRowCheck}">
      style="width: 100%">
      <vxe-column v-if="attrs.checkbox" type="checkbox" width="50" fixed="left" />
      <vxe-column v-if="attrs.radio" type="radio" width="50" fixed="left" />
      <vxe-column v-if="attrs.seq" type="seq" title="序号" :width="attrs.seqWidth?attrs.seqWidth:50" fixed="left" :tree-node="attrs.treeNodeSeq" />
      <template v-for="(item,index) of columns">
        <vxe-column
          v-if="item.action"
          :key="'action_'+index"
          :title="item.title"
          :width="item.width"
          resizable
          fixed="right"
        >
          <template #default="{ row }">
            <template v-if="item.plugins">
              <template v-for="(pluginsItem,_index) of item.plugins" >
                <span class="col-action" 
                  :key="'plu'+_index" 
                  v-if="showPlugin(pluginsItem,row)"
                  @click="pluginClick(pluginsItem,row)">
                  <i v-if="pluginsItem.icon" :class="pluginsItem.icon" ></i>
                  {{ pluginsItem.name }}
                </span>
              </template>
            </template>
          </template>
        </vxe-column>
        <vxe-column
          v-if="!item.action"
          :key="item.field+index"
          :field="item.field"
          :title="item.title"
          :width="item.width"
          :fixed="item.fixed"
          resizable
          :align="item.align"
          :tree-node="item.treeNode"
        >
          <template #default="scope">
            <slot v-if="item.slot" :name='item.field' :row='scope.row'></slot>
            <component v-else-if="item.component" :is="item.component" :ref="item.field+'Comp'" :propConfig="item.compConfig" :parentValue="scope.row"
              :propValue="scope.row[item.field]" @onChange="onChange($event, scope,item.field)" />
            <template v-else>
              <div v-if="item.isDetail" :class="{'ellipsis':item.ellipsis}" :title="scope.row[item.field]" :style="{ 'text-align': item.align }" class="tdCol detail" @click="detail(scope.row)">
                {{ item.formatField ? formatField(item,scope.row) : scope.row[item.field] }}
              </div>
              <div class="tdCol" :class="{'ellipsis':item.ellipsis}" :title="scope.row[item.field]" :style="{ 'text-align': item.align }" v-else>
                {{ item.formatField ? formatField(item,scope.row) : scope.row[item.field] }}
              </div>
            </template>
            
          </template>
        </vxe-column>
      </template>
    </vxe-table>
    <div class="page" v-if="page.total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="attrs.pageSizes"
        :page-size="page.pageSize?page.pageSize:20"
        :layout="attrs.layoutPage?attrs.layoutPage:'total, sizes, prev, pager, next, jumper'"
        :total="page.total">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
  import { computed,getCurrentInstance  } from "vue";
  import lodash from 'lodash'
  import ExcelHelper from '@/benyun/utils/excelHelper'

  const { proxy,ctx:that } = getCurrentInstance();
  const value = ref([]);
  const key_id = ref("_X_ROW_KEY")
  const page = ref({
    pageNo: 1, //当前页
    pageSize: 20, //每页条数
    total: 0 //总条数
  })
  const config = ref([])
  const emit = defineEmits();

  const props = defineProps({
    propConfig:{},
    propValue:{},
    parentValue:{}
  })

  const columns = computed({
    get() {
      return config.value.columns ? config.value.columns : [];
    }
  })
  const requestConfig = computed({
    get() {
      return config.value.request ? config.value.request : null;
    }
  })
  const attrs = computed({
    get() {
      return config.value.attr ? config.value.attr : {};
    }
  })
  const getUuid = () => {
    return (((1 + Math.random()) * 0x10000) | 0).toString(3).substring(1);
  }
  //设置配置
  const setConfig = (c) => {
    if(c){
      config.value = c;
    }
    setConfigAfter()
  }
  //获取配置
  const getConfig = () =>{
    return lodash.cloneDeep(config)
  }
  const setConfigAfter= () => {
    if(attrs.value.pageSize){
      page.value.pageSize = attrs.value.pageSize;
    }
    recalculate();
  }
  const recalculate = () => {
    if(proxy.$refs.table){
      proxy.$refs.table.recalculate(true);
      proxy.$forceUpdate();
    }
  }
  const loadTableData = (data) => {
    if(proxy.$refs.table){
      proxy.$refs.table.loadData(data);
    }
  }
  //点击详情
  const detail= row => {
    let data = lodash.cloneDeep(row);
    delete data[key_id.value];
    emit('detail',data)
  }
  //设置分页
  const setPage = pageParams => {
    if(pageParams.pageNo){
      page.value.pageNo = pageParams.pageNo;
    }
    if(pageParams.pageSize){
      page.value.pageSize = pageParams.pageSize;
    }
    page.value.total = pageParams.total?pageParams.total:0;
  }
  const getPage = () => {
    return page.value
  }
  //每页条数发生变化
  const handleSizeChange = val => {
    page.value.pageSize = val;
    if (page.value.pageSize * val > page.value.total) {
      page.value.pageNo = 1
    }
    emit('pagination',{pageNum:page.value.pageNo,pageSize:page.value.pageSize})
  }
  //当前页发生变化
  const handleCurrentChange = val => {
    page.value.pageNo = val;
    emit('pagination',{pageNum:page.value.pageNo,pageSize:page.value.pageSize})
  }
  //操作列点击操作
  const pluginClick = (config,row) => {
    if(config?.event?.click){
      config.event.click(row)
    }
  }
  //操作按钮是否显示
  const showPlugin = (config,row) => {
    if(config?.event?.show){
      let data = lodash.cloneDeep(row)
      delete data[key_id.value];
      return config.event.show(data)
    }
    return true
  }
  //格式化内容
  const formatField = (config,row) => {
    if(config.formatField){
      return config.formatField(row)
    }
  }
  //组件值的变化
  const onChange = (val,item,code) => {
    proxy.$refs.table.updateStatus(item);
    let row = item.row;
    if(val && val.constructor == Object){
      for (const key in val) {
        row[key] = val[key]
      }
    }else{
      row[code] = val
    }
    emit('onChangeRow',row);
  }
  const fileName = () => {
    let date = new Date();
    return  String(date.getFullYear()) + String(date.getMonth() + 1) + String(date.getDate()) + getUuid(3)
  }
  //获取表格选中的数据
  const getSelectData = () => {
    let data = []
    if (proxy.$refs.table) {
      if (attrs.value.radio && proxy.$refs.table.getRadioRecord()) {
        data = lodash.cloneDeep([proxy.$refs.table.getRadioRecord()]);
      } 
      if(attrs.value.checkbox && proxy.$refs.table.getCheckboxRecords()){
        data = lodash.cloneDeep(proxy.$refs.table.getCheckboxRecords());
      }
    }
    for(let item of data){
      delete item[key_id.value];
    }
    return data
  }
  //导出
  const onExport = name => {
    let ExcelHead = []
    let data = proxy.lodash.cloneDeep(value.value);
    data.forEach((item,index) => {
      for(const key in item){
        if(item[key] === 0){
          item[key] = '0'
        }
      }
      item.index =  String(index + 1)
    });

    if(attrs.value.seq){
      ExcelHead.push({
        text: '序号',
        value: 'index',
        width: '50'
      })
    }
    for(const item of columns.value) {
      if(!item.action) {
        let excelHeadConfig = {
          text: item.title,
          value: item.field,
          width: item.width ? item.width : '150'
        }
        ExcelHead.push(excelHeadConfig)
      }
    }

    const excelHelper = new ExcelHelper()
    excelHelper.success = () => {
      proxy.$message({
        message: '下载成功！',
        type: 'success'
      })
    }
    excelHelper.toExcel({
      // sheetName:'内容',
      fileName: name ? name + '.xlsx' : fileName() + '.xlsx',
      data: data,
      otherData: {ExcelHead}
    })

    // const $table = proxy.$refs.table
    // if ($table) {
    //   $table.exportData({ type: v?v:'csv' })
    // }
  }
  //清除选中
  const clearCheckboxRow = () => {
    if(attrs.value.checkbox){
      proxy.$refs.table.clearCheckboxRow();
    }
    if(attrs.value.radio){
      proxy.$refs.table.clearRadioRow();
    }
  }
  const setValue = data => {
    value.value = data ? data : [];
    proxy.$refs.table.clearValidate()
    proxy.$forceUpdate()
  }
  const getValue = () => {
    let d = lodash.cloneDeep(value.value);
    for(let item of d){
      delete item[key_id.value];
    }
    return d;
  }
  const requestHandle = () => {
    if(!requestConfig.value || !requestConfig.value.url){
      return
    }
    let parame = lodash.cloneDeep(requestConfig.value);
    proxy.request(parame).then(res => {
      setValue(res.data);
    }).catch(err => {})
  }
  if(props.propConfig){
    setConfig(props.propConfig)
  }
  
  defineExpose({
    getValue,setValue,clearCheckboxRow,getSelectData,setPage,getPage,loadTableData,getConfig,setConfig,recalculate,onExport
  })
</script>

<style lang="scss" scoped>
.by-table{
  width: 100%;
  .page{
    width: 100%;
    display: flex;
    padding-top: 16px;
    justify-content: flex-end;
  }
  .tdCol{
    width: 100%;
  }
  .ellipsis{
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.col-action{
  color: #0089ff;
  cursor: pointer;
  padding: 0 4px;
}
.detail{
  color: #0089ff;
  cursor: pointer;
}
</style>