<template>
  <div @keyup.enter="search" class="flex">
    <criteria-paged :model="model" v-ref:paged>
      <criteria @condition-changed='$parent.selfSearch' partial='criteria' v-ref:cri>
        <div class="form-horizontal select-overspread container-fluid auto" novalidate partial>
          <div class="row">
<!--            <res-select-group :show-component="['company','department','operator']" :initres="$parent.$parent.initres"  @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>-->
            <res-select-group :style="$parent.$parent.showclass" :show-component="['company']" :initres="$parent.$parent.initres"  @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
            <!--@re-res="$parent.$parent.getRes" v-ref:sel-->
            <div :class="$parent.$parent.showclass">
              <label  class="font_normal_body">表册状态</label>
              <v-select :value.sync="model.f_book_state"
                        v-model="model.f_book_state"
                        :options='$parent.$parent.bookstates' placeholder='抄表册状态'
                        condition="f_book_state {}"></v-select>
            </div>
            <!--<div :class="$parent.$parent.showclass">-->
              <!--<label class="font_normal_body">抄表册</label>-->
              <!--<v-select :value.sync="model.f_book_name" v-model="model.f_book_name"-->
                        <!--:options='$parent.$parent.meterbooks' placeholder='抄表册'-->
                        <!--style="width:60%"-->
                        <!--close-on-select-->
                        <!--condition="f_meter_book_num = '{}'"></v-select>-->
            <!--</div>-->

            <div class="form-group col-sm-3 button-range" style="float: right" >
              <button @click="$parent.$parent.search()" class="button_search button_spacing" v-el:cx>查询</button>
              <button @click="$parent.$parent.add()" class="button_new button_spacing">新增</button>
              <button class="button_new button_spacing" @click="$parent.$parent.meterbookManage()" >表册用户管理</button>
              <div
                :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                @click="$parent.$parent.criteriaShow=!$parent.$parent.criteriaShow"
                class="button_spacing"
                style="float: right"></div>
            </div>
          </div>
          <div class="row" v-show="$parent.$parent.criteriaShow">
            <!--<div :class="$parent.$parent.showclass">-->
              <!--<label class="font_normal_body">抄表员</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="$parent.$parent.showclass">
              <label  class="font_normal_body" title="表册片区">表册片区</label>
              <v-select :value.sync="model.f_book_slice_area"
                        v-model="model.f_book_slice_area"
                        @change="$parent.$parent.inputtorchange"
                        :options='$parent.$parent.bookSliceArea' placeholder='表册片区'
                        condition="f_book_slice_area = '{}'"></v-select>
            </div>
            <div  :class="$parent.$parent.showclass">
              <label class="font_normal_body">抄&ensp;表&ensp;员</label>
              <v-select :value.sync="model.f_inputtor" v-model='model.f_inputtor'
                        style="width:60%"
                        condition="f_inputtor in {}"
                        :options='$parent.$parent.inputtores' placeholder='抄表员'
                        @change="$parent.$parent.inputtorchange"
                        close-on-select
                        v-el:cc></v-select>
            </div>
            <div :class="$parent.$parent.showclass">
              <label class="font_normal_body">表册编号</label>
              <v-select :value.sync="model.f_book_code" v-model="model.f_book_code"
                        :options='$parent.$parent.bookcodes' placeholder='表册编号'
                        style="width:60%"
                        close-on-select
                        condition="f_meter_book_num = '{}'"></v-select>
            </div>
            <div :class="$parent.$parent.showclass">
              <label class="font_normal_body">抄&ensp;表&ensp;册</label>
              <v-select :value.sync="model.f_meter_book" v-model="model.f_meter_book"
                        :options='$parent.$parent.meterbooks' placeholder='抄表册'
                        multiple
                        style="width:60%"
                        close-on-select
                        condition="f_meter_book_num in {}"></v-select>
            </div>
            <!--<div class="col-sm-4">-->
              <!--<label class="font_normal_body">生效时间大于</label>-->
              <!--<datepicker :format="'yyyy-MM-dd'"-->
                          <!--:value.sync="model.performDate"-->
                          <!--placeholder="生效日期"-->
                          <!--condition="performDate > '{}'"-->
                          <!--v-model="model.performDate" style="width: 55%">-->
              <!--</datepicker>-->
            <!--</div>-->
          </div>
        </div>
      </criteria>
      <data-grid :model="model" class="list_area table_sy"  partial='list'  v-ref:grid>
        <template partial='head'>
          <tr>
            <th>
              <nobr>序号</nobr>
            </th>
            <th>
              <nobr>表册编号</nobr>
            </th>
            <th>
              <nobr>抄表册名</nobr>
            </th>
            <th>
              <nobr>册内户数</nobr>
            </th>
            <th>
              <nobr>所属抄表员</nobr>
            </th>
            <th  v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">
              <nobr>执行时间</nobr>
            </th>
            <th>
              <nobr>结束时间</nobr>
            </th>
            <th>
              <nobr>执行周期</nobr>
            </th>
            <th>
              <nobr>表册状态</nobr>
            </th>
            <th>
              <nobr>表册片区</nobr>
            </th>
            <th  v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">
              <nobr>备注</nobr>
            </th>
            <th v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">
              <nobr>操作员</nobr>
            </th>
            <th v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">
              <nobr>部门名称</nobr>
            </th>
            <th v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">
              <nobr>公司名称</nobr>
            </th>
            <th>
              <nobr>创建时间</nobr>
            </th>
            <th v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">
              <nobr>操作时间</nobr>
            </th>



         <!--   <th>
              <nobr>气价状态</nobr>
            </th> -->
            <th v-if="$parent.$parent.$parent.config.audit">
              <nobr>操作</nobr>
            </th>
      <!--      <th>
              <nobr>历史记录</nobr>
            </th> -->
          </tr>
        </template>
        <template partial='body'>
          <tr>
            <td style="text-align:center">{{$index + 1}}</td>
            <td style="text-align:center">{{row.f_book_code}}</td>
            <td style="text-align:center">{{row.f_book_name}}</td>
            <td style="text-align:center"><button @click.stop="$parent.$parent.$parent.operate(row.id,row.usercount)" class="btn btn-link"><b>{{row.usercount}}</b></button></td>
            <td style="text-align:center"><nobr>{{row.f_inputtor}}</nobr></td>
            <td style="text-align:center" v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)"><nobr>{{row.f_hand_begin_date}}</nobr></td>
            <td style="text-align:center"><nobr>{{row.f_meterbook_end_date}}</nobr></td>
            <td style="text-align:center"><nobr>{{row.f_period}}</nobr></td>
            <td style="text-align:center">{{row.f_book_state}}</td>
            <td style="text-align:center"><nobr>{{row.f_book_slice_area}}</nobr></td>
            <td style="text-align:center" v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)"><nobr>{{row.f_book_remark}}</nobr></td>
            <td style="text-align:center" v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)"><nobr>{{row.f_operator}}</nobr></td>
            <td style="text-align:center" v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)"><nobr>{{row.f_depname}}</nobr></td>
            <td style="text-align:center" v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)">{{row.f_orgname}}</td>
            <td style="text-align:center">{{row.f_create_date}}</td>
            <td style="text-align:center"  v-show="!$parent.$parent.$parent.$parent.usershow && !($parent.$parent.$parent.$parent.isdetail && !$parent.$parent.$parent.$parent.usershow)"><nobr>{{row.f_operate_date}}</nobr></td>
          </tr>
        </template>
        <template partial='foot'></template>
      </data-grid>
    </criteria-paged>
  </div>

  <modal v-if="meterbookEntryShow" :show.sync="meterbookEntryShow" v-ref:meterbookEntryShow backdrop="false" id="meterbookEntryShow">
    <article slot="modal-body" class="modal-body">
      <meterbook-entry></meterbook-entry>
    </article>
    <footer slot="modal-footer">
    </footer>
  </modal>

