<template>

  <div class="flex" style="flex: 1;">
    <div style="flex: 1.2">
      <criteria-paged :model="model" v-ref:paged>
        <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
          <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row">
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">结算日期</label>
                <datepicker placeholder="结算日期" width='100%'
                            v-model="model.endDate"
                            style="width:60%"
                            :value.sync="model.endDate"
                            :format="'yyyy-MM-dd'"
                ></datepicker>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">用户编号</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_userinfo_code"
                       condition="f_userinfo_code = '{}'" placeholder='用户编号'>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4': $parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">用户姓名</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_user_name"
                       condition="f_user_name like '%{}%'" placeholder='用户姓名'>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">用户地址</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_address"
                       condition="f_address like '%{}%'" placeholder='用户地址'>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">气表表号</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_meternumber"
                       condition="f_meternumber = '{}'" placeholder='气表表号'>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">用户类型</label>
                <v-select :value.sync="model.f_user_type" v-model="model.f_user_type"
                          :options='$parent.$parent.userType' placeholder='用户类型'
                          condition="f_user_type = '{}'"
                          close-on-select></v-select>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">用气性质</label>
                <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"
                          :options='$parent.$parent.gasproperties' placeholder='用气性质'
                          condition="f_gasproperties = '{}'"
                          close-on-select></v-select>
              </div>
              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">气表类型</label>
                <v-select :value.sync="model.f_meter_classify" v-model="model.f_meter_classify"
                          :options='$parent.$parent.meterType' placeholder='气表类型'
                          condition="f_meter_classify = '{}'"
                          :value-single="true"
                          @change="$parent.$parent.getType(model.f_meter_classify)"
                          close-on-select></v-select>
              </div>

              <div class="form-group"
                   :class="{'col-sm-2':!$parent.$parent.$parent.isdetail,'col-sm-4':$parent.$parent.$parent.isdetail}">
                <label class="font_normal_body">气表品牌</label>
                <v-select :value.sync="model.f_meter_brand"
                          v-model="model.f_meter_brand"
                          :options.sync='$parent.$parent.meterbrand' placeholder='气表品牌'
                          condition="f_meter_brand = '{}'"
                          close-on-select></v-select>
              </div>
              <div class="span" style="float:right;margin-top:5px">
                <button class="button_search" @click="$parent.$parent.search()" v-el:cx>查询</button>
                <button class="button_search" @click="$parent.$parent.batchSettlementBefore()" v-el:cx>批量结算
                </button>
                <export-excel
                  :data="{endDate: model.endDate,condition: condition + ` and f_orgid = '${$login.f.orgid}'`}"
                  :field="$parent.$parent.getfield"
                  sqlurl="rs/logic/saleExport" sql-name="gethandinfo" template-name='抄表结算导出'
                  :choose-col="true"></export-excel>
                <div style="float: right"
                     class="button_spacing"
                     :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                     @click="$parent.$parent.hidden()">
                </div>
              </div>
            </div>
          </div>
        </criteria>
        <data-grid :model="model" partial='list' class="list_area table_sy" v-ref:grid>
          <template partial='head'>
            <tr>
              <th>
                <input type="checkbox" v-model="$parent.$parent.$parent.all[model.pageIndex-1]"
                       @change="$parent.$parent.$parent.select()"/>
              </th>
              <th>
                <nobr>序号</nobr>
              </th>
              <th>
                <nobr>用户编号</nobr>
              </th>
              <th>
                <nobr>用户姓名</nobr>
              </th>
              <th>
                <nobr>用户电话</nobr>
              </th>
              <th>
                <nobr>用户地址</nobr>
              </th>
              <th>
                <nobr>表号</nobr>
              </th>
              <th>
                <nobr>气表类型</nobr>
              </th>
              <th>
                <nobr>气表品牌</nobr>
              </th>
              <th>
                <nobr>上期结余</nobr>
              </th>
              <th>
                <nobr>收款</nobr>
              </th>
              <th>
                <nobr>用气量</nobr>
              </th>
              <th>
                <nobr>用气金额</nobr>
              </th>
              <th>
                <nobr>结算类型</nobr>
              </th>
              <th>
                <nobr>上次结算日期</nobr>
              </th>
            </tr>
          </template>
          <template partial='body'>
            <td style="text-align: center;">
              <input :id="'body'+model.pageIndex" type='checkbox'
                     @change="$parent.$parent.$parent.selectOne($event,row,$index)"
                     :checked="$parent.$parent.$parent.ischecked(model.pageIndex-1,$index)"/>
            </td>
            <td style="text-align: center;">{{ $index + 1 }}</td>
            <td style="text-align: center;">{{ row.f_userinfo_code }}</td>
            <td style="text-align: center;">{{ row.f_user_name }}</td>
            <td style="text-align: center;">{{ row.f_user_phone }}</td>
            <td style="text-align: center;">{{ row.f_address }}</td>
            <td style="text-align: center;">{{ row.f_meternumber }}</td>
            <td style="text-align: center;">{{ row.f_meter_classify }}</td>
            <td style="text-align: center;">{{ row.f_meter_brand }}</td>
            <td style="text-align: center;">{{ row.f_last_balance }}</td>
            <td style="text-align: center;">{{ row.f_collection }}</td>
            <td style="text-align: center;">{{ row.f_pregas }}</td>
            <td style="text-align: center;">{{ row.f_preamount }}</td>
            <td style="text-align: center;">{{ row.date_type }}</td>
            <td style="text-align: center;">{{ row.f_account_start_date }}</td>
          </template>
        </data-grid>
      </criteria-paged>
      <modal :show.sync="show" v-ref:modal backdrop="false">
        <header slot="modal-header" class="modal-header text-center">
          <h4 class="modal-title">正在批量处理中, 请耐心等待...</h4>
        </header>
        <article slot="modal-body">
          <div class="progress" style="margin: 20px">
            <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">
        </footer>
      </modal>
      <modal :show.sync="showPrint" v-ref:modal backdrop="false" width="30%">
        <header slot="modal-header" class="modal-header text-center">
          <h4 class="modal-title">请选择打印票据格式</h4>
        </header>
        <article slot="modal-body">
          <div class="row">
            <div class="form-group col-sm-10">
              <label class="font_normal_body">票据格式</label>
              <v-select v-model="f_bill_style"
                        placeholder='票据格式'
                        :value.sync="f_bill_style"
                        :options='printstyle'
                        :value-single="true"
                        close-on-select></v-select>
            </div>
          </div>
        </article>
        <footer slot="modal-footer" class="modal-footer">
          <button type="button" class="btn btn-default" @click='showPrint=!showPrint'>取消</button>
          <button type="button" class="btn btn-info" @click='batchSettlement'>确定</button>
        </footer>
      </modal>
    </div>
  </div>
