<template>
  <div class="flex-row" id="machineHandManager">
    <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-2 form-group">
                <label class="font_normal_body color-red">归属起始</label>
                <datepicker placeholder="开始日期"
                            style="width:60%"
                            class="datepicker"
                            v-model="model.startDate"
                            condition="f_hand_date >='{} 00:00:00'"
                            :value.sync="model.startDate"
                            :format="'yyyy-MM-dd'"
                ></datepicker>
              </div>
              <div class="col-sm-2 form-group">
                <label class="font_normal_body color-red">归属结束</label>
                <datepicker placeholder="结束日期"
                            style="width:60%"
                            v-model="model.endDate"
                            :value.sync="model.endDate"
                            condition="f_hand_date <='{} 23:59:59'"
                            :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" style="width:90px" @click="$parent.$parent.danhuShow()">
                  单户抄表
                </button>
                <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.getfield"
                  sqlurl="rs/logic/saleExport" sql-name="getIndustryCommerceHand" template-name='工业商业抄表导出'
                  :choose-col="true">
                </export-excel>
                <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">表&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_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 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" style="white-space: nowrap">
                <label class="font_normal_body">用&ensp;气&ensp;量</label>
                <div class="row">
                  <input type="text" style="width:30%" class="input_search" v-model="model.oughtamountmin"
                         condition="f_oughtamount >= {} " placeholder="">
                  <label class="font_normal_body"> ≤ x ≤ </label>
                  <input type="text" style="width:30%" class="input_search" v-model="model.oughtamountmax"
                         condition="f_oughtamount <= {} " placeholder="">
                </div>
              </div>
              <res-select-group :initres="$parent.$parent.initres"
                                @re-res="$parent.$parent.getRes"
                                :show-component="['company']"
                                v-ref:sel>
              </res-select-group>
            </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>
                <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>
                  <data-order field="f_address" name="基本信息"
                              :order.sync="$parent.$parent.$parent.orderFields.f_address"></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>
                <nobr>用气量</nobr>
              </th>
              <th>
                <nobr>
                  <data-order field="f_last_input_date" name="上次抄表录入日期"
                              :order.sync="$parent.$parent.$parent.orderFields.f_last_input_date"></data-order>
                </nobr>
              </th>
              <th>
                <nobr>
                  <data-order field="f_hand_date" name="下发日期"
                              :order.sync="$parent.$parent.$parent.orderFields.f_hand_date"></data-order>
                </nobr>
              </th>
              <th>
                <nobr>
                  <data-order field="f_input_date" name="抄表录入日期"
                              :order.sync="$parent.$parent.$parent.orderFields.f_input_date"></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>
                <nobr>操作</nobr>
              </th>
              <!--            f_oughtfee-->
            </tr>
          </template>
          <template partial='body'>
            <td style="text-align: center;">{{ $index + 1 }}</td>
            <td style="text-align: center;">{{ row.f_userinfo_code }}</td>
            <td style="text-align: center;">{{ row.f_user_name }}&nbsp;&nbsp;{{ row.f_address }}</td>
            <td style="text-align: center;">{{ row.belongmonth }}</td>
            <td style="text-align: center;">{{ row.f_meternumber }}</td>
            <td style="text-align: center;">{{ row.f_user_phone }}</td>
            <td style="text-align: center;">{{ row.f_last_tablebase }}</td>
            <td id="hand-creat" v-if="row.f_meter_state === '未抄表'" style="text-align: center;">
              <div class="form-group" style="margin-bottom:0px;display: contents;" :class="{
                       'has-success has-feedback': !row.error,
                       'has-error has-feedback': row.error}">
                <input title="可录入小数点后三位"
                       type="text" class="input_search"
                       v-model="row.f_tablebase"
                       @blur="$parent.$parent.$parent.beforenter($index, row)"
                       v-next-el="{id: $index+2}"
                       :id="$index+1"
                       style="width: 100px;padding: 6px;"
                       @focus="$parent.$parent.$parent.clearError(row)"
                       :disabled="row.state === '开始'">
              </div>
              <span v-if="row.error && row.error !== ''" style="color: #ff0000;">{{ row.error }}</span>
            </td>
            <td id="hand-creat" v-if="row.f_meter_state !== '未抄表' "  style="text-align: center;">
              {{ row.f_tablebase }}
            </td>
            <td style="text-align: center;">{{ $parent.$parent.$parent.calculationBase(row) }}</td>
            <td style="text-align: center;">{{ row.f_last_input_date }}</td>
            <td style="text-align: center;">{{ row.f_hand_date }}</td>
            <td style="text-align: center;">
              <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 === '未抄表' && $parent.$parent.$parent.jurisdiction.includes('录入日期修正')">
                <datepicker id="endDate" placeholder="抄表时间"
                            v-model="row.f_input_date"
                            :value.sync="row.f_input_date"
                            :format="'yyyy-MM-dd HH:mm:ss'"
                            :show-reset-button="true">
                </datepicker>
              </div>
              <div v-else>
                {{ row.f_input_date }}
              </div>
            </td>
            <td style="text-align: center;">{{ row.f_inputtor }}</td>
            <td style="text-align: center;">{{ row.f_input_person }}</td>
            <td style="text-align: center;">{{ row.f_operator }}</td>
            <td style="text-align: center;">{{ row.f_comments }}</td>
            <td style="text-align: center;"><nobr>
              <button v-if="row.f_notified_path" class="btn btn-link" @click.stop="$parent.$parent.$parent.imgShow(row.f_notified_path)">图像识别1</button>
              <br>
              <button v-if="row.f_notified2_path" class="btn btn-link" @click.stop="$parent.$parent.$parent.imgShow(row.f_notified2_path)">图像识别2</button>
              <br>
              <button v-if="row.f_notified3_path" class="btn btn-link" @click.stop="$parent.$parent.$parent.imgShow(row.f_notified3_path)">图像识别3</button>
            </nobr></td>
            <td style="text-align: center;">
              <nobr>
                <button type="button" name="button" class="button_search button_spacing width-60"
                        v-if="row.f_meter_state === '已抄表' && (row.id == row.maxid || !row.maxid)"
                        @click.stop="$parent.$parent.$parent.cancelAuditHand(row)">撤销
                </button>
                <button type="button" name="button" class="btn btn-danger"
                        v-if="row.f_meter_state === '未抄表'"
                        @click.stop="$parent.$parent.$parent.delectHand(row)">
                  删除
                </button>
              </nobr>
            </td>
          </template>
        </data-grid>
      </criteria-paged>
      <table class="table-hover">
        <tr style="position: relative" class="table-bordered">
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;color: #5CB95C;font-weight: bold">
            汇总信息
          </td>
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
            用气量:&emsp;{{ sumsmodel.f_oughtamount }}
          </td>
        </tr>
      </table>
    </div>
    <modal :show.sync="danhu.show" :title='danhutitle' backdrop="false" coverstyle="danhumodal">
      <article slot="modal-body" class="modal-body">
        <div class="panel panel-primary datapanel">
          <div class="row">
            <label class="control-label col-sm-6 flex-row" style="transform: translate(0,8px)">客户姓名：{{danhu.info.f_user_name}}</label>
            <label class="control-label col-sm-6 flex-row" style="transform: translate(0,8px)">客户编号：{{danhu.info.f_userinfo_code}}</label>
            <label class="control-label col-sm-6 flex-row" style="transform: translate(0,8px)">用户证号：{{danhu.info.f_book_no}}</label>
            <label class="control-label col-sm-12 flex-row" style="transform: translate(0,8px)">客户地址：{{danhu.info.f_address}}</label>
            <label class="control-label col-sm-6 flex-row" style="transform: translate(0,8px)">上次抄表日期：{{danhu.info.f_input_date}}</label>
            <label class="control-label col-sm-6 flex-row" style="transform: translate(0,8px)">上期底数：{{danhu.info.f_last_tablebase}}</label>
            <label class="control-label col-sm-6 flex-row" style="transform: translate(0,8px)">本期用量：{{f_current_usage}}</label>
          </div>
        </div>
        <div class="panel panel-primary datapanel">
          <div class="row">
            <div class="col-sm-6 flex-row" style="margin-top: 2px">
              <label for="danhucode" class="control-label" style="transform: translate(0,8px)">客户编号</label>
              <input id="danhucode" type="text" class="input_search " style="width: 60% !important;"
                     v-model="danhu.f_userinfo_code" v-ref:danhucode @keyup.enter.stop="danhuCodeSearch"
                     placeholder='客户编号'/>
            </div>
            <div class="col-sm-6 flex-row" style="margin-top: 2px">
              <label for="danhubase" class="control-label" style="transform: translate(0,8px)">本期底数</label>
              <input id="danhubase" type="number" class="input_search " style="width: 60% !important;"
                     v-model="danhu.f_new_tablebase" @keyup.enter.stop="downAndHand"
                     @blur="tableBaseBlur"
                     placeholder='本期底数'/>
            </div>
          </div>
        </div>
        <upload :blodid="row.f_userinfo_id" v-if="config.showupload" isremark="true" fusetype="物联网表收费"></upload>
      </article>
      <footer slot="modal-footer">
      </footer>
    </modal>
    <modal :show.sync="imgshow" v-ref:modal backdrop="true" coverstyle="modalContentRight">
      <header slot="modal-header" class="modal-header">
        抄表图像识别照片
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="from-group">
          <img-self :src="imgfilename" :width="750" :height="750"></img-self>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-success" @click='imgclose'>关闭</button>
      </footer>
    </modal>
  </div>
