<template>
  <div class="binary">
    <div class="basic-main" >
      <div class="flex" style="flex: 1;">
        <div style="flex: 1.2">
    <criteria-paged :model="model" v-ref:paged>
      <criteria partial='criteria' @condition-changed='$parent.search' v-ref:cri>
        <div class="form-horizontal select-overspread container-fluid auto" novalidate  partial>
          <div class="row">
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用户编号</label>
              <input  type="text" class="form-control" v-model="model.f_userinfo_code" placeholder='用户编号' v-filter v-figure_filter
                      condition="f_userinfo_code = '{}'" v-next-el='username'  style="width: 60%"
                      :size="model.f_userinfo_code ? model.f_userfiles_id.length  : 4">
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用户姓名</label>
              <input  type="text" class="form-control" v-model="model.f_user_name" placeholder='用户姓名'
                      condition="f_user_name like '%{}%'" v-next-el='area'  style="width: 60%"
                      :size="model.f_user_name ? model.f_user_name.length * 2 : 4">
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">收费状态</label>
              <v-select :options='$parent.$parent.sellState'
                        :value.sync="model.f_sell_state"
                        close-on-select
                        :value-single="true"
                        condition="f_sell_id {}"
                        placeholder='收费状态'
                        v-model="model.f_sell_state">
              </v-select>
            </div>
            <div class="span" style="float:right;">
              <button class="button_search button_spacing width-60" @click="search()" v-el:cx>查询</button>
              <button class="button_clear button_spacing width-60" @click="$parent.$parent.arrcreate()">附件上传</button>
              <export-excel
                :data="{condition: $parent.$parent.condition}"
                :field="$parent.$parent.getfield"
                sqlurl="rs/logic/saleExport" progress="saleGetExportProgress" sql-name="getGovernmentList" template-name='数据导出'
                :choose-col="true">
              </export-excel>
              <button class="button_clear button_spacing width-60" v-if="model.f_sell_state ==='is null'" @click="$parent.$parent.batchGovernmentSell()">批量缴费</button>
              <button v-show="$parent.$parent.rollback" class="button_clear button_spacing width-60" @click="$parent.$parent.retrun()"  v-el:cba>返回</button>
              <div
                :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                @click="$parent.$parent.hidden()" class="button_spacing" style="float: right">
              </div>
            </div>
          </div>
          <div class="row" v-show="$parent.$parent.criteriaShow">
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">身份证号</label>
              <input  type="text" class="form-control" v-model="model.f_idnumber" placeholder='请输入'
                      condition="f_idnumber = '{}'" v-next-el='area'  style="width: 60%"
                      :size="model.f_idnumber ? model.f_idnumber.length * 2 : 4">
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">地&nbsp;&nbsp;&nbsp;&nbsp;址</label>
              <input  type="text" class="form-control" v-model="model.f_address" placeholder='请输入'
                      condition="f_address like '%{}%'" v-next-el='area'  style="width: 60%"
                      :size="model.f_idnumber ? model.f_idnumber.length * 2 : 4">
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">用户表号</label>
              <input  type="text" class="form-control" v-model="model.f_meternumber" placeholder='请输入'
                      condition="f_meternumber = '{}'" v-next-el='area'  style="width: 60%"
                      :size="model.f_meternumber ? model.f_meternumber.length * 2 : 4">
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">批次号</label>
              <input  type="text" class="form-control" v-model="model.f_batchno" placeholder='请输入'
                      condition="f_batchno = '{}'" v-next-el='area'  style="width: 60%"
                      :size="model.f_batchno ? model.f_batchno.length * 2 : 4">
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">充值时间</label>
              <datepicker placeholder="充值开始时间"
                          style="width:60%"
                          class="datepicker"
                          v-model="model.f_sell_date"
                          condition="f_sell_date>='{}'"
                          :value.sync="model.f_sell_date"
                          :format="'yyyy-MM-dd HH:mm:ss'"
              ></datepicker>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">结束时间</label>
              <datepicker placeholder="充值开始时间"
                          style="width:60%"
                          class="datepicker"
                          condition="f_sell_date<='{}'"
                          v-model="model.f_sell_date_end"
                          :value.sync="model.f_sell_date_end"
                          :format="'yyyy-MM-dd HH:mm:ss'"
              ></datepicker>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">导入时间</label>
              <datepicker placeholder="导入开始时间"
                          style="width:60%"
                          v-model="model.f_operate_date"
                          condition="f_operate_date>='{}'"
                          :value.sync="model.f_operate_date"
                          :format="'yyyy-MM-dd HH:mm:ss'"
              ></datepicker>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">结束时间</label>
              <datepicker placeholder="导入结束时间"
                          style="width:60%"
                          condition ="f_operate_date<='{}'"
                          v-model="model.f_operate_date_end"
                          :value.sync="model.f_operate_date_end"
                          :format="'yyyy-MM-dd HH:mm:ss'"
              ></datepicker>
            </div>
          </div>
        </div>
      </criteria>
      <data-grid  :model="model" partial='list' class="table_sy"  v-ref:grid>
        <template partial='head'>
          <tr>
            <th>
              <input type="checkbox"  @click="$parent.$parent.$parent.isAll(model.pageIndex)">
            </th>
            <th>序号</th>
            <th>批次号</th>
            <th>用户编号</th>
            <th>用户姓名</th>
            <th>身份证号</th>
            <th>地址</th>
            <th>表号</th>
            <th>补贴金额</th>
            <th>付款方式</th>
            <th>备注</th>
            <th>表具类型</th>
            <th>导入时间</th>
            <th>充值时间</th>
            <th>补气编号</th>
          </tr>
        </template>
        <template partial='body'>
          <td style="text-align:center">
            <input type="checkbox" v-model="$parent.$parent.$parent.ids"
                   :value="row.f_userfiles_id">
          </td>
          <td>{{$index+1}}</td>
          <td style="text-align:center">{{row.f_batchno}}</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_idnumber}}</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_preamount}}</td>
          <td style="text-align:center">{{row.f_payment}}</td>
          <td style="text-align:center">{{row.f_comments}}</td>
          <td style="text-align:center">{{row.f_meter_brand}}</td>
          <td style="text-align:center">{{row.f_operate_date}}</td>
          <td style="text-align:center">{{row.f_sell_date}}</td>
          <td style="text-align:center">{{row.f_sell_id}}</td>
        </template>
      </data-grid>
    </criteria-paged>
    </div>
  </div>