</template>

<script>
  /**
   *表册查询列表
   */
  import {PagedList} from 'vue-client'
  import Vue from 'vue'

  let asyncReadyGen = async function (self) {
    // 获取营收参数
    await self.$LoadParams.loadMeterBook(self.f_filialeid)
    // self.loadMeterBooks()
    self.initSlice(self.$login.f.orgid)
    await self.getinputtores()
  await self.$GetSaleParam.initinputtor()
  self.$refs.paged.$refs.cri.model.performDate = self.$login.toStandardDateString()
    self.search()
  }

  export default {
    data () {
      return {
        model: new PagedList('rs/sql/getMeterBookInfo', 20, {performDate: 'this.model.performDate', orderitem: '"' + this.orderitem + '"'}),
        show: false,
        criteriaShow: false,
        lastorgstr: '',
        tempfalg: false,
        f_filialeid: this.$login.f.f_orgid,
        meterbookEntryShow: false,
        // 公司下拉
        curorgid: [this.$login.f.orgid],
        meterbooks: [{label: '全部', value: ''}],
        bookcodes: [{label: '全部', value: ''}],
        row: {},
        inputtores: [{label: '全部', value: ''}],
        f_orgid: '',
        initres: {
          org: [this.$login.f.orgid]
        },
        orgCondtionStr: '',
        gasproperties: [],
        bookSliceArea: [],
        usertypes: this.$appdata.getParam('用户类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')] : []
      }
    },
    props: {
      orderitem: {
        type: String,
        default: 'f_price_id'
      },
      showclass: {
        type: String,
        default: 'col-sm-3  form-group'
      },
      inputtores: [{label: '全部', value: ''}],
      allorgid: [],
      row: {},
      condition: '',
      config: {},
      ispartial: false,
      bookname: {
        type: String
      }
    },
    ready () {
      asyncReadyGen(this)
    },
    methods: {
      meterBookEntryClose () {
        this.meterbookEntryShow = false
      },
      // 初始化片区
      async initSlice (val) {
        if (val) {
          let getAllArea = await this.$resetpost('/rs/search', {
            source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $zone$)',
            userid: this.$login.f.id
          }, {resolveMsg: null, rejectMsg: '获取片区出错！！！'})
          let arr = getAllArea.data.filter((res) => {
            return res.parentid == val
          })
          this.bookSliceArea = []
          arr.forEach((res) => {
            this.bookSliceArea.push({label: res.name, value: res.name})
          })
        }
      },
      async inputtorchange () {
        this.$set('$refs.paged.$refs.cri.model.f_meter_book', [])
        let val1 = this.$refs.paged.$refs.cri.model.f_inputtor
        let val2 = this.$refs.paged.$refs.cri.model.f_book_slice_area
        if ((val1.length > 0) || (val2.length > 0)) {
          let condition = ` 1=1 and f_orgid ='${this.f_filialeid}' and f_book_state='有效' `
          if (val1[0]) {
            condition = condition + ` and f_inputtor = '${val1[0]}' `
          }
          if (val2[0]) {
            condition = condition + ` and f_book_slice_area = '${val2}' `
          }
          let param = {
            items: '*',
            tablename: 't_meter_book',
            condition: condition,
            orderitem: 'id'
          }
          let getMeterBooks = await this.$resetpost('rs/sql/singleTable_OrderBy', {data: param}, {resolveMsg: null, rejectMsg: '获取营收参数出错！！！'})
          if (getMeterBooks.data) {
            if (getMeterBooks.data.length > 0) {
              let rs = []
              let rs2 = []
              getMeterBooks.data.forEach((item) => {
                let temp = {
                  label: item.f_book_name,
                  value: item.id
                }
                let temp2 = {
                  label: item.f_book_code,
                  value: item.id
                }
                rs.push(temp)
                rs2.push(temp2)
              })
              this.meterbooks = [{label: '全部', value: ''}, ...rs]
              this.bookcodes = [{label: '全部', value: ''}, ...rs2]
            } else {
              this.meterbooks = [{label: '全部', value: ''}]
              this.bookcodes = [{label: '全部', value: ''}]
            }
          }
        } else {
          this.meterbooks = [{label: '全部', value: ''}]
          this.bookcodes = [{label: '全部', value: ''}]
          this.initmeterbook()
        }
      },
      getorg (val) {
        console.log('val =', val)
        this.f_orgid = val
        this.f_filiale_id = val[0]
      },
      async initmeterbook (orgstr) {
        if (orgstr == null) {
          orgstr = this.f_filialeid
        }
        // 获取新的抄表册,先去清理所有的抄表册
        this.$GetSaleParam.meterbooks = []
        this.$GetSaleParam.bookcodes = []
      // 开始加载新的抄表册
        await this.$LoadParams.loadMeterBook(orgstr)
        this.meterbooks = [{label: '全部', value: ''}, ...this.$GetSaleParam.getMeterBooks()]
        this.bookcodes = [{label: '全部', value: ''}, ...this.$GetSaleParam.getBookCodes()]
      },
      async getinputtores () {
        // 获取抄表员
        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.inputtoreser = [{label: '全部', value: ''}, ...rs]
      },
      userTypeChange () {
        this.gasproperties = []
        if (this.$refs.paged.$refs.cri.model !== null) {
          this.$refs.paged.$refs.cri.model.f_gasproperties = ''
          this.gasproperties = this.$appdata.getParam(this.$refs.paged.$refs.cri.model.f_user_type[0])
        } else {
          this.gasproperties = [{label: '全部', value: ''}]
        }
      },
      operate (id,usercount) {
        this.$parent.usershow = true
        // this.$parent.id=id
        this.$parent.f_meterbook_num = id
        this.$parent.usercount =usercount
      },
      search () {
        console.log('mbList:this.f_orgid =', this.f_orgid)
        this.$refs.paged.$refs.cri.search()
        this.$dispatch('search')
      },
      selfSearch (args) {
        if (!this.f_orgid) {
          this.f_orgid = this.$login.f.orgid
        }
        let f_orgstr = this.orgCondtionStr ? this.orgCondtionStr : "and f_orgid in ('" + this.f_orgid + "')"
        args.condition = `${args.condition} ` + f_orgstr
        this.model.search(args.condition, args.model)

        this.$refs.paged.$refs.grid.$el.scrollTop = 0
        this.model.search(args.condition, args.model)
      },
      add () {
        if (!this.$login.r.find(value => value == '新增抄表册')) {
          this.$showMessage('你没有【新增抄表册】的权限,请联系管理员!')
          return
        }
        this.$dispatch('add')
      },
      meterbookManage () {
        if (!this.$login.r.find(value => value == '表册用户管理')) {
          this.$showMessage('你没有【表册用户管理】的权限,请联系管理员!')
          return
        }
        this.meterbookEntryShow = true
      },
      async getRes (condition, obj) {
        this.orgCondtionStr = condition
      },
      async updateParams () {
        console.log('重新加载抄表员！！！！！')
        await this.$LoadParams.loadParam(this.f_filialeid)
        await this.$GetSaleParam.initinputtor()
        this.initSlice(this.f_filialeid)
        this.inputtores = []
        this.inputtores.push({label: '全部', value: ''})
        console.log('所有分公司'+ this.allorgid)
        if (this.allorgid != null) {
          this.allorgid.forEach((res) => {
            this.inputtores = this.inputtores.concat(this.$GetSaleParam.getresinputtor(res))
          })
        }
      }

    },
    watch: {
      'model.rows.length' (val) {
        if (val === 1) {
          this.$refs.paged.$refs.grid.select(this.model.rows[0])
          this.$parent.usershow = false
        }
      },
      async 'orgCondtionStr' (val) {
        this.$refs.paged.$refs.cri.model.f_book_slice_area = []
        this.$refs.paged.$refs.cri.model.f_book_state = []
        this.$refs.paged.$refs.cri.model.f_inputtor = []
        this.$refs.paged.$refs.cri.model.f_meter_book = []

        // 更新抄表册
        this.meterbooks = [{label: '全部', value: ''}]
        if (this.lastorgstr != val) {
          this.tempfalg = true
          this.lastorgstr = val
        }
        if (this.tempfalg && val != null && val != '' && val.indexOf('(') > -1) {
          this.tempfalg = false
          let a = val.substring(val.indexOf('(') + 2)
          await this.initmeterbook(a.substring(0, a.indexOf(')') - 1))
        }
        let res = val.match(/'(.*?)'/)
        console.log('正则提取:', res && res[1])
        if (res) {
          this.f_filialeid = res[1]
          console.log(res)
          this.allorgid = res
          this.updateParams()
        }
      }
    },
    computed: {
      pricetypes () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('气价类型')]
      },
      bookstates () {
        return [ {label: '有效', value: "= '有效'"}, {label: '无效', value: "= '无效'"} ]
      }

    }
  }
</script>
<style lang="less">
#meterbookEntryShow {
  .modal-dialog {
    width: 80%;
  }
}
</style>
