<template>
  <div id='UserfilesList' class="flex">
    <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>
          <modal :show.sync="$parent.$parent.upshow" width="500px" title="文件导入" v-ref:modal large backdrop="false">
            <article slot="modal-body" class="modal-body">
              <file-upload class="my-file-uploader " name="UploadFile" class="btn btn-success"
                           style="border-radius: 2px;"
                           action="rs/file/uploadFile" tagname="导入" v-ref:filebattch :headers="headers"
                           multiple>
              </file-upload>
            </article>
            <footer slot="modal-footer" class="modal-footer">
            </footer>
          </modal>
          <div class="row">
            <div class="col-sm-3 form-group">
              <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="col-sm-3 form-group">
              <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 = '{}'" placeholder='用户姓名'>
            </div>

            <div class="form-group button-range" style="float: right">
              <button class="button_search button_spacing" @click="$parent.$parent.clickupshow()" v-if="$parent.$parent.f_civill_id">导入用户</button>
              <button  class="button_search button_spacing" style="width: 90px" @click="$parent.$parent.downloadFiles()">模板下载</button>
              <button class="button_search button_spacing" @click="$parent.$parent.addUser(true)" v-if="$parent.$parent.f_civill_id">添加用户</button>
              <button class="button_search button_spacing" @click="$parent.$parent.removeUser(true)" v-if="$parent.$parent.f_civill_id">解除关系</button>
              <button class="button_search button_spacing" @click="search()">查询</button>
              <button class="button_clear button_spacing" @click="clear">清空</button>
              <div style="float: right" class="button_spacing"
                   :class="{'button_shrink_top': criteriaShow,'button_shrink_bottom': !criteriaShow}"
                   @click="criteriaShow = !criteriaShow"></div>
            </div>
          </div>
          <div class="row" v-show="criteriaShow">
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用户电话</label>
              <input type="text" class="form-control" v-model="model.f_user_phone" placeholder='用户电话'
                     condition="f_user_phone like '%{}%'" v-next-el='yhxm' style="width: 60%"
              >
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">客户类型</label>
              <v-select :options='$parent.$parent.user_type' :value.sync="model.f_user_type"
                        close-on-select condition="f_user_type='{}'"
                        placeholder='用户类型' v-model="model.f_user_type"></v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">客户状态</label>
              <v-select :options='$parent.$parent.user_state' :value.sync="model.f_user_state"
                        close-on-select condition="f_user_state = '{}'"
                        placeholder='客户状态' v-model="model.f_user_state"></v-select>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">抄&nbsp;表&nbsp;员&nbsp;</label>
              <v-select :value.sync="model.f_inputtor" v-model='model.f_inputtor'
                        style="width:60%"
                        :multiple="true"
                        condition="f_inputtor in {}"
                        :options='$parent.$parent.inputtores' placeholder='抄表员'
                        close-on-select
                        v-el:cc></v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用气性质</label>
              <v-select :options='$parent.$parent.gasproperties' :value.sync="model.f_gasproperties"
                        close-on-select condition="f_gasproperties='{}'"
                        placeholder='用气性质' v-model="model.f_gasproperties"></v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">气表类型</label>
              <v-select :options='$parent.$parent.meter_classify' :value.sync="model.f_meter_classify"
                        close-on-select condition="f_meter_classify='{}'" value-single
                        placeholder='气表类型' v-model="model.f_meter_classify"></v-select>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">气表品牌</label>
              <v-select :value.sync="model.f_meter_brand" multiple
                        v-model="model.f_meter_brand"
                        :options='$parent.$parent.meterbrands' placeholder='请选择'
                        condition="f_meter_brand in {}"
                        close-on-select></v-select>
            </div>
            <div class="col-sm-3 form-group">
              <label class="font_normal_body">小&emsp;区&emsp;</label>
              <input type="text" class="input_search" v-model="model.f_residential_area" style="width: 60%"
                     condition=" f_residential_area like '{}%'" placeholder="输入小区">
            </div>
            <div class="form-group col-sm-3">
              <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="col-sm-3 form-group">
              <label class="font_normal_body">楼&emsp;号&emsp;</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_building"
                     condition="f_building = '{}'" placeholder='楼号'>
            </div>
          </div>
        </div>
      </criteria>
      <data-grid :optional="true" class="list_area table_sy" :model="model" partial='list' v-ref:grid>
        <template partial='head'>
          <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>
        </template>
        <template partial='body'>
          <td>{{ $index + 1 }}</td>
          <td>{{ row.f_userinfo_code }}</td>
          <td>{{ row.f_user_name }}</td>
          <td>{{ row.f_user_state }}</td>
          <td>{{ row.f_address }}</td>
          <td>{{ row.f_meternumber }}</td>
          <td>{{ row.f_meter_base }}</td>
        </template>
      </data-grid>
    </criteria-paged>
    <modal v-if="addmeterinfoshow" :show="addmeterinfoshow" width="80%" v-ref:modal :backdrop="false">
      <header slot="modal-header" class="modal-header">
        <span class="glyphicon glyphicon-remove closebtn" @click="addUser(false)"></span>
      </header>
      <article slot="modal-body" class="modal-body" style="height: 700px">
        <userfiles-list :f_filialeids.sync="f_filialeids" v-ref:userlist></userfiles-list>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-default" @click='addUser(false)'>取消</button>
        <button type="button" class="btn btn-primary" @click='confirmAddUser()'>确认</button>
      </footer>
    </modal>
  </div>
