<template>
  <div>
    <!-- <a style="color: #808695" @click="openModal">
      <Icon type="md-download" size="22" style="margin:-5px 0px "/>
      <span style="font-size: 8px">导出</span></a> -->
       <Button type="primary" @click="openModal">导出</Button>
 
      <Modal
      v-model="modal"
      title="导出"
      width="550px"
      scrollable
      @on-ok="exportClick"
      @on-cancel="cancel">
      <div style="margin-left: 20px">
      <p style="font-size: 15px">导出范围<br></p>
      <RadioGroup v-model="exprotType" style="margin-top: 20px" size="large">
        <Radio v-if="result" label="result" >查询结果</Radio>
        <Radio v-if="all" label="all" style="margin-left: 20px">所有数据</Radio>
        <Radio v-if="selected" label="selected" style="margin-left: 20px">选中数据</Radio>
        <Radio v-if="nowPage" label="nowPage" style="margin-left: 20px">当前页面</Radio>
      </RadioGroup>
      <p style="margin-top: 30px;font-size: 15px">导出文件类型<br></p>
      <Input style="margin-top: 15px;width: 390px;text-align: left" value="csv" readonly></Input>
      </div>
      <template #footer>
      <div style="text-align: left;margin-left: 20px">
        <Button @click="exportClick" type="primary">开始导出</Button>
      </div>
      </template>
    </Modal>
  </div>
</template>

<script>
  /*import {getUserLayoutColumns,saveUserLayoutColumns} from '@/api/base/layout-columns-api'*/

  let $this;
  export default {
    name: "bcExportExcel",
    props: {
      excelName: {
        type: String,
        default: `table-${(new Date()).valueOf()}`,
      },
      selected: {
        type: Boolean,
        default: true
      },
      nowPage: {
        type: Boolean,
        default: true
      },
      result: {
        type: Boolean,
        default: true
      },
      all: {
        type: Boolean,
        default: true
      },
      selectedData: {
        type: Array,
        default: function () {
          return []
        },
      },
      tableData: {
        type: Array,
        default: function () {
          return []
        },
      },
      dataColumns: {
        type: Array,
        default: function () {
          return []
        },
      },
      searchForm: {
        type: Object,
        default: function () {
          return {}
        },
      },
      getData: Function,
    },
    data() {
      return {
        params: [],
        modal: false,
        exprotType: 'result'
      }
    },
    methods: {
      openModal() {
        this.modal = true
      },
      cancel() {
        this.modal = false
      },
      exportClick() {
        switch (this.exprotType) {
          case 'selected':
            this.exportExcelSelected();
            break;
          case 'nowPage':
            this.exportExcelNowPage();
            break;
          case 'result':
            this.exportExcelResult();
            break;
          case 'all':
            this.exportExcelAll();
            break
        }
        this.modal=false;
      },
      exportExcelSelected() {
        if (this.selectedData.length === 0) {
          this.$Message.warning('请选择数据！')
          return;
        }
        this.$emit('export-data', {
          filename: this.excelName + '.csv',
          columns: this.handleMultiTableHeader(this.dataColumns, false),
          data: this.filterData(this.selectedData),
        });
      },
      exportExcelNowPage() {
        this.$emit('export-data', {
          filename: this.excelName + '.csv',
          columns: this.handleMultiTableHeader(this.dataColumns, false),
          original: false,
          data: this.filterData(this.tableData),
        })
      },
      exportExcelResult() {
        this.getData(this.searchForm).then(res => {
          let excelData = res.data.result;
          this.$emit('export-data', {
            filename: this.excelName + '.csv',
            columns: this.handleMultiTableHeader(this.dataColumns, false),
            data: this.filterData(excelData),
          })
        }).catch(err => {
          this.$Message.error('导出失败！')
          console.log(err)
        })
      },
      exportExcelAll() {
        this.getData().then(res => {
          let excelData = res.data.result;
          this.$emit('export-data', {
            filename: this.excelName + '.csv',
            columns: this.handleMultiTableHeader(this.dataColumns, false),
            data: this.filterData(excelData),
          })
        }).catch(err => {
          this.$Message.error('导出失败！')
          console.log(err)
        })
      },
      filterData(data) {
        let newData = JSON.parse(JSON.stringify(data));
        let columsFilter=[];
        if(this.dataColumns && this.dataColumns.length>0){
          for(let i=0;i<this.dataColumns.length;i++){
            if(this.dataColumns[i].ifText){
              columsFilter.push(this.dataColumns[i].key)
            }
          }
        }
        if(columsFilter.length>0){
          newData.forEach(n => {
            for(let j=0;j<columsFilter.length;j++){
              n[columsFilter[j]]=n[columsFilter[j]]?n[columsFilter[j]]+'\t':''
            }
          });
        }
        return newData;
      },
      handleMultiTableHeader(columns, noSubTitle) {
        let columnsC=JSON.parse(JSON.stringify(columns));
        for(let i=columnsC.length-1;i>=0;i--){
          if(columnsC[i].ifNotExport){
            columnsC.splice(i,1)
          }
        }
        noSubTitle = noSubTitle || false;//主要目的就是就子级的表头全部循环加上父级的名称前缀,然后再 flat 将数组拉平
        let cols = columnsC.map(res => {
          if (res.hasOwnProperty('children')) {
            return res.children.map(item => {
              if (item.hasOwnProperty('children')) {
                return item.children.map(cc => {
                  cc.title = `${noSubTitle ? '' : `${item.title.substring(item.title.indexOf('_') + 1)}_`}${cc.title}`
                  return cc
                })
              } else {
                item.title = `${noSubTitle ? '' : `${res.title.substring(res.title.indexOf('_') + 1)}_`}${item.title}`
                return item
              }
            })
          } else {
            return res
          }
        }).flat(Infinity);
        cols.forEach((n, i) => {
          if (n.export === false) {
            cols[i] = {};
          }
        });
        return cols;
      },
    },
    mounted() {
      $this = this;
    }
  }
</script>

<style scoped>

</style>
