<template>
  <div id="unit" class="flex-row">
    <div class="three-left" :style="{width:'34%'}">
      <div v-if="config.createType.length > 1">
        <tabset v-ref:tabs :close="false" class="nav nav-tabs">
          <tab header="小区建档">
            <area-files :f_filialeid.sync="f_filialeid" @re-ref="areaFiles" v-ref:areafiles></area-files>
          </tab>
          <tab header="地址建档">
            <address-files @buildfiles="getLocation" :f_filialeid.sync="f_filialeid" v-ref:addressfiles></address-files>
          </tab>
        </tabset>
      </div>
      <div v-else>
        <area-files v-if="config.createType[0] === 'area'" :f_filialeid="$login.f.orgid" @re-ref="areaFiles" v-ref:areafiles></area-files>
        <address-files v-if="config.createType[0] === 'address'" @buildfiles="getLocation" v-ref:addressfiles></address-files>
      </div>

    </div>
    <div class="basic-main" style="margin-left: 1%;" :style="{width:'65%'}">
      <div class="flex" style="flex: 1;" >
        <div style="flex: 1.2">
          <criteria-paged :model="model" v-ref:paged :pager="!row && !areainfo" @sort="sort" >
            <criteria partial='criteria' v-ref:criteria @condition-changed="$parent.selfSearch">
              <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
                <div class="row">
                  <div class="form-group col-sm-4">
                    <label class="font_normal_body">组织机构</label>
                    <res-select
                      restype='organization'
                      @res-select="$parent.$parent.getorg"
                      is-mul="false"
                      :initresid='$parent.$parent.curorgid'
                    >
                    </res-select>
                  </div>
                  <div class="form-group col-sm-4">
                    <label class="font_normal_body">客户编号</label>
                    <input type="text" class="input_search" style="width:60%" v-model="model.f_userinfo_code"
                           @keyup.enter="search()"  condition="f_userinfo_code = '{}'" placeholder='客户编号'>
                  </div>
                  <div class="form-group col-sm-4">
                    <label class="font_normal_body">客户名称</label>
                    <input type="text" class="input_search" style="width:60%" v-model="model.f_user_name"
                           @keyup.enter="search()"  condition="f_user_name = '{}'" placeholder='客户姓名'>
                  </div>

                  <div style="float:right">
                    <button class="button_search" @click="search(), $parent.$parent.clean()">查询</button>
                    <button class="button_clear" @click="$parent.$parent.clear()">清空</button>
                    <button class="button_export" @click="$parent.$parent.importFile">导入</button>
                    <button class="button_search " v-if="$parent.$parent.rows && $parent.$parent.rows.length === 1 && $parent.$parent.rows[0].f_user_state === '正常'"
                            @click="$parent.$parent.bulkOperations('批量销户', 'batch-cancellation')">销户</button>
                    <button class="button_search"  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 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 class="row" v-if="$parent.$parent.criteriaShow">
                  <div class="form-group col-sm-4" >
                    <label class="font_normal_body">旧客户号</label>
                    <input type="text" class="input_search" style="width:60%" v-model="model.f_olduserinfo_code" placeholder='客户编号'
                           condition="f_olduserinfo_code = '{}'">
                  </div>
                  <div class="form-group col-sm-4">
                    <label class="font_normal_body">用气性质</label>
                    <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"
                              :options='$parent.$parent.gasproperties' placeholder='用气性质'
                              close-on-select condition="f_gasproperties='{}'"></v-select>
                  </div>
                  <div class="form-group col-sm-4">
                    <label class="font_normal_body">客户电话</label>
                    <input type="text" class="input_search" style="width:60%" v-model="model.f_user_phone" placeholder='客户电话'
                           condition="f_user_phone = '{}'">
                  </div>
                  <div class="form-group col-sm-4">
                    <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 col-sm-4">
                    <label class="font_normal_body">客户状态</label>
                    <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 col-sm-4">
                    <label class="font_normal_body">调压箱&nbsp;&nbsp;&nbsp;</label>
                    <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>
              </div>
            </criteria>
            <data-grid :model="model" class="list_area table_sy" v-ref:grid partial='list'>
              <template partial='head'>
                <tr>
                  <th>
                    <nobr>序号</nobr>
                  </th>
                  <th>
                    <!--<data-order field="f_userinfo_id" name="客户编号"></data-order>-->
                    <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;">{{$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.addressid}}&nbsp;&nbsp;{{row.f_address_detail ? row.f_address + row.f_address_detail : row.f_address}}</td>
                <td>{{row.f_meternumber}}&nbsp;&nbsp;{{row.f_meter_brand}}&nbsp;&nbsp;{{row.f_table_state}}</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  class="auto" style="height: 70%; margin-top: 1%" v-show="row || areainfo">
          <user-general-info v-if="row || areainfo" :f_filialeid="f_filialeid" :row="row" :areainfo="areainfo" :haslimit="config.hasLimit" @success="renew" @clean="clean"
                             @build-success="buildFileSuccess"></user-general-info>
        </div>

        <div v-if="batcan || batenable">
          <batch-cancellation v-if="batcan" :useraccount="model.rows"  @clean="batchClean" @success="batchSuccess"></batch-cancellation>
          <batch-enable v-if="batenable" :useraccount="model.rows" @clean="batchClean" @success="batchSuccess"></batch-enable>
        </div>
      </div>
    </div>

    <modal :show.sync="show" 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:file :headers="headers"></file-upload>
      </article>
      <footer slot="modal-footer" class="modal-footer">
      </footer>
    </modal>

  </div>