</div>
</div>
  <modal :show.sync="arrshow" width="570px" title="文件导入" v-ref:modal large backdrop="false">
    <article slot="modal-body" class="modal-body">
      <file-upload class="my-file-uploader col-sm-9" name="useraddressUploadFile" action="rs/file/uploadFile"
                   tagname="确定" multiple v-ref:file></file-upload>
      <button class="button_clear btn-gn" style="margin-top: 10px;background-color: #6aa6e2;"
              @click="downloadFiles()">模板下载
      </button>
    </article>
    <footer slot="modal-footer" class="modal-footer">
    </footer>
  </modal>
  <modal :show.sync="progressShow" v-ref:modal   width="50%" style="width:auto;" backdrop="false" >
    <header slot="modal-header" class="modal-header">
      批量建档
    </header>
    <article slot="modal-body" class="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>
      <div style="width:100%;display: flex">
        <p style="text-align: center;width: 100%;" v-show="!downbutton">文件正在导入..</p>
        <p style="text-align: center;width: 100%;" v-show="downbutton">导入成功:{{inputsuccessmage}}</p>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-default" @click='closeRequeset'>关闭</button>
    </footer>
  </modal>
</template>

<script>
  /**
   *阶梯水价查询列表
   */
  // eslint-disable-next-line standard/object-curly-even-spacing

  import {HttpResetClass, PagedList} from 'vue-client'
  import Vue from 'vue'
  import axios from 'axios'
  export default {
    data () {
      return {
        HttpReset: new HttpResetClass(),
        allSelect: false,
        arrshow: false,
        condition: '',
        ids: [],
        sellState: [{label: '已交', value: 'is not null'}, {label: '未交', value: 'is null'}],
        pages: [],
        model: new PagedList('rs/sql/getGovernmentList', 50, {}),
        batchMeterShow: false,
        criteriaShow: false,
        range2: [],
        progressShow: false, // 进度条显示
        percent: 0, // 进度条百分比
        downbutton: false,
        inputsuccessmage: '',
        getfield: {
          'f_batchno': '批次号',
          'f_userinfo_code': '用户编号',
          'f_user_name': '用户姓名',
          'f_idnumber': '身份证号',
          'f_address': '地址',
          'f_meternumber': '表号',
          'f_preamount': '补贴金额',
          'f_comments': '备注',
          'f_meter_brand': '表具类型',
          'f_operate_date': '导入时间',
          'f_sell_date': '充值时间',
          'f_sell_id': '充值编号'
        }
      }
    },
    title: '政府补贴',
    ready () {
      this.$refs.paged.$refs.cri.model.f_operate_date = this.$login.toStandardDateString() + ' 00:00:00'
      this.$refs.paged.$refs.cri.model.f_operate_date_end = this.$login.toStandardDateString() + ' 23:59:59'
      // this.search({condition: `1=1 `, model: this.$refs.paged.$refs.cri.model})
    },
    methods: {
      progressclose () {
        if (this.timer != null) {
          clearInterval(this.timer)
        }
        this.progressShow = false
        this.percent = 0
      },
      closeRequeset () {
        // 判断进度是否已完成
        if (this.percent === 100) {
          // 已完成导入，直接关闭并清理
          if (this.timer != null) {
            clearInterval(this.timer)
          }
          this.progressclose()
          this.percent = 0
          this.uuida = ''
          this.downbutton = false
        } else {
          // 进度未完成，弹出确认关闭的提示
          this.$showMessage('确定关闭吗？当前正在导入，关闭后将无法获取导入进度！', ['confirm', 'cancel']).then(res => {
            if (res === 'confirm') {
              if (this.timer != null) {
                clearInterval(this.timer)
              }
              this.progressclose()
              this.percent = 0
              this.uuida = ''
              this.downbutton = false
            }
          })
        }
      },
      async getRequestReturn (uuid) {
        let self = this
        let param = {
          uuid: uuid
        }
        console.log(param)
        console.log('=============')
        this.timer = setInterval(function () {
          self.$resetpost('/rs/logic/getBatchOperaPro', {data: param}, {resolveMsg: null, rejectMsg: null}, 0).then((res) => {
            if (res.data && res.data.speed) {
              if (res.data.speed == 100 || res.data.speed > 100) {
                clearInterval(self.timer)
                self.percent = 99
                setTimeout(function () {
                  self.percent = 100
                  self.inputsuccessmage = `本次上传共上传${res.data.totalsum}条数据, 成功${res.data.successsum}条,失败${res.data.errorsum}条，具体失败数据请在稽查查询错误查询中查看！！`
                  self.downbutton = true
                }, 100)
              } else {
                self.percent = res.data.speed
              }
            }
          })
        }, 2000)
      },
      batchGovernmentSell () {
        if (this.ids.length === 0 && !this.allSelect) {
          return this.$showMessage('请选择缴费的用户')
        }
        if (this.ids.length !== 0 && !this.allSelect) {
          this.$refs.paged.$refs.cri.condition = this.$refs.paged.$refs.cri.condition ? this.$refs.paged.$refs.cri.condition : '1=1'
          this.condition = this.$refs.paged.$refs.cri.condition + ' and f_userfiles_id in (' + this.ids + ')'
        }
        if (this.allSelect) {
          this.$refs.paged.$refs.cri.condition = this.$refs.paged.$refs.cri.condition ? this.$refs.paged.$refs.cri.condition : '1=1'
          this.condition = this.$refs.paged.$refs.cri.condition
        }
        let userinfo = {
          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
        }
        let uuid = this.$login.guid()
        let data = {
          uuid: uuid,
          condition: this.condition,
          userinfo: userinfo
        }
        try {
          this.$resetpost('rs/govsell/all', {data: data}, {resolveMsg: null, rejectMsg: null}, 500)
        } catch (e) {}
        this.$showMessage(`正在批量处理中, 请耐心等待...`, [])
        // 启动定时器定时查询处理结果
        this.timer = setInterval(async () => {
          let res = await this.HttpReset.load('POST', 'rs/logic/getBatchOperaPro', {data: {uuid: uuid}}, {resolveMsg: null, rejectMsg: null})
          console.log(typeof (res))
          console.log(res)
          this.$showMessage(`正在批量处理中, 正在处理第>>>${res.data.n}户`, [])
          if (res.data.msg || res.data.error) {
            clearInterval(this.timer)
            this.$closeMessage()
            if (res.data.error) {
              this.$showAlert(`${res.data.error}`, 'danger')
              return
            }
            await this.$showMessage(`审核总条数: ${res.data.sum}, 成功${res.data.success}条, 失败${res.data.fail}条`)
            this.search(this.$refs.paged.$refs.cri)
          }
        }, 5000)
      },
      downloadFiles () {
        let downurl = 'rs/downloadfile/file?filename=政府补贴导入Excel模板'
        this.$downFile(downurl, '政府补贴导入Excel模板.xlsx')
      },
      hidden () {
        this.criteriaShow = !this.criteriaShow
      },
      search (args) {
        this.condition = null
        args.condition = `${args.condition} and f_orgid = ` + `'${Vue.$login.f.orgid}'`
        this.condition = args.condition
        console.log('查看条件', args.condition)
        this.model.search(args.condition, args.model)
      },
      arrcreate () {
        this.arrshow = true
      },
      isAll (page) {
        this.allSelect = !this.allSelect
        if (this.pages.includes(page)) { // 已添加,取消动作
          // 从ids中删除本页所有数据的ids
          this.addOrRemove(false)
          this.pages = this.pages.filter((item) => {
            return item !== page
          })
        } else { // 未添加
          this.pages.push(page) // 添加id，添加动作
          this.addOrRemove(true)
        }
      },

      addOrRemove (is) {
        let that = this
        if (is) { // 添加本页所有数据到ids中
          this.model.rows.forEach((row) => {
            if (!that.ids.includes(row.f_userfiles_id)) {
              that.ids.push(row.f_userfiles_id)
            }
          })
        } else { // 从ids中取消所有的数据
          this.model.rows.forEach((row) => {
            that.ids = that.ids.filter((item) => {
              return item !== row.f_userfiles_id
            })
          })
        }
      }
    },
    computed: {

    },
    events: {
      'onFileUpload': async function (file, res) {
        if (this.batchMeterShow) {
          this.iswork = true
          // 当前上传的是批量导入的档案
          let param = {
            filepath: res.f_downloadpath,
            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
          }
          let self = this
          try {
            await axios.post('rs/logic/newSettleFileImport',
              {data: param}, {timeout: 10 * 60 * 1000}).then((res) => {
                if (res.data) {
                  self.$showMessage(`本次上传共上传${res.data.totalsum}条数据, 成功${res.data.successnum}条,失败${res.data.errorsum}条，具体失败数据请在稽查查询错误查询中查看！！`)
                  self.iswork = false
                // this.$showAlert('导入成功','success',2000)
                }
              })
          } catch (error) {
            if (error.response) {
              if (error.response.status == 500) {
                this.$showAlert('服务繁忙,请重试!!!', 'danger', 3000)
              } else if (error.response.status == 404) {
                this.$showAlert('服务运行中,请耐心等待后进行重试!!', 'danger', 3000)
              } else {
                this.$showAlert(error.response.data, 'danger', 2000)
              }
              console.log(error.response.data)
              console.log(error.response.status)
              console.log(error.response.headers)
            } else if (error.request) {
              console.log(error.request)
              this.$showAlert(error.request, 'danger', 2000)
            } else {
              console.log('Error', error.message)
              this.$showAlert(error.message, 'danger', 2000)
            }
            this.iswork = false
          }
          this.batchMeterShow = false
          // this.$showAlert(`一共上传${res.data.total}条数据, 成功${res.data.successnum}条`, 'success', 2000)
          this.$refs.paged.$refs.cri.model.search()
        } else {
          let uuid = this.$login.guid()
          let data = {
            uuid: uuid,
            tablename: 't_government_charge',
            filepath: res.f_downloadpath,
            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
          }
          // this.$resetpost('rs/logic/governmentSellImport', {data: data}, {
          //   resolveMsg: null,
          //   rejectMsg: '上传失败'
          // }).then((res) => {
          //   this.arrshow = false
          //   this.$showAlert(`一共上传${res.data.totalsum}条数据, 成功${res.data.successnum}条`, 'success', 2000)
          //   this.search(this.$refs.paged.$refs.cri)
          // })
          let self = this
          try {
            self.progressShow = true
            axios.post('rs/logic/governmentSellImport',
              {data: data}, {timeout: 1000}).then((res) => {
              })
            self.percent = 0
            self.getRequestReturn(uuid)
          } catch (error) {
            if (error.response) {
              if (error.response.status == 500) {
                this.$showAlert('服务繁忙,请重试!!!', 'danger', 3000)
              } else if (error.response.status == 404) {
                this.$showAlert('服务运行中,请耐心等待后进行重试!!', 'danger', 3000)
              } else {
                this.$showAlert(error.response.data, 'danger', 2000)
              }
            } else if (error.request) {
              this.$showAlert(error.request, 'danger', 2000)
            } else {
              this.$showAlert(error.message, 'danger', 2000)
            }
            this.iswork = false
          }
          this.$refs.file.$el.querySelector('input').value = ''
          this.batchMeterShow = false
          this.search()
        }
      }
    }
  }
</script>
<style>
  .form-group{
    height: 30px;
  }
</style>
