<template xmlns:v-el="">
  <div class="flex-row">
    <div class="basic-main">
      <criteria-paged :model="model" v-ref:paged @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="col-sm-6">-->
              <!--style="border: 1px solid #a6d5ea; box-shadow: darkgrey 1px 1px 1px 2px;padding: 0.5%">-->
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">归属起始</label>
                <datepicker placeholder="开始日期"
                            style="width:60%"
                            class="datepicker"
                            v-model="model.startDate"
                            :value.sync="model.startDate"
                            :format="'yyyy-MM-dd'"
                ></datepicker>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">归属结束</label>
                <datepicker placeholder="结束日期"
                            style="width:60%"
                            v-model="model.endDate"
                            :value.sync="model.endDate"
                            :format="'yyyy-MM-dd'"
                ></datepicker>
              </div>

              <div class="col-sm-2 form-group">
                <label class="font_normal_body">客户编号</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_userinfo_code"
                       condition="f_userinfo_code='{}'" placeholder='客户编号'>
              </div>

              <div class="span" style="float:right;">
                <button class="button_search button_spacing" @click="$parent.$parent.search()">查询</button>
                <button class="button_clear button_spacing" @click="$parent.$parent.clear()">清空</button>
                <export-excel :data="$parent.$parent.getCondition"
                              :field="$parent.$parent.getExportFields" :header="$parent.$parent.other"
                              sqlurl="rs/logic/saleExport"
                              sql-name="getDownPlan"
                              template-name='抄表计划下发导出'
                              :choose-col="true">
                </export-excel>
                <button class="button_search button_spacing"
                        @click="$parent.$parent.batchDownHand()">计划下发
                </button>
                <button v-if="$parent.$parent.inputtor_change" class="button_search button_spacing"
                        @click="$parent.$parent.batchInputtorChange()">抄表员调整
                </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-2 form-group">-->
              <!--                <label class="font_normal_body">表&ensp;编&ensp;号</label>-->
              <!--                <input type="text" style="width:60%" class="input_search" v-model="model.f_user_id"-->
              <!--                       condition="f_user_id='{}'" placeholder='表编号'>-->
              <!--              </div>-->
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">表&emsp;&emsp;号</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_meternumber"
                       condition="f_meternumber like '%{}%'" placeholder='表号'>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">客户姓名</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_user_name" placeholder='客户姓名'
                       condition="f_user_name = '{}'">
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">小&ensp;&ensp;&ensp;&ensp;区</label>
                <v-select :value.sync="model.f_residential_area"
                          class="select_list select"
                          enter-push
                          v-model="model.f_residential_area"
                          style="width: 60%"
                          multiple="true"
                          :options='$parent.$parent.residentialArea' placeholder='选择小区'
                          close-on-select v-el:cc>
                </v-select>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">楼&emsp;&emsp;栋</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_building"
                       condition="f_building = '{}'" placeholder='楼栋'>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">单&emsp;&emsp;元</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_unit"
                       condition="f_unit = '{}'" placeholder='单元'>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">楼&emsp;&emsp;层</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_floor"
                       condition="f_floor = '{}'" placeholder='楼层'>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">门&ensp;牌&ensp;号</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_room"
                       condition="f_room like '%{}%'" placeholder='门牌号'>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">客户地址</label>
                <input type="text" style="width:60%" class="input_search" v-model="model.f_address"
                       condition="f_address like '%{}%'" placeholder='客户地址'>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">抄&ensp;表&ensp;员</label>
                <v-select :value.sync="model.f_inputtor" v-model='model.f_inputtor'
                          style="width:60%"
                          multiple="true"
                          :options='$parent.$parent.inputtores' placeholder='抄表员'
                          close-on-select
                          v-el:cc></v-select>
              </div>

              <div class="col-sm-2 form-group">
                <label class="font_normal_body">客户类型</label>
                <v-select :value.sync="model.f_user_type" v-model="model.f_user_type"
                          :options='$parent.$parent.usertypes' placeholder='客户类型'
                          style="width:60%"
                          close-on-select
                          condition="f_user_type = '{}'"></v-select>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">用户等级</label>
                <v-select :value.sync="model.f_user_level" v-model="model.f_user_level"
                          :options='$parent.$parent.userlevels' placeholder='用户等级'
                          style="width:60%"
                          close-on-select
                          condition="f_user_level = '{}'"></v-select>
              </div>
              <div class="col-sm-2 form-group">
                <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='抄表册'
                          style="width:60%"
                          :multiple="true"
                          condition="f_meter_book_num in {}"></v-select>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body">调压箱名</label>
                <v-select :value.sync="model.f_adjustable_name" v-model="model.f_adjustable_name"
                          :options='$parent.$parent.adjustablename' placeholder='调压箱名称'
                          style="width:60%"
                          close-on-select
                          condition="f_adjustable_name = '{}'"></v-select>
              </div>
              <res-select-group :initres="$parent.$parent.initres" @re-res="$parent.$parent.getRes"
                                v-ref:sel></res-select-group>
            </div>


            <!-- 多选框 -->
            <!--<div class="col-sm-2 form-group">-->
            <!--<button class="btn btn-success" @click="$parent.$parent.batchDownHand()">计划下发</button>-->
            <!--</div>-->

            <!--<div class="form-group" v-if="$parent.$parent.meter_state">-->
            <!--<button class="btn btn-success" @click="$parent.$parent.allDownHand()" >全部下发</button>-->
            <!--</div>-->
            <!-- 多选框结束 -->

            <!--<div class="col-sm-2 form-group">-->
            <!--<button class="btn btn-success" @click="$parent.$parent.adjust()">抄表员调整</button>-->
            <!--</div>-->
            <!--<div class="col-sm-2 form-group">-->
            <!--<button class="btn btn-success" @click="$parent.$parent.fileUpload()">文件上传</button>-->
            <!--</div>-->
            <!--<div class="col-sm-2 form-group">-->
            <!--<button class="btn btn-success" @click="search(), $parent.$parent.clean()">打印</button>-->
            <!--</div>-->

          </div>
        </criteria>
        <data-grid :model="model" partial='list' class="list_area table_sy" v-ref:grid id="hand_manager_grid">
          <template partial='head'>
            <tr>
              <!--<th><input type='checkbox' v-model="$parent.$parent.$parent.all" @change="$parent.$parent.$parent.chooseAll"></th>-->
              <th>
                <nobr>序号</nobr>
              </th>
              <th>
                <nobr>
                  <data-order field="f_userinfo_code" name="客户编号"
                              :order.sync="$parent.$parent.$parent.orderFields.f_userinfo_code"></data-order>
                </nobr>
              </th>
              <!--              <th>-->
              <!--                <nobr>表编号</nobr>-->
              <!--              </th>-->
              <!--              <th>基本信息</th>-->
              <th>
                <nobr>
                  <data-order field="f_address" name="基本信息"
                              :order.sync="$parent.$parent.$parent.orderFields.f_address"></data-order>
                </nobr>
              </th>
              <th>
                <nobr>用户等级</nobr>
              </th>
              <!--<th><nobr><data-order field="f_building" name="楼号"-->
              <!--:order.sync="$parent.$parent.$parent.orderFields.f_building"></data-order></nobr>-->
              <!--</th>-->
              <!--<th><nobr><data-order field="f_unit" name="单元号"-->
              <!--:order.sync="$parent.$parent.$parent.orderFields.f_unit"></data-order></nobr>-->
              <!--</th>-->
              <!--<th><nobr><data-order field="f_room" name="房号"-->
              <!--:order.sync="$parent.$parent.$parent.orderFields.f_room"></data-order></nobr>-->
              <!--</th>-->
              <th>
                <nobr>调压箱名称</nobr>
              </th>
              <th>
                <nobr>抄表员</nobr>
              </th>
              <th>
                <nobr>上期结余</nobr>
              </th>
              <th>
                <nobr>表号</nobr>
              </th>
              <th>
                <nobr>上期底数</nobr>
              </th>

              <!--              <th>抄表册</th>-->
              <th>
                <nobr>
                  <data-order field="f_book_name" name="抄表册"
                              :order.sync="$parent.$parent.$parent.orderFields.f_book_name"></data-order>
                </nobr>

              </th>
              <th>
                <nobr>操作</nobr>
              </th>
              <!--            f_oughtfee-->
            </tr>
          </template>
          <template partial='body'>
            <!--<td style="text-align: center;">-->
            <!--<input  v-if="row.f_meter_state === '未下发'"-->
            <!--:id="model.pageIndex" type='checkbox' @change="$parent.$parent.$parent.chooseOne($event,row,model.rows)"-->
            <!--:checked="$parent.$parent.$parent.ischecked(row)"/>-->
            <!--</td>-->
            <td style="text-align: center;">{{$index + 1}}</td>
            <td>{{row.f_userinfo_code}}</td>
            <!--            <td>{{row.f_user_id}}</td>-->
            <td>{{row.f_user_name}}&nbsp;&nbsp;{{row.f_address}}</td>
            <td>{{row.f_user_level}}</td>
            <!--<td>{{row.f_building}}</td>-->
            <!--<td>{{row.f_unit}}</td>-->
            <!--<td>{{row.f_room}}</td>-->

            <td>{{row.f_adjustable_name}}</td>
            <td>{{row.f_inputtor}}</td>
            <td style="text-align: center;">{{row.f_balance}}</td>
            <td>{{row.f_meternumber}}</td>
            <td>{{row.f_meter_base}}</td>
            <td>{{row.f_book_name}}</td>
            <td style="text-align: center;"><nobr>
              <!--              <button type="button" name="button" class="button_search button_spacing width-60"-->
              <!--                      v-if="$parent.$parent.$parent.config.customCal && row.f_meter_state === '已抄表' && row.states === 1 && row.f_oper_state === '正常' &&  row.f_whether_pay === '否'"-->
              <!--                      @click.stop="$parent.$parent.$parent.fileterprice(row)">自定义划价-->
              <!--              </button>-->

              <!--<button type="button" name="button" class="btn btn-link" disabled="disabled"-->
                                    <!--v-if="row.num > 0">已换表-->
              <!--</button>-->
              <span v-if="row.num">有{{row.num}}条待审核或未抄表记录</span>
              <button type="button" name="button" class="button_search button_spacing width-60"
                      @click.stop="$parent.$parent.$parent.downHand(row)" v-if="!row.num"
              >下发计划
              </button>

              <!--              <button type="button" name="button" class="btn btn-link"-->
              <!--                      v-if="row.f_meter_state === '待审核' ">待审核-->
              <!--              </button>-->


            </nobr>
            </td>
          </template>
        </data-grid>
      </criteria-paged>
      <split-price :showdata="splitdata" :pricesplit="priceSplit" v-if="priceSplit"></split-price>
      <modal :show.sync="show" v-ref:modal backdrop="false">
        <header slot="modal-header" class="modal-header">
          <h4 class="modal-title">计划下发</h4>
        </header>
        <article slot="modal-body" class="modal-body">
          <form class="form-horizontal">
            <div class="row auto">
              <div class="form-group form-input-group col-sm-6">
                <label class="label-control">下发日期</label>
                <datepicker placeholder="下发日期" :value.sync="downModel.downDate" format="yyyy-MM-dd HH:mm:ss"></datepicker>
              </div>
            </div>
            <div class="row auto">
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">抄表员:</label>
                </div>
                <div class="col-sm-4 form-group">
                  <input type="radio" value="downWithUserfiles" v-model="downModel.downWay" checked>
                  <label class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;表册抄表员</label>
                </div>
                <div class="col-sm-4 form-group">
                  <input type="radio" value="downWithSelf" v-model="downModel.downWay">
                  <label class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;自定义抄表员</label>
                </div>
            </div>
            <div class="row auto" v-if="downModel.downWay === 'downWithSelf'">
              <div class="form-group form-input-group col-sm-6">
                <label class="font_normal_body">抄表员</label>
                <div class="col-sm-4">
                  <v-select :value.sync="downModel.downInputtor" v-model='downModel.downInputtor'
                            :options='inputtores2' placeholder='抄表员'
                            close-on-select></v-select>
                </div>
              </div>
            </div>
          </form>
        </article>

        <footer slot="modal-footer" class="modal-footer">
          <button type="button" class="btn btn-default" @click='close()'>取消</button>
          <button type="button" class="btn btn-success" @click='confirm()'>确认</button>
        </footer>
      </modal>
      <modal :show.sync="downConfirm" backdrop="false">
        <header slot="modal-header" class="modal-header">
          <h4 class="modal-title">下发确认</h4>
        </header>
        <article slot="modal-body" class="modal-body" style="padding: 18px;">
          <div class="col-sm-12 form-group" style="align-content: center;">
            {{msg}}
          </div>
        </article>

        <footer slot="modal-footer" class="modal-footer">
          <button type="button" class="btn btn-success" @click='downContinue'>继续下发正常用户</button>
          <!--          <button type="button" class="btn btn-success" @click='downFilter'>下发无抄表</button>-->
          <button type="button" class="btn btn-default" @click='close'>取消</button>
        </footer>
      </modal>

      <!--<modal :show.sync="downConfirm" backdrop="false">-->
        <!--<header slot="modal-header" class="modal-header">-->
          <!--<h4 class="modal-title">下发确认</h4>-->
        <!--</header>-->
        <!--<article slot="modal-body" class="modal-body">-->
          <!--<div class="col-sm-12 form-group">-->
            <!--{{msg}}-->
          <!--</div>-->
        <!--</article>-->

        <!--<footer slot="modal-footer" class="modal-footer">-->
          <!--<button type="button" class="btn btn-success" @click='downContinue'>继续下发</button>-->
          <!--&lt;!&ndash;          <button type="button" class="btn btn-success" @click='downFilter'>下发无抄表</button>&ndash;&gt;-->
          <!--<button type="button" class="btn btn-default" @click='close'>取消</button>-->
        <!--</footer>-->
      <!--</modal>-->
      <modal :show.sync="inputtor_show" backdrop="false">
        <header slot="modal-header" class="modal-header">
          <h4 class="modal-title">抄表员变更</h4>
        </header>
        <article slot="modal-body" class="modal-body">
          <form class="form-horizontal">
            <div class="row auto">
              <div class="form-group form-input-group col-sm-6">
                <label>调整客户数</label>
                <input class="input_search" v-model="model.count" disabled>
              </div>
            </div>
            <div class="row auto">
              <div class="form-group form-input-group col-sm-6">
                <label class="label-control">抄表员</label>
                <div class="col-sm-4">
                  <v-select :value.sync="inputtorModel.inputtor" v-model='inputtorModel.inputtor'
                            :options='inputtores2' placeholder='抄表员'
                            close-on-select></v-select>
                </div>
              </div>
            </div>
          </form>
        </article>

        <footer slot="modal-footer" class="modal-footer">
          <button type="button" class="btn btn-success" @click='inputtorConfirm'>确认</button>
          <button type="button" class="btn btn-default" @click='close'>取消</button>
        </footer>
      </modal>

      <modal :show.sync="uploadshow" 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="col-sm-2 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>
  </div>