</template>

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

  let loadParamGem = async function (self) {
    await self.$getConfig(self, 'UserFiles')
    self.headers.username = Vue.$login.f.name
    self.headers.username = Vue.$login.guid()
    await self.$LoadParams.loadParam(self.f_filialeid)
    await self.search()
    self.initAdjustables()
  }

  let addressInfoGen = async function (self, areainfo) {
    areainfo.isEdit = false
    if (areainfo.file_num > 0 && !areainfo.f_userinfo_id) {
      // 完善
      // 将表档案信息带入，完善客户信息
      let getMetersInfo = await self.$resetpost('rs/logic/sale_getMeterByAddress', {
        data: {
          f_useraddress_id: areainfo.id
        }
      }, {resolveMsg: null, rejectMsg: '获取表信息出错'})
      areainfo.meter = getMetersInfo.data[0]
    }
    if (areainfo.file_num > 0 && areainfo.f_userinfo_id) {
      // 添加 将客户信息带入
      let getUserinfo = await self.$resetpost('rs/sql/saleSingleTable', {
        data: {
          tablename: 't_userinfo',
          condition: `f_userinfo_id = '${areainfo.f_userinfo_id}'`
        }
      }, {resolveMsg: null, rejectMsg: '获取档案出错'})

      areainfo.user = getUserinfo.data[0]
    }
    self.bulidFiles(areainfo)
  }

  export default {
    'title': '档案管理',
    data () {
      return {
        config: {
          createType: ['address', 'area'],  // 建档方式： address-地址建档  area-小区建档
          hasLimit: false
        },
        model: new PagedList('rs/sql/sale_getUserfies', 30, {orderitem: '"f_userinfo_id DESC"'}),
        row: null, // 选择一条客户信息，对其进行修改
        areainfo: null, // 小区批量建档使用的数据
        rows: [], // 客户档案选择一条时，将只显示一条信息，rows用来存放整页的数据
        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'
        },

        curorgid: [this.$login.f.orgid],
        f_filialeid: this.$login.f.orgid,

        // 销户启用
        batcan: false,
        batenable: false,

        inputtores: this.$appdata.getParam('抄表员'),
        adjustables: [],

        // 导入组件
        show: false,

        criteriaShow: false,

        gasproperties: this.$appdata.getParam('用气性质') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用气性质')] : []
      }
    },
    // ready () {
    //   loadParamGem(this)
    // },
    methods: {

      hidden () {
        this.criteriaShow = !this.criteriaShow
      },
      search () {
        this.$refs.paged.$refs.criteria.search()
      },
      modifyUser (row) {
        this.row = row
        this.areainfo = null
        this.criteriaShow = false
        this.$refs.paged.$refs.grid.$el.scrollTop = 0
        this.$refs.paged.$refs.grid.model.rows = [row]
      },
      clean () {
        this.row = null
        this.areainfo = null
        this.$refs.paged.$refs.grid.select(null)
        this.$refs.paged.$refs.grid.model.rows = this.rows
      },
      renew () {
        this.row = null
        this.areainfo = null
        this.clearCondition()
        this.search()
        // 建档或修正档案成功刷新地址列表
        this.$refs.addressfiles.$refs.paged.$refs.cri.search()
      },
      clearCondition () {
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = ''
        })
      },

      bulkOperations (name, type) {
        if (name === '批量销户') {
          this.batcan = true
          this.batenable = false
          this.newArea = false
        } else if (name === '批量启用') {
          this.batenable = true
          this.batcan = false
          this.newArea = false
        }
      },
      batchSuccess () {
        this.clearCondition()
        this.batchClean()
      },
      batchClean () {
        this.batcan = false
        this.batenable = false
        this.newArea = false
        this.search()
      },
      buildFile (row) {
        // console.log('我是建档。。。', row)
        this.row = row
      },
      // 小区批量建档
      bulidFiles (row) {
        this.row = null
        this.areainfo = row
        // 将列表的数据清空
        this.$refs.paged.$refs.grid.model.rows = []
      },
      // 小区批量建档成功
      buildFileSuccess (data) {
        // console.log('建档案成功', data)
        this.model.rows.unshift(data)
      },
      selfSearch (args) {
        console.log('开始查询档案', this.f_filialeid)
        args.condition = `${args.condition} and f_filialeid = '${this.f_filialeid}'`
        this.criteriaShow = false
        this.$refs.paged.$refs.grid.$el.scrollTop = 0
        this.model.search(args.condition, args.model)
        this.clean()
      },
      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)

        addressInfoGen(this, row)
      },
      areaFiles (row) {
        row.isEdit = true
        row.f_residential_area_id = row.id
        // row.id = null
        delete row.id
        this.bulidFiles(row)
      },

      initAdjustables () {
        console.log('初始化调压箱', this.$GetSaleParam)
        let arr = []
        let filter = this.$login.f.orgid
        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]
      },
      importFile () {
        this.show = true
      },
      clear () {
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = []
        })
      },
      getorg (val) {
        this.f_filialeid = val[0]
      }
    },
    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]
      },
      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
        }
      },
      'f_filialeid' (val) {
        loadParamGem(this)
      }
    },
    events: {
      FileUpload: function (file, res) {
        let data = {
          tablename: 't_userinfo',
          filepath: res.path
        }
        this.$resetpost('rs/logic/import', data, {resolveMsg: null, rejectMsg: '上传失败'}).then((res) => {
          console.log('dddddddd', this)
          this.close()
          this.$showAlert(`一共上传${res.data.total}条数据, 成功${res.data.successnum}条`, 'success', 2000)
          this.search()
        })
      },
      onFileUpload: function (file, res) {
        let data = {
          tablename: 't_userinfo',
          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/sale_userfilesImp', {data: data}, {resolveMsg: null, rejectMsg: '上传失败'}).then((res) => {
          this.show = false
          this.$showAlert(`一共上传${res.data.total}条数据, 成功${res.data.successnum}条`, 'success', 2000)
          this.search()
        })
      }
    }
  }
</script>
<style>
  .nav-tabss ul > li > a {
    padding: 5px 10px;
  }
</style>