</template>

<script>
import {HttpResetClass, PagedList} from 'vue-client'

export default {
  name: 'UserfilesList',
  data () {
    return {
      model: new PagedList('rs/sql/ncmeterQuery', 20),
      f_orgid: '',
      gasproperties: this.$appdata.getParam('用气性质') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用气性质')] : [],
      user_type: this.$appdata.getParam('用户类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')] : [],
      meter_classify: [{label: '机表', value: '机表'}],
      user_state: [{label: '正常', value: '正常'}, {label: '预备', value: '预备'}, {label: '销户', value: '销户'}],
      meterbrands: [],
      addmeterinfoshow: false,
      upshow: false,
      HttpReset: new HttpResetClass(),
    }
  },
  props: {
    f_filialeids: {
      type: String
    },
    // 团缴主键
    f_civill_id: {
      type: Number
    }
  },
  ready () {
    this.$refs.paged.$refs.cri.model.f_meter_classify = '机表'
    this.loadParamGem()
  },
  methods: {
    downloadFiles () {
      let downurl = 'rs/downloadfile/file?filename=团缴用户导入模板'
      this.$downFile(downurl,'团缴用户导入模板.xlsx')
    },
    clickupshow () {
      this.upshow = !this.upshow
    },
    async loadParamGem () {
      await this.$LoadParams.loadParam()
      await this.initAdjustables()
      await this.$refs.paged.$refs.cri.search()
    },
    async initAdjustables () {
      // 初始化气表品牌
      let brandArr = []
      this.$GetSaleParam.getGasbrand().forEach((item) => {
        let temp1 = {}
        temp1.label = item.label
        temp1.value = item.value.f_meter_brand
        brandArr.push(temp1)
      })
      this.meterbrands = [{label: '全部', value: ''}, ...brandArr]
    },
    selfSearch (args) {
      if (!this.f_orgid) {
        this.getorg([this.f_filialeids])
      }
      if (this.f_civill_id) {
        args.condition = `${args.condition} and f_civill_id = ${this.f_civill_id}`
      } else {
        args.condition = `${args.condition} and (f_civill_id is null or f_civill_id = '')`
      }
      args.condition = `${args.condition} and f_orgid in ${this.f_orgid}`
      this.model.search(args.condition, args.model)
      this.$refs.paged.$refs.grid.selectInit()
    },
    getorg (val) {
      this.f_orgid = this.$login.convertToIn(val)
    },
    addUser (flag) {
      this.addmeterinfoshow = flag
    },
    async confirmAddUser () {
      let dataArr = this.$refs.userlist.$refs.paged.$refs.grid.getRowData()
      if (dataArr.length == 0) {
        this.$showMessage(`当前未选中任何用户, 请核实!!!`)
        return
      }
      let res = await this.$showMessage(`当前选中${dataArr.length}条用户, 确认建立团缴关系吗?`, ['confirm', 'cancel'])
      if (res == 'confirm') {
        let ids = []
        for (let row of dataArr) {
          ids.push(row.f_userfiles_id)
        }
        ids = this.$login.convertToIn(ids)
        let param = {
          ids: ids,
          f_civill_id: this.f_civill_id
        }
        await this.$resetpost('rs/logic/updateCivill', param, {resolveMsg: '建立团缴关系成功', rejectMsg: '建立团缴关系失败!!!'})
        this.addUser(false)
        this.$refs.paged.$refs.cri.search()
      }
    },
    async removeUser () {
      let dataArr = this.$refs.paged.$refs.grid.getRowData()
      if (dataArr.length == 0) {
        this.$showMessage(`当前未选中任何用户, 请核实!!!`)
        return
      }
      let res = await this.$showMessage(`当前选中${dataArr.length}条用户, 确认解除团缴关系吗?`, ['confirm', 'cancel'])
      if (res == 'confirm') {
        let ids = []
        for (let row of dataArr) {
          ids.push(row.f_userfiles_id)
        }
        ids = this.$login.convertToIn(ids)
        let param = {
          ids: ids
        }
        await this.$resetpost('rs/logic/updateCivill', param, {resolveMsg: '解除团缴关系成功', rejectMsg: '解除团缴关系失败!!!'})
        this.$refs.paged.$refs.cri.search()
      }
    }
  },
  computed: {
    inputtores () {
      // 获取抄表员
      console.log('获取抄表员', this.$login.f)
      let rs = []
      if (this.$login.f.f_gasman.length > 0) {
        for (let i = 0; i < this.$login.f.f_gasman.length; i++) {
          let temp = {
            label: this.$login.f.f_gasman[i].name,
            value: this.$login.f.f_gasman[i].name
          }
          rs.push(temp)
        }
      }
      this.inputtores2 = rs
      return [...rs]
    }
  },
  watch: {
    'f_civill_id' () {
      this.$refs.paged.$refs.cri.search()
    }
  },
  events: {
    onFileUpload: function (file, res) {
      console.log('进入了团缴导入')
      let uuid = this.$login.guid()
      let data1 = {
        f_civill_id: this.f_civill_id,
        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,
        uuid: uuid
      }
      console.log('传入数据', data1)
      try {
        this.$resetpost('rs/logic/importCivill', data1, {resolveMsg: null, rejectMsg: null}, 1000)
      } catch (e) {}
      this.$showAlert(`文件上传成功,正在后台批量处理, 请耐心等待结果......`, 'warning')
      // 启动定时器定时查询处理结果
      let timer = setInterval(async () => {
        let res = await this.HttpReset.load('POST', 'rs/logic/getBatchOperaPro', {data: {uuid: uuid}}, {resolveMsg: null, rejectMsg: null})
        console.log('查询进度返回: ', res)
        if (res.data.msg || res.data.error) {
          clearInterval(timer)
          if (res.data.error) {
            this.$showAlert(`${res.data.error}`, 'danger')
            return
          }
          this.$showAlert(`${res.data.msg}`, 'success', 2000)
          this.upshow = false
          this.$refs.paged.$refs.cri.search()
        }
      }, 5000)
    }
  }
}
</script>

<style lang="less">
#UserfilesList {
  tr {
    th {
      text-align: center;
    }

    td {
      text-align: center;
    }
  }
}
</style>
