<template>
  <button class="button_export button_spacing" @click='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">
      <h4 class="modal-title">导出列选择</h4>
      <input type="checkbox" class="" id="f_operator" v-model="all">
      <label for="f_operator" class="font-size">全选</label>
    </header>
    <article slot="modal-body">
      <div class="auto col-sm-11 col-md-offset-1"  style="margin-top: 10px;">
        <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>
    </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" type="button" class="btn btn-success" @click='export()'>导出</button>
      </center>
    </footer>
  </modal>
</template>

<script>
import co from 'co'

let postGen = function * (self) {

  let p = {}
  // 判断如果有field，说明表头为自动生成，否则为模板导出
  if (self.exporthead) {
    if(self.sqlName){
      p = yield self.$resetpost(self.sqlurl, {data: {body: {sumName:self.sumname,data: self.data, field: self.exporthead, templateName: self.templateName, sqlName: self.sqlName}, bean: self.bean}}, {resolveMsg: null, rejectMsg: null}, 0)
    }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}, 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}, bean: self.bean}}, {resolveMsg: null, rejectMsg: null}, 0)
  }
  var link = document.createElement('a');
  p.data.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 xy="http://"
    let pathName = xy + 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.modelval = []
  self.fields = {}
  self.exporthead = []
}
export default {
  // data:sql需要的替换字段
  // sqlurl:导出Excel查询的sql语句
  // field:需要导出Excel的字段名和对应中文名或hbm配置文件名（全名）
  // total:统计字段（统计行）
  // props: ['data', 'sqlurl', 'field', 'total', 'bean', 'chooseCol','sumName'],
  data () {
    return {
      show: false,
      all: false,
      fields: {},
      modelval: [],
      // 表头
      exporthead: [],
      selftotal:[]
      // sumName:[]
    }
  },
  props: {
    sumname:{

    },
    data: {},
    sqlurl: {
      type: String
    },
    field: {},
    total: {},
    bean: {
      type: String
    },
    btnName: {
      type: String,
      default: '导出Excel'
    },
    templateName: {
      type: String
    },
    sqlName: {
      type: String
    },
    pathName: {
      type: String
    },
    attach: {
      type: String,
      default: 'name'
    },
    chooseCol: {
      type: Boolean,
      default: false
    }
  },
  methods: {

    exportExcel () {
      //tag
      if (this.field) {
        if (this.chooseCol === true){
          this.fields = this.field
          this.show = true
        } else {
          this.data.items = '*'
          Object.keys(this.field).forEach((key)=>{
            this.exporthead.push(key+':'+this.field[key])
          })
          this.post()
        }
      } else {
        this.post()
      }
    },
    export () {
      // 获取导出选择的表头和列
      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
      //tag
      this.post()
      this.close()
    },
    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="合计"
      // }
      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.all = false
      this.modelval = []
      this.show = false
    },
  },
  watch: {
    'all' (val) {
      if (val) {
        this.modelval = Object.keys(this.fields)
      } else {
        this.modelval = []
      }
    },
    'modelval.length' () {
      this.sortModelval()
    }
  }
}
</script>
