<template>
  <button v-show="isshow" class="button_export button_spacing" @click.prevent='exportExcel()'
          :id="'vc-exportexcel-'+attach">{{ btnName }}
  </button>
  <modal :show.sync="show" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header text-center">
      <div v-show="!progressShow">
        <h4 class="modal-title">导出列选择</h4>
        <input type="checkbox" class="" id="f_operator" v-model="all">
        <label for="f_operator" class="font-size">全选</label>
      </div>
      <div v-show="progressShow">
        <h4 class="modal-title">导出中,请耐心等待...</h4>
      </div>
    </header>
    <article slot="modal-body">
      <div class="auto col-sm-11 col-md-offset-1" style="margin-top: 10px;" v-show="!progressShow">
        <div class="col-sm-4" v-for="f in fields">
          <input type="checkbox" class="" :id="'export-col-'+$index" v-model="modelval" :value="$key">
          <label :for="'export-col-'+$index" class="font-size">{{ f }}</label>
        </div>
      </div>
      <div class="progress" style="margin: 20px" v-show="progressShow">
        <div class="progress-bar progress-bar-success progress-bar-striped active" :style="{width: percent}">
          {{ percent }}
        </div>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <center>
        <button v-show="show" type="button" class="btn btn-default" @click='close()'>取消</button>
        <button v-show="show && !progressShow" type="button" class="btn btn-success" @click='export()'>导出</button>
      </center>
    </footer>
  </modal>
</template>

<script>
import co from 'co'
import {HttpResetClass} from 'vue-client'
import Vue from "vue";

let postGen = function* (self) {
  try {
    let p = {}
    // 判断如果有field，说明表头为自动生成，否则为模板导出
    if (self.exporthead) {
      if (self.sqlName) {
        p = yield self.$resetpost(self.sqlurl, {
          data: {
            body: {
              header: self.header,
              footer: self.footer,
              sumName: self.sumname,
              data: self.data,
              field: self.exporthead,
              templateName: self.templateName,
              sqlName: self.sqlName,
              uuid: self.uuid
            },
            bean: self.bean
          }
        }, {resolveMsg: null, rejectMsg: null}, 1000)
      } else if (self.pathName) {
        p = yield self.$resetpost(self.sqlurl, {
          data: {
            body: {
              sumName: self.sumname,
              data: self.data,
              field: self.exporthead,
              templateName: self.templateName,
              pathName: self.pathName,
              uuid: self.uuid
            },
            bean: self.bean
          }
        }, {resolveMsg: null, rejectMsg: null}, 0)
      }
    } else {
      p = yield self.$resetpost(self.sqlurl, {
        data: {
          body: {sumName: self.sumname, data: self.data, total: self.total, uuid: self.uuid},
          bean: self.bean
        }
      }, {resolveMsg: null, rejectMsg: null}, 0)
    }
  } catch (e) {
    console.error(e)
  }
  self.modelval = []
  self.fields = {}
  self.exporthead = []
  self.progressQuery()
}