</template>
<script>
import {PagedList} from 'vue-client'

export default {
  title: '抄表结算',
  data () {
    return {
      model: new PagedList('rs/sql/gethandinfo', 20, {endDate: 'this.model.endDate'}),
      meterbrand: [],
      timer: null,
      showPrint: false,
      criteriaShow: true,
      getfield: {},
      f_bill_style: '',
      config: {
        excelHeaders: {
          'f_userinfo_code': '用户编号',
          'f_address': '用户地址',
          'f_user_name': '用户姓名',
          'f_user_type': '用户类型',
          'f_meternumber': '表号',
          'f_meter_classify': '气表类型',
          'f_meter_brand': '气表品牌',
          'f_last_balance': '上期结余',
          'f_collection': '收款',
          'f_pregas': '用气量',
          'f_preamount': '用气金额',
          'f_account_start_date': '上次结算日期'
        }
      },
      printstyle: this.$appdata.getParam('打印格式'),
      // 要操作的用户
      rowsdata: [],
      meterbrandBak: [],
      gasBrand: [],
      // 控制全选
      all: [],
      // 结算进度进度
      show: false,
      percent: 0,
      // 控制单选
      radio: []
    }
  },
  async ready () {
    this.$refs.paged.$refs.cri.model.endDate = this.$login.toStandardDateString()
    await this.$LoadParams.loadParam()
    let arr = []
    this.gasBrand = this.$GetSaleParam.getGasbrand()
    this.gasBrand.forEach((item) => {
      let temp = {}
      if (item.value.f_meter_type === '物联网表' || item.value.f_meter_type === '机表') {
        temp.label = item.label
        temp.value = item.value.f_meter_brand
        arr.push(temp)
      }
    })
    this.meterbrandBak = [{label: '全部', value: ''}, ...arr]
    this.meterbrand = [{label: '全部', value: ''}, ...arr]
    this.getfield = this.config.excelHeaders
  },
  watch: {
    'model.model.endDate' () {
      this.search()
    }
  },
  methods: {
    batchSettlementBefore () {
      this.showPrint = true
    },
    getType (row) {
      console.log(row)
      let arr = []
      if (row) {
        this.gasBrand.forEach((item) => {
          let temp = {}
          if (item.value.f_meter_type === row) {
            temp.label = item.label
            temp.value = item.value.f_meter_brand
            arr.push(temp)
          }
          this.meterbrand = [{label: '全部', value: ''}, ...arr]
        })
      } else {
        this.meterbrand = this.meterbrandBak
      }
    },
    async batchSettlement () {
      this.mergeRowData()
      if (!this.f_bill_style) {
        return this.$showMessage('请选择票据格式')
      }
      let msg
      if (this.rowsdata.length) {
        msg = `确定对选中的用户进行批量结算吗? 一共${this.rowsdata.length}条`
      } else {
        msg = `确定对查询的所有用户进行批量结算吗? 一共${this.model.count}条`
      }
      try {
        let res = await this.$showMessage(msg, ['confirm', 'cancel'])
        console.log('res==>', res)
        if (res == 'confirm') {
          let uuid = this.$login.guid()
          let data = {
            uuid: uuid,
            f_bill_style: this.f_bill_style,
            condition: this.model.condition,
            dataRow: this.rowsdata,
            f_account_end_date: Date.parse(this.model.model.endDate + ' 23:59:59') > Date.parse(this.$login.toStandardTimeString()) ? this.$login.toStandardTimeString() : this.model.model.endDate + ' 23:59:59',
            endDate: this.model.model.endDate,
            f_operator: this.$login.f.name,
            f_operatorid: this.$login.f.id,
            f_orgid: this.$login.f.orgid,
            f_orgname: this.$login.f.orgs,
            f_depid: this.$login.f.depids,
            f_depname: this.$login.f.deps,
            f_filialeids: this.$login.f.orgid
          }
          console.log(data)
          try {
            await this.$resetpost('rs/batchSettlement/allSettlement', data, {
              resolveMsg: '批量结算成功',
              rejectMsg: '批量结算失败！！'
            })
          } catch (e) {
            console.log('批量结算失败', e)
          }
          this.search()
          // this.$showMessage(`正在批量处理中, 请耐心等待...`, [])
          // this.show = true
          // 启动定时器定时查询处理结果
          // this.timer = setInterval(async () => {
          //   let http = new HttpResetClass()
          //   let res = await http.load('POST', 'rs/batchSettlement/getBatchOperaPro', {uuid: uuid}, {resolveMsg: null, rejectMsg: null})
          //   if (res.data.percent) {
          //     this.percent = res.data.percent
          //   }
          //   if (res.data.redisMsg) {
          //     this.show = false
          //     clearInterval(this.timer)
          //     this.$closeMessage()
          //     await this.$showMessage(res.data.redisMsg)
          //     this.search()
          //   }
          // }, 1500)
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.selectInit()
      }
    },
    // show () {
    //   this.criteriaShow = true
    // },
    hidden () {
      this.criteriaShow = !this.criteriaShow
    },
    initQueryParam () {
      let arr = []
      this.$GetSaleParam.getGasbrand().forEach((item) => {
        let temp = {}
        temp.label = item.label
        temp.value = item.value.f_meter_brand
        arr.push(temp)
      })
      this.meterbrand = [{label: '全部', value: ''}, ...arr]
    },
    search () {
      this.$parent.endDate = this.$refs.paged.$refs.cri.model.endDate
      this.$refs.paged.$refs.cri.search()
      this.$dispatch('search')
    },
    selfSearch (args) {
      // 查询时清空选择的数据,防止出错
      this.selectInit()
      args.condition = `${args.condition} and f_orgid = '${this.$login.f.orgid}'`
      this.model.search(args.condition, args.model)
    },
    // 多选框初始化
    selectInit () {
      this.showPrint = false
      this.f_bill_style = ''
      this.rowsdata = []
      this.all = []
      this.radio = []
    },
    // 合并二维数组并去空
    mergeRowData () {
      let data = []
      // 合并
      for (let array of this.rowsdata) {
        data.push.apply(data, array)
      }
      // 去空
      for (var i = 0; i < data.length; i++) {
        if (data[i] == '' || typeof (data[i]) == 'undefined') {
          data.splice(i, 1)
          i--
        }
      }
      this.rowsdata = data
    },
    select () {
      let index = this.model.pageIndex - 1
      console.log('全选', this.all[index])
      if (!this.radio[index]) {
        this.radio.$set(index, [])
      }
      if (this.all[index]) {
        // 数据
        this.rowsdata[index] = Object.assign([], this.model.rows)
        // 勾选
        for (var i = 0; i < this.model.rows.length; i++) {
          this.radio[index].$set(i, true)
        }
      } else {
        // 数据
        this.rowsdata[index] = []
        // 不勾选
        for (var i = 0; i < this.model.rows.length; i++) {
          this.radio[index].$set(i, false)
        }
      }
    },
    selectOne (event, row, i) {
      console.log('单选', event.target.checked)
      let index = this.model.pageIndex - 1
      if (!this.rowsdata[index]) {
        this.rowsdata[index] = []
      }
      if (!this.radio[index]) {
        this.radio.$set(index, [])
      }
      if (event.target.checked) {
        // 数据
        this.rowsdata[index][i] = row
        // 勾选
        this.radio[index].$set(i, true)
        // 判断是否全部选中
        var allState = true
        if (this.model.rows.length != this.radio[index].length) {
          allState = false
        }
        for (var state of this.radio[index]) {
          if (!state) {
            allState = false
          }
        }
        if (allState) {
          this.all.$set(index, true)
        } else {
          this.all.$set(index, false)
        }
      } else {
        // 数据
        this.rowsdata[index][i] = []
        // 不勾选
        this.radio[index].$set(i, false)
        // 任意取消一个则全选状态设为false
        this.all.$set(index, false)
      }
    }
  },
  computed: {
    ischecked () {
      return function (index, i) {
        // console.log("计算属性")
        if (!this.radio[index]) {
          return false
        }
        return this.radio[index][i]
      }
    },
    userType () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')]
    },
    gasproperties () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('用气性质')]
    },
    meterType () {
      return [{label: '全部', value: ''}, {label: '机表', value: '机表'}, {label: '物联网表', value: '物联网表'}]
    }
  }
}
</script>
