<template xmlns:v-el="">
  <div class="flex">
    <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">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;归属期</label>
              <datepicker placeholder="开始日期"
                          style="width:60%"
                          v-model="model.startDate"
                          :value.sync="model.startDate"
                          :format="'yyyy-MM-dd'"
              ></datepicker>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;</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">
              <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="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;表编号</label>
              <input type="text" style="width:60%" class="input_search" v-model="model.f_user_id"
                     condition="f_user_id='{}'" 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>


              <button v-if="$parent.$parent.meter_state" class="button_search button_spacing" style="width:90px"  @click="$parent.$parent.batchDownHand()">计划下发</button>
              <button v-if="$parent.$parent.inputtor_change" class="button_search button_spacing" style="width:90px" @click="$parent.$parent.batchInputtorChange()">抄表员调整</button>

              <export-excel
                :data="{startDate: model.startDate, endDate: model.endDate,condition: condition + ` and f_orgid = '${$login.f.orgid}'`}"
                :field="$parent.$parent.getfield"
                sqlurl="rs/logic/saleExport" sql-name="periodAlreadyIssued" template-name='抄表导出'
                :choose-col="true"></export-excel>
              <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-show="$parent.$parent.criteriaShow">
            <div class="col-sm-2">
              <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 like '%{}%'">
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;区域&nbsp;&nbsp;&nbsp;</label>
              <input type="text" style="width:60%" class="input_search" v-model="model.f_area"
                     condition="f_area like '%{}%'" placeholder='区域'>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;小区&nbsp;&nbsp;&nbsp;</label>
              <input type="text" style="width:60%" class="input_search" v-model="model.f_residential_area"
                     condition="f_residential_area like '%{}%'" placeholder='小区'>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;楼栋&nbsp;&nbsp;&nbsp;</label>
              <input type="text" style="width:60%" class="input_search" v-model="model.f_building"
                     condition="f_building like '%{}%'" placeholder='楼栋'>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;单元&nbsp;&nbsp;&nbsp;</label>
              <input type="text" style="width:60%" class="input_search" v-model="model.f_unit"
                     condition="f_unit like '%{}%'" placeholder='单元'>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;楼层&nbsp;&nbsp;&nbsp;</label>
              <input type="text" style="width:60%" class="input_search" v-model="model.f_floor"
                     condition="f_floor like '%{}%'" placeholder='楼层'>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;门牌号</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">
              <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">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;抄表员</label>
              <v-select :value.sync="model.f_inputtor" v-model='model.f_inputtor'
                        style="width:60%"
                        :options='$parent.$parent.inputtores' placeholder='抄表员'
                        close-on-select
                        condition="f_inputtor = '{}'" v-el:cc></v-select>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">是否缴费</label>
              <v-select :value.sync="model.f_whether_pay" v-model='model.f_whether_pay'
                        style="width:60%"
                        :options='$parent.$parent.whetherpaies' placeholder='是否缴费'
                        close-on-select
                        condition="f_whether_pay = '{}'"></v-select>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">抄表状态</label>
              <v-select :value.sync="model.f_meter_state" v-model='model.f_meter_state'
                        style="width:60%"
                        :options='$parent.$parent.meterstates' placeholder='抄表状态'
                        close-on-select
                        condition="f_meter_state = '{}'"></v-select>
            </div>
            <div class="col-sm-2">
              <label class="font_normal_body">气表类型</label>
              <v-select :value.sync="model.f_meter_classify" v-model="model.f_meter_classify"
                        style="width:60%"
                        :options='$parent.$parent.meters' placeholder='气表类型'
                        close-on-select
                        condition="f_meter_classify = '{}'"
                        default-value="'机表'"></v-select>
            </div>
            <div class="col-sm-2">
              <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>


          <!-- 多选框 -->
          <!--<div class="col-sm-2">-->
          <!--<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">-->
          <!--<button class="btn btn-success" @click="$parent.$parent.adjust()">抄表员调整</button>-->
          <!--</div>-->
          <!--<div class="col-sm-2">-->
          <!--<button class="btn btn-success" @click="$parent.$parent.fileUpload()">文件上传</button>-->
          <!--</div>-->
          <!--<div class="col-sm-2">-->
          <!--<button class="btn btn-success" @click="search(), $parent.$parent.clean()">打印</button>-->
          <!--</div>-->

        </div>
      </criteria>
      <data-grid :model="model" partial='list' v-ref:grid class="list_area table_sy" >
        <template partial='head'>
          <tr>
            <!--<th><input type='checkbox' v-model="$parent.$parent.$parent.all" @change="$parent.$parent.$parent.chooseAll"></th>-->
            <th>序号</th>
            <th>
              <data-order field="f_userinfo_id" name="客户编号"
                          :order.sync="$parent.$parent.$parent.orderFields.f_userinfo_code"></data-order>
            </th>
            <th>表编号</th>
            <th>基本信息</th>
            <th>抄表员</th>
            <th>下发日期</th>
            <th>上期底数</th>
            <th>本期底数</th>
            <th>应交气量</th>
            <th>是否缴费</th>
            <th>操作</th>
          </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_user_phone}}&nbsp;&nbsp;{{row.f_address}}</td>
          <td>{{row.f_inputtor}}</td>
          <td>{{row.f_hand_date}}</td>
          <td>{{row.f_meter_base}}</td>
          <td id="hand-creat">
            <div class="form-group" style="margin-bottom:0px;display: contents;" :class="{
                       'has-success has-feedback': !row.error,
                       'has-error has-feedback': row.error}"
                 v-if="row.f_meter_state === '未抄表' && row.states !== 0">

              <input title="只能录入整数" type="text" class="input_search" v-model="row.f_tablebase"
                     @blur="$parent.$parent.$parent.beforenter($index, row)"
                     v-next-el="{id: $index+1}" :id="$index" style="width: 100px;padding: 6px;"
                     @focus="$parent.$parent.$parent.clearError(row)"
                     :disabled="row.state === '开始'">
              <span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"
                    v-show="(row.f_tablebase && row.f_tablebase !== '')? ((row.f_tablebase-0) >= (row.f_meter_base -0)) : false"></span>
              <span class="hand-loading" v-if="row.state === '开始'"></span>
              <!-- <span id="inputSuccess2Status" class="sr-only">(success)</span> -->
              <span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"
                    v-show="(row.f_tablebase && row.f_tablebase !== '')? ((row.f_tablebase-0) < (row.f_meter_base -0) ) : false"></span>
              <!-- <span id="inputError2Status" class="sr-only">(error)</span> -->
            </div>
            <div id="handManager" v-else>
              <span
                v-if="row.states === 0">{{row.f_tablebase || row.f_tablebase === 0 ? row.f_tablebase : '本期无计划'}}</span>
              <span
                v-if="row.states === 1">{{row.f_tablebase || row.f_tablebase === 0 ? row.f_tablebase : '尚未下发'}}</span>
            </div>
            <span v-if="row.error" style="color: red;">{{row.error}}</span>
          </td>
          <td style="text-align: center;">{{row.f_oughtamount = row.f_tablebase ?
            (row.f_share_gas ?
            (row.f_tablebase - 0 - (row.f_meter_base - 0)).toFixed(2) + (row.f_share_gas > 0 ? '+' : '') + row.f_share_gas.toFixed(2) : (row.f_tablebase - 0 - (row.f_meter_base - 0)).toFixed(2)) : 0}}
          </td>
          <td style="text-align: center;">{{row.f_whether_pay}}</td>
          <!-- <td style="text-align: center;">{{row.f_meter_source}}</td>
          <td style="text-align: center;">{{row.f_issued_state}}</td> -->
          <td style="text-align: center;">
            <button type="button" name="button" class="btn btn-link"
                    v-if="row.f_meter_state === '已抄表' && row.states === 1 && row.f_oper_state === '正常'"
                    @click.stop="$parent.$parent.$parent.cancelHand2(row)">冲正
            </button>

            <button type="button" name="button" class="btn btn-link" disabled="disabled"
                    v-if="row.f_oper_state === '换表'">已换表
            </button>

            <button type="button" name="button" class="btn btn-link"
                    @click.stop="$parent.$parent.$parent.delectHand(row)  && row.states === 1"
                    v-if="row.f_meter_state === '未抄表' && row.states === 1">删除
            </button>

            <button type="button" name="button" class="btn btn-link"
                    @click.stop="$parent.$parent.$parent.downHand(row)"
                    v-if="row.f_meter_state === '未下发'">下发计划
            </button>
            <button type="button" name="button" class="btn btn-link"
                    v-if="row.f_meter_state === '待审核' ">待审核
            </button>

            <button type="button" name="button" class="btn btn-link"
                    @click.stop="$parent.$parent.$parent.pass(row)"
                    v-if="row.f_meter_state === '待审核'">通过
            </button>

            <button type="button" name="button" class="btn btn-link"
                    @click.stop="$parent.$parent.$parent.nopass(row)"
                    v-if="row.f_meter_state === '待审核' ">不通过
            </button>
          </td>
        </template>
      </data-grid>
    </criteria-paged>

    <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"></datepicker>
            </div>
          </div>
          <div class="row auto">
            <div class="form-group form-input-group col-sm-3">
              <div class="col-sm-2"></div>
              <input type="radio" value="downWithUserfiles" v-model="downModel.downWay" checked>
              <label>档案抄表员</label>
            </div>
            <div class="form-group form-input-group col-sm-3">
              <input type="radio" value="downWithSelf" v-model="downModel.downWay">
              <label class="label-control">自定义抄表员</label>
            </div>
          </div>
          <div class="row auto" v-if="downModel.downWay === 'downWithSelf'">
            <div class="form-group form-input-group col-sm-6">
              <label class="label-control">抄表员</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">
        <div class="col-sm-2">
          {{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="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>
          <!--<div class="row auto">-->
          <!--<div class="form-group form-input-group col-sm-12" >-->
          <!--<label class="label-control">变更原因</label>-->
          <!--<div class="col-sm-10">-->
          <!--<textarea class="input_search"  v-model="inputtorModel.reason" rows="3" placeholder="请填写原因"></textarea>-->
          <!--</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">
          <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, HttpResetClass} from 'vue-client'
  import Vue from 'vue'
  import co from 'co'

  let readyGen = async function (self) {
    await self.$getConfig(self, 'HandManager')
    console.log('抄表管理config', self.config)
    self.getfield = self.config.excelHeaders
    self.reflash()
  }

  let downGen = function *(type, condition, data, self) {
    // if(data == 0 ) {
    //   self.$showAlert('下发计划户数为0！请选择需要下发的计划！！', 'danger', 0)
    //   return
    // }
    self.condition = condition
    self.msg = '确认下发计划'
    console.log('下发计划。。。', type, condition, data, self)
    // 判断之前是否有未抄表数据
    let getUnhand = null
    // let getUnhand = yield Vue.resetpost('rs/sql/getUnhand', {data: {startDate: self.startDate, condition: self.condition}}, {resolveMsg: null, rejectMsg: '获取未抄表数据异常!!'})
    // if (type === 'batch' || type === 'single') {
    if (type === 'single') {
      getUnhand = yield Vue.resetpost('rs/sql/getUnhand', {
        data: {
          startDate: self.model.params.startDate,
          condition: condition
        }
      }, {resolveMsg: null, rejectMsg: '获取未抄表数据异常!!'})
      self.msg = `下发客户编号为${data.f_userinfo_code}的抄表计划？`
      // } else if (type === 'all') {
    } else if (type === 'batch') {
      let tempCondition = condition.replace("and f_meter_state = '未下发'", '')
      console.log('去掉未下发状态..', tempCondition)
      getUnhand = yield Vue.resetpost('rs/sql/getUnhand', {
        data: {
          startDate: self.model.params.startDate,
          condition: tempCondition
        }
      }, {resolveMsg: null, rejectMsg: '获取未抄表数据异常!!'})
      self.msg = `确认下发当前总计:  ${data}  户计划`
    }
    console.log('获取未抄表数据.......', getUnhand)
    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)
    }
    console.log('未抄表Id....', self.unhandplan)
    if (getUnhand.data.length > 0) {
      self.msg = self.msg + `, 警告: 之前有 ${getUnhand.data.length} 条未抄表数据`
    }
    self.show = true
  }

  let beforenterGen = async function (self, index, row) {
    // 验证是不是总表
    console.log('看看row里面有没有总分表类型，，，', row)
    // self.enter(index, row)
    if (row.f_totalsplit_type === '总表') {
      let hasUnHand = await self.$HandService.getSplitInfo(row.f_userfiles_id)
      if (hasUnHand) {
        self.$showAlert('该表下面有未抄或未审核的分表信息！！请先抄录或审核分表信息！', 'danger', 0)
        row.f_tablebase = null
      } else {
        self.enter(index, row)
      }
    } else {
      self.enter(index, row)
    }
  }

  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 {
        criteriaShow: false,
        model: new PagedList('rs/sql/periodAlreadyIssued', 30),
        config: {
          excelHeaders: {
            'f_userinfo_code': '客户编号',
            'f_address': '客户地址',
            'f_user_name': '客户姓名',
            'f_meter_base': '上期底数',
            'f_tablebase': '本期指数',
            'f_user_phone': '客户电话'
          }
        },
        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,

        //  downDate: this.$login.toStandardYearMonth().replace("-", ""),
        msg: '',
        condition: '',
        headers: {'username': Vue.$login.f.name, 'blodid': Vue.$login.guid()},
        orderDefault: 'id',
        orderFields: {
          f_userinfo_id: 'no'
        },
        getfield: {},
        outlet: '',
        filiale: '',
        meters: [{label: '全部', value: ''}, {label: '机表', value: '机表'}, {label: '物联网表', value: '物联网表'}],
        meterstates: this.$appdata.getParam('抄表状态') ? [{
          label: '全部',
          value: ''
        }, ...this.$appdata.getParam('抄表状态')] : [],
        usertypes: this.$appdata.getParam('客户类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('客户类型')] : [],
        inputtores2: [] // 下发时使用自定义抄表员
      }
    },
    ready () {
      readyGen(this)
    },
    methods: {
      hidden() {
        this.criteriaShow = !this.criteriaShow
      },
      clear(){
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = []
        })
      },

      //判断当前页是否全选
      isChooseAll(rows){
        if (this.plans.length == 0 && rows.length == 0) {
          console.log('长度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) {
              console.log('从来没选过这行-----》', rows[i])
              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()
      },
      chooseAll(){
        console.log("全选", this.all)
        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 = []
        console.log('清空数据')
        this.$refs.paged.$refs.criteria.search()
      },
      selfSearch (args) {
        this.meter_state = args.condition.includes('未下发')
        this.inputtor_change = args.condition.includes('未抄表')
        args.condition += ` and f_orgid = '${this.$login.f.orgid}'`
        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
        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()
      },
      beforenter (index, row) {
        // 限制本次抄表不能低于上次
        if (row.f_tablebase) {
          if (row.f_tablebase - parseInt(row.f_tablebase) !== 0) {
            row.state = '失败'
            Vue.set(row, 'error', '底数只能输入整数')
          } else if (row.f_tablebase < row.f_meter_base) {
            row.state = '失败'
            Vue.set(row, 'error', '本期表底数不能低于上期表底数')
          } else {
            beforenterGen(this, index, row)
          }
        }
      },
      enter (index, row) {
        console.log('录入数据。..', row)
        if (this.$appdata.getSingleValue('抄表审核') === '启用') {
          let handplan = {
            id: row.id,
            f_oughtamount: row.f_oughtamount,
            f_tablebase: row.f_tablebase,
            f_hand_date: row.f_hand_date,
            f_input_date: Vue.$login.toStandardDateString(),
            f_input_person: Vue.$login.f.name,
            f_meter_state: '待审核',
            f_meter_source: '手动录入',

            f_operator: Vue.$login.f.name,
            f_operatorid: Vue.$login.f.id,
            f_orgid: Vue.$login.f.orgid,
            f_orgname: Vue.$login.f.orgs,
            f_depid: Vue.$login.f.depids,
            f_depname: Vue.$login.f.deps

          }
          console.log('抄表负数。。0', handplan)
          this.$resetpost('rs/entity/t_handplan', handplan, {
            resolveMsg: null,
            rejectMsg: '抄表数据保存出错!!!'
          }).then((res) => {
            row.f_meter_state = '待审核'
            row.f_whether_pay = '否'
            row.f_input_date = res.data.f_input_date
            console.log('录入完成。，。。', row.f_meter_state, row.f_whether_pay)
            this.$parent.search()
          }).catch((error) => {
            row.state = '失败'
            Vue.set(row, 'error', JSON.stringify(error))
          })
        } else {
          // 没有启用抄表审核功能
          row.f_input_person = this.$login.f.name
          row.f_inputtor = row.f_inputtor
          row.f_userinfo_id = row.f_userinfo_id + ''
          row.f_userfiles_id = row.f_userfiles_id + ''
          this.pass(row)
        }
      },
      pass (row) {
        console.log('通过。。。', row)
        let param = {
          f_meter_classify: row.f_meter_classify,
          f_meter_brand: row.f_meter_brand,
          f_hand_id: row.id,
          f_tablebase: row.f_tablebase
        }
        this.$resetpost('rs/logic/sale_commonEnter', {data: param}, {resolveMsg: null, rejectMsg: null}).then((res) => {
          row.f_meter_state = res.data.f_meter_state
          row.f_whether_pay = res.data.f_whether_pay
          console.log('通过成功呢，。。', row, res.data)
          this.search()
        }).catch((error) => {
          row.state = '失败'
          Vue.set(row, 'error', JSON.stringify(error))
        })
      },
      nopass (row) {
        console.log('不通过。。。', row)
        let handplan = {
          id: row.id,
          f_oughtamount: 0,
          f_tablebase: 0,
          f_input_date: null,
          f_meter_state: '未抄表',
          f_meter_source: null
        }
        this.$resetpost('rs/entity/t_handplan', handplan, {
          resolveMsg: null,
          rejectMsg: '未通过，抄表数据返回未抄表保存出错!!!'
        }).then((res) => {
          row.f_tablebase = null
          row.f_meter_state = '未抄表'
          row.f_whether_pay = '否'
          this.search()
        }).catch((error) => {
          row.state = '失败'
          Vue.set(row, 'error', JSON.stringify(error))
        })
      },
      clearError (row) {
        if (row.f_tablebase === 0) {
          row.f_tablebase = ''
        }
        Vue.set(row, 'error', null)
      },
      fileUpload () {
        this.uploadshow = true
      },
      // 删除这条计划
      delectHand (row) {
        this.$showMessage('删除后不可恢复，确认删除吗？', ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            this.$resetpost('rs/logic/deletePlan', {data: row}).then(() => {
              this.$dispatch('refresh', '删除计划', row)
              this.search()
            })
          }
        })
      },
      cancelHand2 (row) {
        console.log('抄表冲正。、。。、', row)
        let param = {
          f_hand_id: row.id,
          operInfo: {
            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
          }
        }
        let url = row.f_meter_type === '物联网表' ? 'rs/logic/iotSettlementCancel' : 'rs/logic/sale_commonEnterCancel'
        this.$resetpost(url, {data: param}, {warnMsg: '确定对这条记录进行撤销吗？'}).then(() => {
          this.search()
        })
      },
      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
          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("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~看一下时间 ")
        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/downHand', {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.toStandardDateString(),
          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.reflash()
      }
    },
    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: {
      inputtores () {
        // 获取抄表员
        console.log('获取抄表员', this.$login.f)
        let rs = []
        if (this.$login.f.f_gasman.length > 0) {
          for (let i = 0; i < this.$login.f.f_gasman.length; i++) {
            let temp = {
              label: this.$login.f.f_gasman[i].name,
              value: this.$login.f.f_gasman[i].name
            }
            rs.push(temp)
          }
        }
        this.inputtores2 = rs
        return [{label: '全部', value: ''}, ...rs]
      },
      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: {
      onFileUpload: function (file, res) {
        let data = {
          model: {
            f_operator: this.$login.f.name,
            f_end_date: this.$login.nextMonth20(this.$login.toStandardTimeString())
          },
          filepath: res.path
        }
        if (data.filepath.includes('先锋')) {
          this.$resetpost('rs/logic/xfimport', data, {resolveMsg: null, rejectMsg: '上传失败'}, 0).then((res) => {
            // console.log('终于成功了', res)
            this.uploadshow = false
            this.$showAlert(`一共上传${res.data.total}条数据, 成功${res.data.successnum}条, 未抄下发${res.data.nohandnum}条, 失败下发${res.data.failednum}条, 异常下发${res.data.exceptionnum}条`, 'success', 2000)
            this.$parent.search()
          })
        } else if (data.filepath.includes('伦力')) {
          this.$resetpost('rs/logic/llimport', data, {resolveMsg: null, rejectMsg: '上传失败'}, 0).then((res) => {
            // console.log('终于成功了', res)
            this.uploadshow = false
            this.$showAlert(`一共上传${res.data.total}条数据, 成功${res.data.successnum}条, 未抄下发${res.data.nohandnum}条, 失败下发${res.data.failednum}条, 异常下发${res.data.exceptionnum}条`, 'success', 2000)
            this.$parent.search()
          })
        }
      }
    }
  }
</script>
<style lang="less" scoped>
  #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);
    }
  }
</style>