</template>
<script>
import {PagedList, HttpResetClass} from 'vue-client'
import Vue from 'vue'

let readyGen = async function (self) {
  self.getfield = self.config.excelHeaders
  self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
  self.reflash()
}

export default {
  title: '工商业抄表',
  data () {
    return {
      priceModel: false,
      initres: {
        org: [this.$login.f.orgid],
        dep: [],
        user: []
      },
      sumsmodel: [],
      orgCondtionStr: '',
      deletestate: false,
      criteriaShow: false,
      imgshow: false,
      imgfilename: '',
      model: new PagedList('rs/sql/getIndustryCommerceHand', 50, {orderitem: this.orderDefault ? '"' + this.orderDefault + ' "' : `'f_hand_date desc'`}, {
        f_oughtamount: 0,
        f_oughtfee: 0
      }),
      config: {
        // 导出列要和查询列相同
        excelHeaders: {
          'f_user_id': '表编号',
          'f_meternumber': '表号',
          'f_inputtor': '抄表员',
          'f_last_input_date': '上次抄表时间',
          'f_input_date': '抄表日期',
          'f_userinfo_code': '客户编号',
          'f_address': '客户地址',
          'f_residential_area': '小区名称',
          'f_user_name': '客户姓名',
          'f_last_tablebase': '上期底数',
          'f_tablebase': '本期指数',
          'f_oughtamount': '应交气量',
          'f_input_person': '录入人员',
          'f_meter_classify': '气表分类',
          'f_meter_style': '气表型号',
          'f_user_phone': '客户电话',
          'f_comments': '备注'
        },
        examine: true,
        customCal: false
      },
      meter_state: false, // 是否显示计划下发按钮
      downModel: {
        downDate: Vue.$login.toStandardTimeString(),
        downWay: 'downWithUserfiles',
        downInputtor: []
      },
      inputtorModel: {
        inputtor: [],
        reason: ''
      },
      f_current_usage:'',
      auditState: [{label: '全部', value: ''}, {label: '未抄表', value: '未抄表'}, {
        label: '待审核',
        value: '待审核'
      }, {label: '已抄表', value: '已抄表'}],

      plans: [], // 记录当前行是否被勾选
      all: false, // 是否全选
      show: false, // 下发日期模态框显示
      unhandplan: [], // 之前是否有未抄表记录
      downConfirm: false, // 下发若有未抄记录，确认框
      uploadshow: false,
      // 小区
      residentialArea: [],

      //  downDate: this.$login.toStandardYearMonth().replace("-", ""),
      msg: '',
      condition: '',
      orderDefault: 'f_hand_date',
      orderFields: {
        f_userinfo_id: 'no'
      },
      getfield: {},
      outlet: '',
      filiale: '',
      condition2: '',
      area: [],
      inputtouPerson: [],
      meters: [{label: '全部', value: ''}, {label: '机表', value: '机表'}, {label: '物联网表', value: '物联网表'}],
      resultstate: this.$appdata.getParam('抄表结果状态'),
      meterstates: [{label: '全部', value: ''}, {label: '未抄表', value: '未抄表'}, {label: '已抄表', value: '已抄表'}],
      usertypes: this.$appdata.getParam('客户类型') ? [{
        label: '全部',
        value: ''
      }, ...this.$appdata.getParam('客户类型')] : [],
      splitdata: '',
      f_filialeid: this.$login.f.orgid,
      meterbooks: [],
      upshow: false,
      inputid: 0,
      examineshow: false,
      examinerow: null,
      showfiles: false,
      uploadText: '抄表',
      examinetype: false,
      danhu: {
        show: false,
        f_userinfo_code: '',
        f_new_tablebase: '',
        info: {}
      },
      showerr: false,
      err: '',
      // 请求对象(批量导入,查询进度使用)
      HttpReset: new HttpResetClass(),
      row: null,
      // 应抄底数
      should_base: 0,
      // 计算公式
      designFormulas: null
    }
  },
  ready () {
    this.getaddress()
    readyGen(this)
  },
  mounted () {
    console.log(this.inputid)
    document.getElementById(this.inputid).focus()
  },
  methods: {
    tableBaseBlur () {
      if (this.danhu.f_new_tablebase) {
        this.f_current_usage = (this.danhu.f_new_tablebase -0) - (this.danhu.info.f_last_tablebase -0)
      }
    },
    imgclose () {
      this.imgshow = false
    },
    imgShow (val) {
      this.imgfilename = `rs/image/file/` + val
      this.imgshow = true
    },
    async danhuCodeSearch () {
      this.danhu.f_userinfo_code = this.danhu.f_userinfo_code.replace(/(^\s*)|(\s*$)/g, '')
      await this.$resetpost('rs/sql/getIndustryCommerceDanHu', {
        data: {
          f_userinfo_code: this.danhu.f_userinfo_code,
          f_orgid: this.f_filialeid
        }
      },
        {resolveMsg: null, rejectMsg: '查询用户信息失败，网络错误'}).then(res => {
          if (res.data.length !== 1) {
            this.$showAlert(res.data.length === 0 ? '没有查询到用户' : '查询到多条用户信息', 'warning', 3000)
            return
          }
          if (res.data[0].f_meter_state === '未抄表') {
            this.$showAlert('该用户有未抄表记录', 'warning', 3000)
            return
          }
          this.danhu.info = res.data[0]
          document.getElementById('danhubase').focus()
        })
    },
    calculationBase (row) {
      let oughtamount = null
      if (row.f_tablebase) {
        if (row.f_share_gas) {
          oughtamount = (row.f_tablebase - 0 - (row.f_last_tablebase - 0)).toFixed(4) + (row.f_share_gas > 0 ? '+' : '') + row.f_share_gas.toFixed(3)
        } else {
          if (row.f_capacity && row.f_capacity > 0 && row.f_tablebase < row.f_last_tablebase) {
            oughtamount = (row.f_tablebase - 0 + (row.f_capacity - row.f_last_tablebase)).toFixed(3)
          } else {
            oughtamount = (row.f_tablebase - 0 - (row.f_last_tablebase - 0)).toFixed(3)
          }
        }
      } else {
        oughtamount = 0
      }
      row.f_oughtamount = oughtamount
      return oughtamount
    },
    cancelHand (row) {
      if (this.config.examine) {
        let handdate = new Date(row.f_hand_date)
        let ima = new Date()
        if (handdate.getMonth() == ima.getMonth()) {
          this.cancelHand3(row)
        } else {
          if (!this.$login.r.find(value => value == '抄表隔月冲正')) {
            this.$showMessage('当前登录用户没有【抄表隔月冲正】权限, 请联系管理员!')
          } else {
            this.cancelHand3(row)
          }
        }
      } else {
        this.cancelHand3(row)
      }
    },
    cancelAuditHand (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 = 'rs/logic/IndustryCommerceHandCancel'
      this.$resetpost(url, {data: param}, {warnMsg: '确定对这条记录进行撤销吗？'}).then(() => {
        this.search()
        this.close()
      })
    },
    // 单户抄表
    async downAndHand () {
      if (!this.danhu.info.f_userinfo_code || this.danhu.info.f_userinfo_code === '') {
        this.$showAlert(`请先查询用户信息`, 'warning', 2000)
        return
      }
      if (this.danhu.f_new_tablebase < 0) {
        this.$showAlert(`底数不能小于0，请注意!`, 'warning', 2000)
        return
      } else if (this.danhu.f_new_tablebase.toString().split('.').length > 1 && this.danhu.f_new_tablebase.toString().split('.')[1].length > 3) {
        this.$showAlert(`底数最多只能输入小数点后3位，请注意!`, 'warning', 2000)
        return
      } else if (this.danhu.f_new_tablebase < this.danhu.info.f_tablebase && !this.danhu.info.f_capacity) {
        this.$showAlert(`本期表底数不能低于上期表底数`, 'warning', 2000)
        return
      }
      this.danhu.info.f_hand_date = this.$login.toStandardTimeString()
      this.danhu.info.f_meter_source = '单户抄表'
      this.danhu.info.f_operatorid = this.$login.f.id
      this.danhu.info.f_operator = this.$login.f.name
      this.danhu.info.f_inputtor = this.$login.f.name
      this.danhu.info.f_orgid = this.$login.f.orgid
      this.danhu.info.f_orgname = this.$login.f.orgs
      this.danhu.info.f_depid = this.$login.f.depids
      this.danhu.info.f_depname = this.$login.f.deps
      this.danhu.info.f_input_person = this.$login.f.name
      this.danhu.info.f_new_tablebase = this.danhu.f_new_tablebase
      this.$resetpost('rs/logic/IndustryCommerceHandEnter', {data: this.danhu.info}, {
        resolveMsg: null,
        rejectMsg: null
      }).then((res) => {
        this.$showAlert(`单户抄表成功!`, 'success', 2000)
        this.danhuShow()
      }).catch((error) => {
        this.danhu.show = false
        this.$showAlert(`抄表失败,请注意查看，失败原因：` + JSON.toString(error), 'danger', 2000)
      })
    },
    danhuShow () {
      this.model.params.startDate = this.$refs.paged.$refs.criteria.model.startDate
      this.model.params.endDate = this.$refs.paged.$refs.criteria.model.endDate
      this.downModel.downDate = this.$login.toStandardTimeString()
      this.danhu = {
        show: true,
        f_userinfo_code: '',
        f_new_tablebase: '',
        info: {}
      }
      this.f_current_usage = ''
      setTimeout(() => {
        document.getElementById('danhucode').focus()
        this.$refs.paged.$refs.criteria.search()
      }, 100)
    },
    paycodefocus () {
      this.$nextTick(() => {
        this.$els.paycode.focus()
      })
    },
    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
    },
    hidden () {
      this.criteriaShow = !this.criteriaShow
    },
    clear () {
      Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
        this.$refs.paged.$refs.criteria.model[key] = []
      })
    },
    search () {
      // 查询前清空选择项
      this.plans = []
      this.$refs.paged.$refs.criteria.search()
    },
    selfSearch (args) {
      this.meter_state = args.condition.includes('未下发')
      this.inputtor_change = args.condition.includes('未抄表')
      console.log('=====抄表1====', args.condition.includes('未抄表'))
      console.log('=====抄表1====', this.deletestate)
      if (args.condition.includes('未抄表')) {
        this.deletestate = true
      } else {
        this.deletestate = false
      }
      console.log('=====抄表1====', this.deletestate)
      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()
    },
    beforenter (index, row) {
      this.inputid = index + 1
      // 限制本次抄表不能低于上次
      if (row.f_tablebase) {
        if (row.f_tablebase < 0) {
          row.state = '失败'
          Vue.set(row, 'error', '底数不能小于0')
          this.speckText('底数不能小于0，请注意!')
        } else if (this.danhu.f_new_tablebase.toString().split('.').length > 1 && this.danhu.f_new_tablebase.toString().split('.')[1].length > 3) {
          row.state = '失败'
          Vue.set(row, 'error', '底数最多只能输入小数点后3位')
          this.speckText('底数最多只能输入小数点后3位，请注意!')
        } else if (row.f_tablebase < row.f_last_tablebase && !row.f_capacity) {
          row.state = '失败'
          Vue.set(row, 'error', '本期表底数不能低于上期表底数')
          this.speckText('本期表底数不能低于上期表底数，请注意!')
        } else {
          if (row.f_tablebase < row.f_last_tablebase) {
            this.$showMessage('本次抄表已超越最大量程, 请熟知!')
          }
          // 抄表结果状态没选默认给正常
          row.f_result_state = row.f_result_state ? row.f_result_state : '正常'
          this.enter(index, row)
        }
      }
    },
    enter (index, row) {
      console.log('录入数据。..', row)
      let f_input_date = Vue.$login.toStandardTimeString()
      let handplan = {
        id: row.id,
        f_oughtamount: row.f_oughtamount,
        f_tablebase: row.f_tablebase,
        f_hand_date: f_input_date,
        f_input_date: f_input_date,
        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_yccustom_handplan', handplan, {
        resolveMsg: null,
        rejectMsg: '抄表数据保存出错!!!'
      }).then((res) => {
        row.f_meter_state = '已抄表'
        row.f_input_date = f_input_date
        let sql = `update t_userfiles set f_yc_meter_base = ${row.f_tablebase} where f_userfiles_id = '${row.f_userfiles_id}' `
        this.$resetpost('rs/logic/runSQL', { sql: sql })
      }).catch((error) => {
        row.state = '失败'
        Vue.set(row, 'error', JSON.stringify(error))
        this.speckText('抄表录入出错，请注意!')
      })
    },
    clearError (row) {
      if (row.f_tablebase === 0) {
        row.f_tablebase = ''
      }
      Vue.set(row, 'error', null)
    },
    async speckText (str) {
      var url = 'http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=6&text=' + encodeURI(str)
      await new Audio(url).play()
      this.err = str
      this.showerr = true
      this.paycodefocus()
    },
    closeerr () {
      this.showerr = false
    },
    // 删除这条计划
    delectHand (row) {
      let sql = `update t_yccustom_handplan set f_hand_state = '无效' where id = '${row.id}' `
      this.$resetpost('rs/logic/runSQL', { sql: sql }).then((res) => {
        this.search()
      })
    },
    cancelHand3 (row) {
      // 抄表加入权限
      if (!this.$login.r.find(value => value == '机表抄表冲正')) {
        this.$showMessage('当前登录用户没有冲正权限, 请联系管理员!')
        return
      }
      // 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 = 'rs/logic/sale_commonEnterCancel'
      this.$resetpost(url, {data: param}, {warnMsg: '确定对这条记录进行撤销吗？'}).then(() => {
        this.search()
        this.close()
      })
    },
    // 关闭下发计划得弹出框
    close () {
      this.show = false
      this.inputtor_show = false
      this.downConfirm = false
      this.examineshow = false
      this.examinetype = false
      this.detailsShow = false
      this.priceModel = 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.search()
    }
  },
  watch: {
    'detailsShow' (val) {
      if (!val) {
        this.should_base = 0
        this.designFormulas = null
      }
    }
  },
  computed: {
    danhutitle () {
      return '单户抄表    当前计划年月：' + this.downModel.downDate
    },
    getCondition () {
      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
      }
    },
    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 [...rs]
    },
    // 界面细节权限
    jurisdiction () {
      console.log('抄表界面细节', this.$login.r)
      return this.$login.r ? this.$login.r : []
    }
  },
  events: {
    dblclick: function (row, index) {
      this.row = row
      this.detailsShow = true
    },
    // 删除Resid数组元素
    'delResid' (val) {
      this.resid.$remove({id: val, f_biobid: ''})
    },
    // 增加Resid数组元素
    'resid' (val) {
      console.log('-=', val)
      this.resid.push({id: val, f_biobid: ''})
    }
  }
}
</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);
    }
  }

  .detail-panel {
    text-align: center;
    color: #31708f;
    background-color: #e8f1f9;
    border-color: #F2F6FA;
  }
}

#hand_manager_grid {
  thead {
    position: relative;
    z-index: 2;
  }
}

#machineHandManager {
  .color-red {
    color: red;
  }
}
</style>
