<template>
  <div class="flex-row" >

    <div style="width: 30%;overflow:auto;white-space:nowrap">
      <!--<p style="text-align: center">地址列表</p>-->
      <!--<address-select :show="true" :f_location="{f_locationId: `${$login.f.parent.parentid}`,f_locationType: 't_organization'}"-->
      <!--@re-ref="getLocation" v-ref:addressdelect></address-select>-->
      <tabset v-ref:tabs :close="false" class="nav-tabss">
        <tab header="小区建档">
          <area-list :f_filialeid="$login.f.f_orgids" @re-ref="areaFiles" v-ref:areafiles></area-list>
        </tab>
        <tab header="地址建档">
          <address-files @buildfiles="getLocation" v-ref:addressfiles></address-files>
        </tab>
      </tabset>
    </div>

    <div style="flex: 1.5;width: 70%;height: 100%" class="flex" id="user-files">
      <div class="flex" :class="{'list-1':listshow,'list-2':!listshow}">
        <criteria-paged :model="model" v-ref:paged :pager="!row && !newArea && !areainfo" @sort="sort">
          <criteria partial='criteria' v-ref:criteria @condition-changed="$parent.selfSearch">
            <div novalidate class="form-inline auto" partial>
              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_userinfo_code"
                       condition="f_userinfo_code='{}'" placeholder='用户编号'
                       :size="model.f_userinfo_code ? model.f_userinfo_code.length : 4">
              </div>
              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_user_name"
                       condition="f_user_name like '%{}%'" placeholder='用户姓名'
                       :size="model.f_user_name ? model.f_user_name.length * 2 : 4">
              </div>
              <div class="form-group">
                <input  type="text" class="form-control" v-model="model.f_user_phone" placeholder='电话'
                        condition="f_user_phone = '{}'"
                        :size="model.f_user_phone ? model.f_user_phone.length : 2">
              </div>

              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_residential_area"
                       condition="f_residential_area like '%{}%'" placeholder='小区'
                       :size="model.f_residential_area ? model.f_residential_area.length * 2 : 4">
              </div>
              <div class="form-group">
                <input type="text" class="form-control" v-model="model.f_address"
                       condition="f_address like '%{}%'" placeholder='用户地址'
                       :size="model.f_address ? model.f_address.length * 2 : 4">
              </div>
              <div class="form-group">
                <v-select :value.sync="model.f_user_state" v-model="model.f_user_state"
                          :options='$parent.$parent.userstates' placeholder='用户状态'
                          close-on-select condition="f_user_state='{}'"></v-select>
              </div>
              <div class="form-group">
                <v-select
                  :value.sync="model.f_area"
                  v-model="model.f_area"
                  :options='$parent.$parent.areas'
                  placeholder='片区/管理站'
                  condition="f_slice_area like '%{}%'"
                  close-on-select>
                </v-select>
              </div>
              <div class="form-group">
                <v-select :value.sync="model.f_adjustable_id" :options='$parent.$parent.adjustables' placeholder='调压箱' close-on-select
                          v-model='model.f_adjustable_id'   condition="f_adjustable_id = '{}'" :search='true'></v-select>
              </div>
              <div class="form-group">
                <button class="btn btn-success width-100" @click="search(), $parent.$parent.clean()">查询</button>
              </div>
              <div class="form-group">
                <button class="btn btn-success width-100" @click="$parent.$parent.fileUpload()" title="演示系统暂不支持" :disabled="true">导入</button>
              </div>
              <div class="form-group">
                <button class="btn btn-success width-100" @click="$parent.$parent.bulkOperations('抄表员调整', 'change-meter-reader')" title="演示系统暂不支持" :disabled="true">抄表员调整</button>
              </div>
              <div class="form-group">
                <button class="btn btn-success width-100" v-if="$parent.$parent.rows && $parent.$parent.rows.length === 1 && $parent.$parent.rows[0].f_user_state === '正常'"
                        @click="$parent.$parent.bulkOperations('批量销户', 'batch-cancellation')">销户</button>
              </div>
              <div class="form-group">
                <button class="btn btn-success width-100"  v-if="$parent.$parent.rows && $parent.$parent.rows.length === 1 && $parent.$parent.rows[0].f_user_state === '销户'"
                        @click="$parent.$parent.bulkOperations('批量启用', 'batch-enable')">启用</button>
              </div>
            </div>
          </criteria>
          <data-grid :model="model" v-ref:grid  partial='list'>
            <template partial='head'>
              <tr>
                <th><nobr>序号</nobr></th>
                <th>
                  <data-order field="f_userinfo_code" name="用户编号" :order.sync="$parent.$parent.$parent.orderFields.f_userinfo_code"></data-order>
                </th>
                <th><nobr>用户信息</nobr></th>
                <th><nobr>地址信息</nobr></th>
                <th><nobr>状态</nobr></th>
                <th><nobr>操作</nobr></th>
                <!-- <th v-show= "$parent.$parent.$parent.jurisdiction.includes('档案修正权限')"><nobr>操作</nobr></th> -->
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align: center;">{{$index + 1}}</td>
              <td>{{row.f_userinfo_code}}</td>
              <td>{{row.f_user_name}}&nbsp;&nbsp;{{row.f_user_phone ? row.f_user_phone : ''}}</td>
              <td>{{row.f_address_detail ? row.f_address + row.f_address_detail : row.f_address}}</td>
              <td style="text-align: center;">{{row.f_user_state}}</td>
              <td style="text-align: center;">
                <!-- <td style="text-align: center;" v-show= "$parent.$parent.$parent.jurisdiction.includes('档案修正权限')"> -->
                <button type="button" name="button" class="btn btn-link" v-if="row.f_user_state === '正常'"
                        @click.stop="$parent.$parent.$parent.modifyUser(row)">修正</button>
                <button type="button" name="button" v-if="row.f_user_state !== '正常' && row.f_user_state !== '销户'" class="btn btn-link"
                        @click.stop="$parent.$parent.$parent.buildFile(row)">建档</button>
              </td>
            </template>
          </data-grid>
        </criteria-paged>
      </div>
      <div style="height: 500px;" v-show="row || newArea || areainfo || nonUser" class="select-overspread">
        <user-general-info   v-if="row || areainfo || nonUser"  :row="row" :modify="modify" @clean="clean" :areainfo="areainfo" :non-user="nonUser" @success="renew" @build-success="buildFileSuccess"></user-general-info>
      </div>
      <div style="height: 500px;" v-if="batcan || batenable || batinputtor">
        <batch-cancellation v-if="batcan" :useraccount="model.rows"  @clean="clean" @success="batchSuccess"></batch-cancellation>
        <batch-enable v-if="batenable" :useraccount="model.rows" @clean="clean" @success="batchSuccess"></batch-enable>
        <change-meter-reader v-if="batinputtor" :data="model" @clean="clean" @success="batchSuccess"></change-meter-reader>
      </div>
      <!-- <div style="height: 500px;" v-if="showaccept">
        <business-accept v-if="showaccept" @clean="clean"></business-accept>
      </div> -->
    </div>
    <!-- <card-list :btns="operatebtn" :userinfoid="row ? row.f_userinfo_id : ''" v-ref:card :is-operate="false"></card-list> -->
    <modal :show.sync="show" v-ref:modal backdrop="false">
      <header slot="modal-header" class="modal-header">
        <button type="button" class="close" @click="close"><span>&times;</span></button>
        <h4 class="modal-title">文件上传</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="form-group">
          <file-upload class="my-file-uploader" name="myFile"
                       action="rs/file/upload" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>
        </div>
      </article>

      <footer slot="modal-footer" class="modal-footer">
        <!-- <button v-show="show" type="button" class="btn btn-default" @click='close'>取消</button>

        <button v-show="show" type="button" class="btn btn-success" @click='confirm(filename)'>确认</button> -->
      </footer>
    </modal>
  </div>