</template>
<script>
  import {PagedList, HttpResetClass} from 'vue-client'
  import Vue from 'vue'
  import co from 'co'

  let readyGen = async function (self) {
    await self.$getConfig(self, 'HandManager')
    await self.$LoadParams.loadMeterBook(self.f_filialeid)
    self.loadMeterBooks()
    self.getfield = self.config.excelHeaders
    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
    self.reflash()
  }

  let downGen = function* (type, condition, data, self) {
    self.condition = condition
    self.msg = '确认下发计划'
    let getUnhand = yield Vue.resetpost('rs/sql/getUnhand', {data: {startDate: self.startDate,
        condition: self.condition}}, {resolveMsg: null, rejectMsg: '获取待审核数据异常!!'})
    for (let i = 0; i < getUnhand.data.length; i++) {
      let temp = {
        id: getUnhand.data[i].id,
        f_user_id: getUnhand.data[i].f_user_id,
        f_userfiles_id: getUnhand.data[i].f_userfiles_id
      }
      self.unhandplan.push(temp)
    }
    if (getUnhand.data.length > 0) {
      self.msg = self.msg + `, 警告: 之前有 ${getUnhand.data.length} 条待审核数据`
    } else {
      self.unhandplan = []
    }
    // console.log('1111111:',self.msg)
    self.show = true
  }

  let inputtotChangeGen = async function (self) {
    let param = {
      f_change_content: self.inputtorModel.inputtor[0],
      f_change_cause: self.inputtorModel.reason,
      condition: self.model.condition,
      startDate: self.model.params.startDate,
      endDate: self.model.params.endDate,
      f_operator: self.$login.f.name,
      f_change_count: self.model.count,
      f_change_type: '抄表员变更',
      // f_input_person: self.$login.f.name,
      f_operatorid: self.$login.f.id,
      f_orgid: self.$login.f.orgid,
      f_orgname: self.$login.f.orgs,
      f_depid: self.$login.f.depids,
      f_depname: self.$login.f.deps
    }
    console.log('抄表单抄表员变更', param)
    await self.$resetpost('rs/logic/changeInputtor', param, {resolveMsg: null, rejectMsg: '批量抄表员变更失败'})
    self.$showAlert(`总计变更 ${self.model.count} 户抄表员为 ${self.inputtorModel.inputtor[0]}`, 'success', 2000)
    self.inputtor_show = false
    self.initModal()
    self.reflash()
  }

  export default {
    title: '计划下发',
    data () {
      return {
        initres: {
          org: [this.$login.f.orgid],
          dep: [],
          user: []
        },
        sumsmodel: [],
        orgCondtionStr: '',
        priceSplit: false,
        criteriaShow: false,
        model: new PagedList('rs/sql/getDownPlan', 30, {orderitem: this.orderDefault ? '"' + this.orderDefault + ' "' : `'f_userinfo_id desc'`}),
        config: {

          // 导出列要和查询列相同
          excelHeaders: {
            'f_index': '序号',
            'f_user_id': '表编号',
            'f_meternumber': '表号',
            'f_inputtor': '抄表员',
            'f_balance': '上期结余',
            'f_last_input_date': '上次抄表',
            'f_hand_date': '下发时间',
            'f_input_date': '抄表日期',
            'f_userinfo_code': '客户编号',
            'f_address': '客户地址',
            'f_residential_area': '小区名称',
            'f_user_name': '客户姓名',
            'f_meter_base': '上期底数',
            'f_tablebase': '本期指数',
            'f_oughtfee': '应交金额',
            'f_oughtamount': '应交气量',
            'f_whether_pay': '是否缴费',
            'f_book_name': '抄表册',
            'f_meter_classify': '气表分类',
            'f_price_type': '气价类型',
            'f_price_name': '气价名称',
            'f_price_list': '气价单价',
            'f_meter_type': '气表类型',
            'f_meter_style': '气表型号',
            'f_accounts_state': '下账标识',
            'f_user_phone': '客户电话',
            'f_adjustable_id': '表箱号'
          },
          examine: true,
          customCal: false
        },
        meter_state: false, // 是否显示计划下发按钮
        downModel: {
          downDate: Vue.$login.toStandardTimeString(),
          downWay: 'downWithUserfiles',
          downInputtor: []
        },
        inputtor_change: false, // 是否显示抄表员变更按钮
        inputtor_show: false, // 控制抄表员变更模板
        inputtorModel: {
          inputtor: [],
          reason: ''
        },
        plans: [], // 记录当前行是否被勾选
        all: false, // 是否全选
        show: false, // 下发日期模态框显示
        unhandplan: [], // 之前是否有未抄表记录
        downConfirm: false, // 下发若有未抄记录，确认框
        uploadshow: false,
        // 小区
        residentialArea: [],

        //  downDate: this.$login.toStandardYearMonth().replace("-", ""),
        msg: '',
        condition: '',
        headers: {'username': Vue.$login.f.name, 'blodid': Vue.$login.guid()},
        orderDefault: 'f_userfiles_id',
        orderFields: {
          f_userinfo_id: 'no'
        },
        getfield: {},
        outlet: '',
        filiale: '',
        condition2: '',
        area: [],
        inputtouPerson: [],
        inputtores:[],
        usertypes: this.$appdata.getParam('客户类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('客户类型')] : [],
        userlevels: this.$appdata.getParam('用户等级') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用户等级')] : [],
        adjustablename: this.$appdata.getParam('调压箱名称') ? [{
          label: '全部',
          value: ''
        }, ...this.$appdata.getParam('调压箱名称')] : [],
        inputtores2: [], // 下发时使用自定义抄表员,
        splitdata: '',
        f_filialeid: this.$login.f.orgid,
        meterbooks: [],
        upshow: false,
        inputid: 0,
        showfiles: false,
        uploadText: '抄表',
        showerr: false,
        err: '',
        other: [],
        // 请求对象(批量导入,查询进度使用)
        HttpReset: new HttpResetClass()
      }
    },
    ready () {
      this.getinputtores()
      this.getaddress()
      readyGen(this)
    },
    mounted () {
      console.log(this.inputid)
      document.getElementById(this.inputid).focus()
    },
    methods: {
      getotherfooter () {
        this.other = []
        // this.footer = []
        let otherInData = []
        otherInData.push(`导出时间: ${this.$login.toStandardTimeString()}`)
        // let footerData = []
        // let exportfield = this.getExportFields
        // footerData.push('合计')
        // for (var field in this.sumsmodel) {
        //   footerData.push(`${exportfield[field]}合计:${this.sumsmodel[field]}`)
        // }
        // this.footer.push(footerData)
        this.other.push(otherInData)
      },
      // 获得本月的最后一天。
      getLastDayOfMonth (year, month) {
        let new_year = year    // 取当前的年份
        let new_month = month++// 取下一个月的第一天，方便计算（最后一天不固定）
        if (month > 12)            // 如果当前大于12月，则年份转到下一年
        {
          new_month -= 12        // 月份减
          new_year++            // 年份增
        }
        let new_date = new Date(new_year, new_month, 1)                // 取当年当月中的第一天
        let date_count = (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate()// 获取当月的天数
        // let last_date = new Date(new_date.getTime() - 1000 * 60 * 60 * 24);//获得当月最后一天的日期
        return date_count
      },

      getRes (obj) {
        this.orgCondtionStr = obj
      },
      async getaddress () {
        console.log('开始获取小区')
        let HttpReset = new HttpResetClass()
        var data = await HttpReset.load('POST', 'rs/sql/manage_getarealist', {
          data: {
            condition: `1=1 and s.f_filialeid = '${this.$login.f.orgid}'`
          }
        }, {resolveMsg: null, rejectMsg: '获取小区失败!'})
        console.log('小区', data)
        let house = []
        house.push()
        for (let row of data.data) {
          console.log('开始保存小区')
          house.push({label: row.f_residential_area, value: row.f_residential_area})
        }
        this.residentialArea = house
      },
      async getinputtores () {
        let HttpReset = new HttpResetClass()
        let condition = {
          items: '*',
          tablename: 't_user',
          condition: `charindex('抄表员',rolestr) > 0 and state = '在职' and f_organization_id = '${this.$login.f.orgid}'`,
          orderitem: 'id DESC'
        }
        var data = await HttpReset.load('POST', 'rs/sql/singleTable_OrderBy', {
          data: condition
        }, {resolveMsg: null, rejectMsg: '获取抄表员失败!'})
        let house = []
        for (let row of data.data) {
          house.push({label: row.name, value: row.name})
        }
        this.inputtores = [{label: '全部', value: ''}, ...house]
        this.inputtores2 = house
      },
      loadMeterBooks () {
        this.meterbooks = this.$GetSaleParam.getMeterBooks()
      },

      fileterprice (row) {
        this.splitdata = row
        this.priceSplit = true
        console.log('row==>', row)
      },
      hidden () {
        this.criteriaShow = !this.criteriaShow
      },
      clear () {
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = []
        })
        this.$refs.paged.$refs.criteria.model.f_meter_classify = ['机表']
      },

      // 判断当前页是否全选
      isChooseAll (rows) {
        if (this.plans.length == 0 && rows.length == 0) {
          return false
        }
        for (var i = 0; i < rows.length; i++) {
          let flag = false
          if (rows[i].f_meter_state == '未下发') {
            for (let plan of this.plans) {
              if (plan.id == rows[i].f_userfiles_id) {
                flag = true
                if (!plan.state) {
                  return false
                }
              }
            }
            if (!flag) {
              return false
            }
          }
        }
        return true
      },
      // 选择需要下发的计划
      chooseOne (e, row, rows) {
        console.log('row', row)
        let checked = e.target.checked
        console.log('state', e.target.checked)
        // 判断当前行是否被选中
        if (checked) {
          let onePlan = {
            id: row.f_userfiles_id,
            state: true
          }
          // 记录被选中计划的状态
          let flag = false
          for (let plan of this.plans) {
            if (plan.id == row.f_userfiles_id) {
              flag = true
              plan.state = true
            }
          }
          if (!flag) {
            this.plans.push(onePlan)
          }
        } else {
          for (let plan of this.plans) {
            if (plan.id == row.f_userfiles_id) {
              plan.state = false
            }
          }
        }
        // let param = {id:row.id,isChoose:true}

        if (this.isChooseAll(rows)) {
          this.all = true
        } else {
          this.all = false
        }
        // this.delRepetition()
      },
      uploadFiles () {
        this.showfiles = !this.showfiles
      },
      chooseAll () {
        if (this.all) {
          // this.chooseInfo[index-1] = []
          // for (let row of this.model.rows){
          //   this.chooseInfo[index-1].push(row)
          // }
          // this.chooseInfo = Object.assign([],this.chooseInfo,this.model.rows)

          for (let row of this.model.rows) {
            if (row.f_meter_state == '未下发') {
              let onePlan = {
                id: row.f_userfiles_id,
                state: true
              }
              let flag = false
              for (let plan of this.plans) {
                if (plan.id == row.f_userfiles_id) {
                  flag = true
                  plan.state = true
                }
              }
              if (!flag) {
                this.plans.push(onePlan)
              }
            }
          }
        } else {
          // this.chooseInfo[index-1] = []
          // console.log("this.chooseInfo[index-1]",this.chooseInfo[index-1])
          for (let row of this.model.rows) {
            if (row.f_meter_state == '未下发') {
              for (let plan of this.plans) {
                if (plan.id == row.f_userfiles_id) {
                  plan.state = false
                }
              }
            }
          }
        }
      },
      search () {
        // 查询前清空选择项
        this.plans = []
        this.$refs.paged.$refs.criteria.search()
      },
      clickupshow () {
        this.upshow = !this.upshow
      },
      selfSearch (args) {
        this.meter_state = args.condition.includes('未下发')
        this.inputtor_change = args.condition.includes('未抄表')

        if (!this.orgCondtionStr) {
          args.condition = `${args.condition}` + ' and f_orgid = ' + this.$login.f.orgid
        } else {
          args.condition = `${args.condition}` + this.orgCondtionStr
        }

        // 抄表员查询条件
        this.inputtouPerson = this.$refs.paged.$refs.criteria.model.f_inputtor
        if (this.inputtouPerson.length !== 0) {
          let str = JSON.stringify(this.inputtouPerson)
          str = str.replace(/"/g, `'`)
          str = str.replace(/\[/g, ``)
          str = str.replace(/\]/g, ``)
          console.log('=====抄表员model22222222222绑定====', str)
          // 查询多个抄表员时条件
          args.condition += ` and f_inputtor in  ( ${str} )`
        }
        // 小区查询条件
        this.area = this.$refs.paged.$refs.criteria.model.f_residential_area
        console.log('=====小区model绑定====', this.area)
        if (this.area.length !== 0) {
          let str = JSON.stringify(this.area)
          str = str.replace(/"/g, `'`)
          str = str.replace(/\[/g, ``)
          str = str.replace(/\]/g, ``)
          console.log('=====小区model22222222222绑定====', str)
          // 查询多个小区时条件
          args.condition += ` and f_residential_area in  ( ${str} )`
        }

        if (args.model.f_meter_brand && args.model.f_meter_brand.length > 0) {
          if (args.model.f_meter_brand[0].f_meter_brand) {
            args.condition = `${args.condition} and f_meter_brand = '${args.model.f_meter_brand[0].f_meter_brand}'`
          }
        }
        this.model.params.startDate = this.$refs.paged.$refs.criteria.model.startDate
        this.model.params.endDate = this.$refs.paged.$refs.criteria.model.endDate
        this.condition2 = args.condition
        console.log('selfsearch..', args.condition, this.model)
        this.model.search(args.condition, this.model)
      },
      reflash () {
        this.$refs.paged.$refs.criteria.model.f_orgid = `${Vue.$login.f.orgid}`
        this.$refs.paged.$refs.criteria.model.startDate = this.$login.toStartAndEndDateString()[0]
        this.$refs.paged.$refs.criteria.model.endDate = this.$login.toStartAndEndDateString()[1]
        this.search()
      },
      fileUpload () {
        this.uploadshow = true
      },
      down (type, condition, data) {
        co(downGen(type, condition, data, this))
      },
      // 单条下发计划
      downHand (row) {
        console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' + row.f_userfiles_id)
        this.down('single', `f_userfiles_id = '${row.f_userfiles_id}'`, row)
      },
      // 批量下发计划
      batchDownHand () {
        this.down('batch', this.model.condition, this.model.count)
      },
      // batchDownHand () {
      //   this.condition = ''
      //   let count = 0
      //   for (let plan of this.plans){
      //     if(plan.state){
      //       this.condition = this.condition + plan.id + ','
      //       count = count + 1
      //     }
      //   }
      //   this.down('batch', `f_user_id in (${this.condition.substring(0,this.condition.length-1)})`,count)
      // },
      // allDownHand () {
      //   this.down('all', this.model.condition, this.model.count)
      // },
      batchInputtorChange () {
        this.inputtor_show = true
      },
      inputtorConfirm () {
        this.$showMessage(`确认变更前请确认选择的时间区间和查询条件是否正确，确认变更当前 ${this.model.count} 户抄表员`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            inputtotChangeGen(this)
          }
        })
      },
      confirm () {
        // 正式提交下发
        // 进行日期校验,判断下发的日期是否属于选择的归属期内
        console.log('下发日期校验', this.downModel, this.$refs.paged.$refs.criteria.model)
        if (this.validateDate()) {
          this.show = false
          // this.confirmDownHand()
          console.log('有没有异常数据：',this.unhandplan)
          if (this.unhandplan.length > 0) {
            this.downConfirm = true
          } else {
            this.confirmDownHand()
          }
        } else {
          this.$showAlert('您选择的下发时间不在归属期内, 请重新选择下发时间', 'warning', 3000)
        }
      },
      validateDate () {
        let currentDown = new Date(this.downModel.downDate)
        console.log(new Date(this.$refs.paged.$refs.criteria.model.startDate))
        console.log(new Date(this.$refs.paged.$refs.criteria.model.endDate))
        return currentDown >= new Date(this.$refs.paged.$refs.criteria.model.startDate + ' 00:00:00') && currentDown <= new Date(this.$refs.paged.$refs.criteria.model.endDate + ' 23:59:59')
      },

      downContinue () {
        this.downConfirm = false
        this.confirmDownHand()
      },
      // downFilter () {
      //   this.downConfirm = false
      //   console.log('过滤有未抄记录的抄表')
      //   let filterUser = ''
      //   for (let json of this.unhandplan) {
      //     filterUser += `'${json.f_userfiles_id}',`
      //   }
      //   filterUser = filterUser.slice(0, filterUser.length - 1)
      //   this.condition = this.condition + ` and  f_userfiles_id not in (${filterUser})`
      //   console.log('获取新的条件。', this.condition)
      //   this.confirmDownHand()
      // },
      confirmDownHand () {
        console.log('下发数据。。', this.downModel)
        let param = {
          downDate: this.downModel.downDate,
          startDate: this.model.params.startDate,
          endDate: this.model.params.endDate,
          condition: this.condition,
          f_operator: this.$login.f.name,
          f_operatorid: this.$login.f.id
        }
        if (this.downModel.downWay === 'downWithSelf') {
          param.inputtor = this.downModel.downInputtor[0]
        }
        console.log('下发参数：', param)
        this.$resetpost('rs/logic/machineDownHand', {data: param}, {resolveMsg: null, rejectMsg: null}).then((res) => {
          // 将缓存的未抄表ID数组置空
          // this.unhandplan = []
          this.initModal()
          this.search()
          this.$showAlert(`全部下发,总计下发${res.data}户`, 'success', 2000)
        }).catch((error) => {
          this.$showAlert(`下发失败,请注意查看，失败原因：${error}`, 'danger', 0)
        })
      },
      // 关闭下发计划得弹出框
      close () {
        this.show = false
        this.inputtor_show = false
        this.downConfirm = false
        // 初始化模态框数据
        this.initModal()
        if (this.uploadshow) {
          this.uploadshow = false
          // 讲选的文件清空
          this.$refs.file.$el.querySelector('input').value = ''
        }
      },
      initModal () {
        this.downModel = {
          downDate: Vue.$login.toStandardTimeString(),
          downWay: 'downWithUserfiles',
          downInputtor: []
        }
        this.inputtorModel = {
          inputtor: [],
          reason: ''
        }
      },
      // 判断当前登陆人是不是子公司的人员
      isHead () {
        return this.$login.f.parent.parent.name.includes('统一资源管理')
      },
      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()
      },
      guid () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          let r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8)
          return v.toString(16)
        })
      }
    },
    watch: {
      'downModel.downWay' (val) {
        if (val === 'downWithSelf') {
          console.log('抄表员。。', this.inputtores2)
          if (this.inputtores2.length > 0) {
            this.downModel.downInputtor = [this.inputtores2[0].value]
          }
        }
      }
      // 'model.rows'(val){
      //   console.log('页面切换',val)
      //   if(this.isChooseAll(val)){
      //     this.all = true
      //   }else{
      //     this.all = false
      //   }
      // },
    },
    computed: {
      getExportFields () {
        return {
          'f_userinfo_code': '客户编号',
          'f_user_name': '客户姓名',
          'f_address': '用户地址',
          'f_user_level': '用户等级',
          'f_adjustable_name': '调压箱名称',
          'f_inputtor': '抄表员',
          'f_balance': '上期结余',
          'f_meternumber': '表号',
          'f_meter_base': '上期底数',
          'f_book_name': '抄表册'
        }
      },
      getCondition () {
        // return {condition: `${this.$refs.paged.$refs.cri.condition}` + this.orgCondtionStr}
        return {
          startDate: this.$refs.paged.$refs.criteria.model.startDate,
          endDate: this.$refs.paged.$refs.criteria.model.endDate,
          orderitem: this.orderDefault ? this.orderDefault : 'id',
          condition: this.condition2
        }
      },
      whetherpaies () {
        return [
          {label: '全部', value: ''},
          {label: '已缴费', value: '是'},
          {label: '未缴费', value: '否'}
        ]
      },
      // 界面细节权限
      jurisdiction () {
        console.log('抄表界面细节', this.$login.r)
        return this.$login.r ? this.$login.r : []
      },
      firestates () {
        return [
          {label: '全部', value: ''},
          {label: '已点火', value: '1'},
          {label: '未点火', value: '0'}
        ]
      },
      ischecked () {
        return function (row) {
          for (let plan of this.plans) {
            if (plan.id == row.f_userfiles_id) {
              return plan.state
            }
          }
        }
      }
    },
    events: {

    }
  }
</script>
<style lang="less">
  #handManager {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .btn {
      margin: 0px;
    }

    .hand-loading {
      border: 3px solid #ccc;
      border-right-color: #337ab7;
      border-radius: 50%;
      animation: spin 0.6s linear;
      position: absolute;
      animation-iteration-count: infinite;
      top: 0;
      right: 50%;
      z-index: 2;
      display: block;
      width: 28px;
      height: 28px;
      line-height: 28px;
      text-align: center;
      pointer-events: none;
    }

    @keyframes spin {
      100% {
        transform: rotate(360deg);
      }
    }
  }

  #hand_manager_grid {
    thead {
      position: relative;
      z-index: 2;
    }
  }
</style>