export default {
  //uuid:需要导出的Excel对应的key
  // data:sql需要的替换字段
  // sqlurl:导出Excel查询的sql语句
  // field:需要导出Excel的字段名和对应中文名或hbm配置文件名（全名）
  // total:统计字段（统计行）
  // props: ['data', 'sqlurl', 'field', 'total', 'bean', 'chooseCol','sumName'],
  data() {
    return {
      uuid: '',
      show: false,
      all: false,
      fields: {},
      modelval: [],
      // 表头
      exporthead: [],
      selftotal: [],
      // sumName:[],
      // 进度条显示
      progressShow: false,
      // 进度百分比
      percent: '0%',
      // 定时器
      timer: null,
      // 请求对象
      HttpReset: new HttpResetClass()
    }
  },
  props: {
    // 表头
    header: {},
    // 表尾
    footer: {},
    sumname: {},
    data: {},
    sqlurl: {
      type: String
    },
    field: {},
    total: {},
    bean: {
      type: String
    },
    progress: {
      type: String,
      default: 'getExportProgress'
    },
    btnName: {
      type: String,
      default: '导出Excel'
    },
    templateName: {
      type: String
    },
    sqlName: {
      type: String
    },
    pathName: {
      type: String
    },
    attach: {
      type: String,
      default: 'name'
    },
    chooseCol: {
      type: Boolean,
      default: false
    },
    isshow: {
      type: Boolean,
      default: true
    },
    defaultselect: [],
    chooserow: {
      type: Boolean,
      default: false
    }
  },
  beforeDestroy() {
    this.closeTimer()
  },
  methods: {

    exportExcel() {
      //tag
      if (this.field) {
        if (this.chooseCol === true) {
          this.fields = this.field
          this.show = true;
          // //
          if (this.defaultselect != null && this.defaultselect) {
            for (var item in this.defaultselect) {
              this.modelval.push(item)
            }
            if (this.chooserow) {
              this.export()
            }
          }

        } else {
          this.data.items = '*'
          Object.keys(this.field).forEach((key) => {
            this.exporthead.push(key + ':' + this.field[key])
          })
          this.post()
        }
      } else {
        this.post()
      }
    },
    export() {
      if (this.$login.r.includes('限制导出')) {
        this.$showMessage('你被限制导出, 请联系管理员')
        return
      }
      // 获取导出选择的表头和列
      let temp = ''
      this.modelval.forEach((item) => {
        temp = temp + item + ','
        this.exporthead.push(item + ':' + this.field[item])
        //this.exporthead[item] = this.field[item]
      })
      temp = temp.slice(0, temp.length - 1)
      //tag
      this.data.items = temp
      this.post()
    },
    post() {
      // if(this.total) {
      //
      //   var temp={"合计":"合计"}
      //   for (var a in this.field) {
      //     for (var b in this.total) {
      //         if(a==b){
      //           temp[a]=this.total[a]
      //         }
      //     }
      //   }
      //   this.selftotal.push(temp)
      //   //tag
      //   //tag
      //
      //   // this.selftotal.push(this.total)
      //   // this.selftotal[0].a="合计"
      // }
      this.uuid = this.guid();
      let gen = postGen(this)
      co(gen)
    },
    stamp() {
      this.modelval = []
      this.show = true
    },
    sortModelval() {
      let sortModel = []
      Object.keys(this.fields).forEach((key) => {
        if (this.modelval.includes(key)) {
          sortModel.push(key)
        }
      })
      //tag
      this.modelval = sortModel
    },
    close() {
      this.closeTimer()
      this.all = false
      this.modelval = []
      this.show = false
      this.progressShow = false
      this.percent = '0%'
    },
    progressQuery() {
      //tag
      this.progressShow = true
      // 启动定时器之前先关闭定时器,防止之前的定时器未关闭
      this.closeTimer()
      // 立即执行一遍
      this.progressTask()
      this.timer = setInterval(this.progressTask, 3000)
    },
    async progressTask() {
      let self = this
      let url ='rs/logic/getBatchOperaPro'
      if(Vue.$appdata.getSingleValue('安检excel单值')){
        url = 'rs/logic/getBatchOperaProNew'
      }

      let res = await self.HttpReset.load('POST', url,{data: {uuid: self.uuid}}, {resolveMsg: null, rejectMsg: null})
      res = res.data
      //tag
      if (res.error) {
        self.$showAlert(`导出excel错误: ${res.error}`, 'danger', 0)
        self.closeTimer()
      } else {
        // self.$showAlert(`${res.msg}`, 'success', 2000)
        self.percent = (res.percent ? res.percent : 0) + '%'
        // 进度100%
        if (res.fileName && res.percent == 100) {
          var link = document.createElement('a');
          res.fileName.forEach((item) => {
            //tag
            // let path = item.filename.substring(item.filename.indexOf('webapps'), (item.filename.length))
            // let pathName = path.substring(path.indexOf('/') + 1, path.length)
            let path = item.filename
            //webapps这个是在服务器上导出用的
            let pathName = location.protocol + "//" + location.host + "/webapps" + path.split('webapps')[1]
            //excel这个是在本地导出用的
            // let pathName = "http://" + location.host + "/excel" + path.split('excel')[1]
            link.href = pathName;
            link.download = path.split('excel/')[1];
            link.dispatchEvent(new MouseEvent('click'));
          })
          self.close()
        }
      }
    },
    // 关闭定时器
    closeTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    }
  },
  watch: {
    'all'(val) {
      if (val) {
        this.modelval = Object.keys(this.fields)
      } else {
        this.modelval = []
      }
    },
    'modelval.length'() {
      this.sortModelval()
    }
  }
}
</script>