</template>

<script>

  import { PagedList } from 'vue-client'
  import Vue from 'vue'

  let loadParamGem = async function (self) {
    console.log('获取登录信息，', self.$login, self.$appdata, self.$appdata.getParam('用户类型'), Vue.$login.f.name)
    self.headers.username = Vue.$login.f.name
    self.headers.username = Vue.$login.guid()
    await self.search()
    await self.$LoadParams.loadParam()
    self.initAdjustables()
  }

  export default {
    'title': '用户档案',
    data () {
      return {
        model: new PagedList('rs/sql/singleTable_OrderBy', 30, {items: '"*"', tablename: '"t_userinfo"', orderitem: '"f_userinfo_id  desc"'}),
        row: null, // 选择一条用户信息，对其进行修改
        arearow: null, // 新建修改小区使用的数据小区使用
        areainfo: null, // 小区批量建档使用的数据
        rows: [], // 用户档案选择一条时，将只显示一条信息，rows用来存放整页的数据
        newArea: false,
        nonUser: false,  // 非民用
        modify: false,
        batcan: false,
        batenable: false,
        batinputtor: false,
        show: false,
        showaccept: false,
        headers: {'username': this.$login.f.name, 'blodid': this.$login.guid()},
        contract: [{label: '全部', value: ' is null or f_contract_id is not null'}, {label: '有', value: ' is not null'},
          {label: '无', value: ' is null'}],
        orderDefault: 'f_createfile_date desc',
        orderFields: {
          f_userinfo_id: 'no'
        },

        inputtores: this.$appdata.getParam('抄表员'),
        adjustables: [],
        listshow:false
      }
    },
    ready () {
      loadParamGem(this)
    },
    methods: {
      addAccept () {
        this.showaccept = true
        this.newArea = false
        this.batcan = false
        this.batenable = false
        this.batinputtor = false
        this.nonUser = false
        this.modify = false
        this.row = null
        this.areainfo = null
      },
      search () {
        this.$refs.paged.$refs.criteria.search()
      },
      modifyUser (row) {
        this.listshow = true
        this.row = row
        this.nonUser = (this.row.f_user_type === '非民用')
        this.modify = true
        this.newArea = false
        this.showaccept = false
        this.areainfo = null
        this.arearow = null
        this.batcan = false
        this.batenable = false
        this.batinputtor = false
        this.$refs.paged.$refs.grid.model.rows = [row]
      },
      clean () {
        this.listshow = false
        this.newArea = false
        this.batcan = false
        this.batenable = false
        this.batinputtor = false
        this.nonUser = false
        this.modify = false
        this.row = null
        this.areainfo = null
        this.showaccept = false
        this.$refs.paged.$refs.grid.select(null)
        this.$refs.paged.$refs.grid.model.rows = this.rows
      },
      renew () {
        this.nonUser = false
        this.modify = false
        this.newArea = false
        this.showaccept = false
        this.row = null
        this.areainfo = null
        this.clearCondition()
        this.search()
        //建档或修正档案成功刷新地址列表
        this.$refs.addressfiles.$refs.paged.$refs.cri.search()
      },
      clearCondition () {
        console.log('清空条件。。', this.$refs.paged)
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = ''
        })
      },
      buildFile (row) {
        // console.log('我是建档。。。', row)
        this.row = row
        this.modify = false
        this.nonUser = false
        this.newArea = false
        this.showaccept = false
      },
      // 查看修改小区
      selected (row) {
        // console.log('我是修改小区。。。', row)
        this.nonUser = false
        this.modify = false
        this.arearow = row.val
        this.areainfo = null
        this.newArea = true
        this.showaccept = false
        this.row = null
        this.$refs.paged.$refs.grid.model.rows = this.rows
      },
      // 小区批量建档
      bulidFiles (row) {
        this.listshow = true
        console.log('k开始建档')
        this.arearow = null
        this.newArea = false
        this.nonUser = false
        this.modify = false
        this.showaccept = false
        this.row = null
        this.areainfo = row
        // 将列表的数据清空
        // this.model.rows = []
        this.$refs.paged.$refs.grid.model.rows = this.rows
      },
      addNoUser (row) {
        console.log('建非民用row', row)
        this.arearow = null
        this.newArea = false
        this.row = null
        this.showaccept = false
        // 将列表的数据清空
        this.modify = false
        this.areainfo = row
        // this.model.rows = []
        this.nonUser = true
      },
      // 小区批量建档成功
      buildFileSuccess (data) {
        // console.log('建档案成功', data)
        this.model.rows.unshift(data)
      },
      selfSearch (args) {
        args.condition = `${args.condition} and f_filialeids  = '${this.$login.f.f_orgids}'`
        this.model.search(args.condition, args.model)
      },
      bulkOperations (name, type) {
        if (name === '批量销户') {
          this.batcan = true
          this.batenable = false
          this.batinputtor = false
        } else if (name === '批量启用') {
          this.batenable = true
          this.batinputtor = false
          this.batcan = false
        } else if (name === '抄表员调整') {
          this.batenable = false
          this.batinputtor = true
          this.batcan = false
        }
        this.newArea = false
        this.showaccept = false
        this.row = null
      },
      batchSuccess () {
        this.batenable = false
        this.batinputtor = false
        this.batcan = false
        this.showaccept = false
        this.search()
      },
      // 打开文件上传对话框
      fileUpload () {
        this.show = true
      },
      // 关闭文件上传对话框
      close () {
        // this.show = false
        if (this.show) {
          this.show = false
          // 讲选的文件清空
          this.$refs.file.$el.querySelector('input').value = ''
        }
      },
      sort (field, rule) {
        // 将所有排序方式设为不排序，实现相互排斥
        for (let key in this.orderFields) {
          if (key === field) {
            this.orderFields[key] = rule
          } else {
            this.orderFields[key] = 'no'
          }
        }
        // 如果新规则不排序，还原为默认排序
        if (rule === 'no') {
          this.model.paramSource.orderitem = `'${this.orderDefault}'`
        } else {
          this.model.paramSource.orderitem = `'${field} ${rule}'`
        }

        this.search()
      },

      getLocation(row){
        console.log('进入',row)
        //是修改档案
        if(row.f_useraddress_id){
          this.$resetpost('rs/sql/saleSingleTable', {data:{tablename: 't_userinfo', condition: `f_useraddress_id = '${row.f_useraddress_id}'`}}, {resolveMsg: null, rejectMsg: '获取档案出错'}).then((getUser) => {
            //只有一条档案数据才正确
            if (getUser.data.length === 1) {
              this.modifyUser(getUser.data[0])
            }
          })
        }else{
          //是创建档案
          //查询工单里面的档案数据
          this.$resetpost('rs/sql/sale_getService_sql',{data:{condition: `'${row.id}'`}},{resolveMsg: null, rejectMsg: '查询工单信息失败'}).then((getService) => {
            //工单中有数据
            if(getService.data.length === 1){
              this.$showMessage('该地址下有已完成的置换通气单,是否要将通气单中的信息带入建档中?', ['confirm', 'cancel']).then((res)=>{
                if (res === 'confirm') {
                  let filesinfo = Object.assign({},row,getService.data[0])
                  this.bulidFiles(filesinfo)
                }else{
                  this.bulidFiles(row)
                }
              })
            }else{
              this.bulidFiles(row)
            }
          })
        }
      },
      areaFiles(row){
        this.bulidFiles(row)
      },

      initAdjustables () {
        console.log('初始化调压箱', this.$GetSaleParam)
        let arr = []
        let filter =  this.$login.f.f_orgids
        this.$GetSaleParam.getAdjustable(filter).forEach((item) => {
          let temp = {}
          temp.label = `[${item.value.f_adjustable_id}]-${item.label}`
          temp.value = `${item.value.id}`
          arr.push(temp)
        })
        this.adjustables = [{label: '全部', value: ''}, ...arr]
      },
    },
    computed: {
      userstates () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户状态')]
      },
      areas () {
        let rs = []
        for (let i = 0; i < this.$login.f.f_allArea.length; i++) {
          let temp = {
            label: this.$login.f.f_allArea[i].label,
            value: this.$login.f.f_allArea[i].label
          }
          rs.push(temp)
        }
        return [{label: '全部', value: ''}, ...rs]
      },
      // sliceArea () {
      //   let rs = []
      //   console.log('小区片区。。。', this.$refs.paged.$refs.criteria.model.f_area)
      //   if (this.$refs.paged.$refs.criteria.model.f_area.length > 0) {
      //     for (let i = 0; i < this.$login.f.f_allArea.length; i++) {
      //       if (this.$login.f.f_allArea[i].label === this.$refs.paged.$refs.criteria.model.f_area[0]) {
      //         rs = this.$login.f.f_allArea[i].value
      //       }
      //     }
      //   }
      //   console.log('获取小区片区。。。。', rs)
      //   return [{label: '全部', value: ''}, ...rs]
      // },
      firestates () {
        return [
          {label: '全部', value: ''},
          {label: '点火', value: '1'},
          {label: '未点火', value: '0'}
        ]
      },
      jurisdiction () {
        return this.$login.r
      }
    },
    watch: {
      // 每次查询将查询到的数据存储起来，供选择操作后的替换
      'model.state' (val) {
        if (val === '正确') {
          this.rows = this.model.rows
        }
      }
    },
    events: {
      onFileUpload: function (file, res) {


          let data = {
              tablename: 't_userinfo',
              filepath: res.path,
              f_filialeids: this.$login.f.f_orgids,
              f_filiale: this.$login.orgpathnames,
              f_orgstr: this.$login.f.orgpathstr
          }
          this.$resetpost('rs/logic/importUserfiles', {data: data}, {resolveMsg: null, rejectMsg: '上传失败'}).then((res) => {
              this.close()
              this.$showAlert(`一共上传${res.data.total}条数据, 成功${res.data.successnum}条`, 'success', 2000)
              this.search()
          })

      }
    }
  }
</script>
<style>
  .nav-tabss ul > li > a{
    padding: 5px 10px;
  }
  .list-1{
    height: auto;
    max-height: 40%;
  }
  .list-2{
  }
</style>
