<template>
  <button class="button_export button_spacing" @click='printData()'>打印</button>
  <modal :show.sync="printshow" 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_generations" v-model="all">
      <label for="f_generations" 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-3" v-for="f in fields">
          <input type="checkbox" class="" :id="'water-owe-details-'+$index" v-model="modelval" :value="$key">
          <label :for="'water-owe-details-'+$index" class="font-size">{{f}}</label>
        </div>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <center>
        <button v-show="printshow" type="button" class="btn btn-default" @click='close()'>取消</button>
        <button v-show="printshow" type="button" class="btn btn-success" @click='print()'>打印</button>
        <print-table-rc :model='model' v-show="false" v-ref:print
                     :printview="printview"
                     :xyprint="xyprint"
                     :top='40' :left='40' :right='40' :bottom='40' :print-name="printName"
                     :thead="thead" :tfoot='tfoot' :attach="attach" :sumhtml="sumhtml"
                     :fields="modelval" :is-selected="isSelected" :printpage="printpage">
        </print-table-rc>
      </center>
    </footer>
  </modal>
</template>

<script>
  import co from 'co'

  export default {
    // data:sql需要的替换字段
    // sqlurl:导出Excel查询的sql语句
    // field:需要导出Excel的字段名和对应中文名或hbm配置文件名（全名）
    // total:统计字段（统计行）
    // props: ['data', 'sqlurl', 'field', 'total', 'bean', 'chooseCol'],
    data () {
      return {
        printshow: false,
        all: false,
        fields: {},
        modelval: [],
        thead: '',
        tfoot: '',
        //合计数据
        sumsmodel: {},
        // 合计超文本
        sumhtml: ''
      }
    },
    props: {
      model: {},
      field: {},
      printview:{},
      xyprint:{},
      starthead: {
        type:String,
        default:''
      },
      titletable: {
        type:String,
        default:''
      },
      printName: {},
      // 默认列
      defaultfield: {},
      // 合计数据
      sumsmodel: {},
      // 合计数据的列名称配置(当没有找到对应合计的名称时,会从field中找)
      sumField: {},
      // 单页合计
      pageSum: null,
      isSelected: {
        type:Boolean,
        default:false
      },
      //设置打印底部信息 如制表人：审核人：。。。
      footinfo: [],
      // 设置打印底部信息  其他信息 格式为二维数组 如：[['1','','','4'],['5','','','8']]
      footmsg: [],
      printpage: {
        type:Boolean,
        default:false
      },
      // 全表汇总信息只在最后一页显示
      sumone: {
        type:Boolean,
        default:true
      },
      attach: {
        type: String,
        default: 'name'
      },
      chooserow: {
        type: Boolean,
        default: false
      }
    },
    methods: {

      async printData () {
        console.log('打印。。。', this.model, this.field, this.printName, this.sumsmodel)

        if (this.model.rows.length === 0) {
          this.$showAlert('请查询需要打印的数据！！', 'warning', 2000)
          return
        }
        this.all = false
        //默认选择要打印的列
        this.modelval = this.defaultfield
        this.fields = this.field
        console.log('所有打印字段',this.fields)
        this.printshow = true
        await this.put()
        if(this.chooserow){
          this.print()
        }
      },

      put () {
        // 对Modelval进行排序
        this.sortModelval()
        this.getfield()
        // 组织头数据
        if(this.titletable!=''){
          this.thead = `<tr><th colspan=${this.modelval.length}><h1>${this.titletable}</h1></th></tr><tr>`
        }else{
          this.thead = `<tr><th colspan=${this.modelval.length}><h1>${this.printName}统计报表</h1></th></tr><tr>`
        }
        if(this.starthead!=''){
          this.thead += `<tr><th colspan=${this.modelval.length}>${this.starthead}</th></tr><tr>`
        }
        for (let key of this.modelval) {
          this.thead += '<td style="text-align: left;">' + this.fields[key] + '</td>'
        }
        this.thead += '</tr>'
      },
      // 对选择的列进行排序
      sortModelval () {
        console.log('选择列进行排序。。。', this.fields, this.modelval)
        let sortModel = []
        Object.keys(this.fields).forEach((key) => {
          if (this.modelval.includes(key)) {
            sortModel.push(key)
          }
        })
        this.modelval = sortModel
        console.log('选择的打印的字段', this.modelval)
      },

      close () {
        this.all = false
        this.modelval = []
        this.printshow = false
        this.$dispatch('print-close')
      },

      print () {
        this.$refs.print.PrintAsFile()
        this.printshow = false
        this.$dispatch('print-data')
      },
      getfield(){
        //合计字段打印
        this.tfoot = ''
        if(this.sumsmodel){
          if (this.sumone) {
            this.sumhtml = `<tr><th colspan=${this.modelval.length} style="border-width: 0;">全表汇总信息: `
            Object.keys(this.sumsmodel).forEach((key) => {
              let keyName = this.sumField[key] ? this.sumField[key] : this.fields[key]
              this.sumhtml += keyName + '合计: ' + `<font color="blue">${this.sumsmodel[key]} </font>`
            })
            this.sumhtml += '</th></tr>'
          } else {
            this.tfoot = `<tr><th colspan=${this.modelval.length} style="border-width: 0;">全表汇总信息: `
            Object.keys(this.sumsmodel).forEach((key) => {
              let keyName = this.sumField[key] ? this.sumField[key] : this.fields[key]
              this.tfoot += keyName + '合计: ' + `<font color="blue">${this.sumsmodel[key]} </font>`
            })
            this.tfoot += '</th></tr>'
          }
        }
        if (this.pageSum) {
          this.tfoot += `<tr>`
          for (let row of this.modelval) {
            let format = this.pageSum[row]
            if (format) {
              this.tfoot += `<td tdata="SubSum" format="${format}" style="border-width: 0;">######</td>`
            } else {
              this.tfoot += `<td style="border-width: 0;"></td>`
            }
          }
          this.tfoot += `</tr>`
        }
        this.tfoot += `<tr><th colspan=${this.modelval.length} style="border-width: 0;">打印时间: ${this.$login.toStandardTimeString()}</th></tr>`
        //设置打印底部信息 如制表人：审核人：。。。
        if(this.footinfo!=null && this.footinfo.length!=0){
          this.tfoot += `<tr><td colspan=${this.modelval.length} style="border-width: 0;"></td></tr><tr>`
          for(let i=0;i<this.footinfo.length;i++){
            this.tfoot += `<th colspan=${this.modelval.length/this.footinfo.length} style="border-width: 0;text-align: left;">${this.footinfo[i]}:</th>`
          }
          this.tfoot += `</tr>`
        }
        // 设置打印底部信息  其他信息 格式为二维数组 如：[['1','','','4'],['5','','','8']]
        if (this.footmsg != null && this.footmsg.length != 0) {
          for (let i = 0; i < this.footmsg.length; i++) {
            this.tfoot += `<tr style="padding:  0 2px 0 2px"><th style="border: 0" colspan=${this.modelval.length} ><table style="width: 100%;border-width: 0;text-align: left;"><tr>`
            for (let j = 0; j < this.footmsg[i].length; j++) {
              // 如果this.footsmg[i]有三个元素 则每个占比 33.33%
              // 如果this.footsmg[i]有四个元素 则每个占比 25%
              this.tfoot += `<td style="border-width: 0;text-align: left;width: ${(Number(1) / Number(this.footmsg[i].length) * 100).toFixed(2)}%">${this.footmsg[i][j]}</td>`
            }
            this.tfoot += `</tr></table></th></tr>`
          }
        }
      },
    },
    watch: {
      'all' (val) {
        if (val) {
          this.modelval = Object.keys(this.fields)
        } else {
          this.modelval = []
        }
      },
      'modelval.length' () {
        this.put()
      }
    },
    computed: {

    }
  }
</script>
