<template>
  <form novalidate class="form-horizontal" style="width: 95%;margin: auto">
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户ID.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_userinfo_code" class=" font text-left">用户编号：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_userinfo_code" class="search_input input-font"
               v-model=item.f_userinfo_code readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户姓名.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label class="font text-left">用户姓名：</label>
      </div>
      <div class="col-xs-8">
        <input class="search_input input-font"
               v-model=item.f_user_name readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/详细住址.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label class="font text-left">用户地址：</label>
      </div>
      <div class="col-xs-8">
        <input class="search_input text-input input-font"
               v-model=item.f_address readonly="readonly"/>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/详细住址.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label class="font text-left">是否楼层用户：</label>
      </div>
      <v-select :value.sync="item.f_is_lc" class="input-font" style="margin-left: 5%;"
                :width="'60%'"
                v-model="item.f_is_lc"
                :options='is_no' placeholder='是否楼层用户' close-on-select clear-button value-single
      ></v-select>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/详细住址.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label class="font text-left">定位位置：</label>
      </div>
      <div class="col-xs-8">
        <input type="text"  class="search_input text-input input-font" style="width: 45%"
               v-model=item.f_host_meter_name :value.sync="item.f_host_meter_name" readonly/>
        <button type="button"
                name="button" class="btn btn-primary" style="width: 35%" @click="getposition">定位
        </button>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户电话.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_housing" class="font text-left">用户电话：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_housing" class="search_input input-font"
               v-model="item.f_user_phone" readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/表号.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_meter_number" class="font text-left">表号：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_meter_number" class="search_input input-font"
               v-model="item.f_meternumber" readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/门牌.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_cardmeternumber" class="font text-left">现场表号：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_cardmeternumber" class="search_input input-font"
               v-model="item.f_cardmeternumber" placeholder="请设置用户现场表标记"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户类型.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_user_type" class="font text-left">用户类型：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_user_type"  class="search_input input-font"
               v-model="item.f_user_type" readonly="readonly"/>
      </div>
    </div>
    <div class="row app-row" :style="{color: item.f_is_special == '是' ? 'red' : 'inherit' }">
      <div class="col-xs-4">
        <img src="../../assets/用户类型.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_user_type" class="font text-left">是否为特殊用户：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_is_special"  class="search_input" style="font: 15px PingFang-SC-Medium;"
               v-model="item.f_is_special" readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row" :style="{color: item.f_special_type ? 'red' : 'inherit' }">
      <div class="col-xs-4">
        <img src="../../assets/用户类型.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_user_type" class="font text-left">特殊用户分类：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_special_type"  class="search_input" style="font: 15px PingFang-SC-Medium;"
               v-model="item.f_special_class" readonly="readonly"/>
      </div>
    </div>
    <div class="row app-row" :style="{color: meterDate.f_meter_read_special_type ? 'red' : 'inherit' }">
      <div class="col-xs-4">
        <img src="../../assets/上传状态.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_difference" class="font text-left">现场情况内容：</label>
        <!--累购-当前表底数-剩余-->
      </div>
      <div class="col-xs-8">
        <v-select  :close-on-select="true" search="false" :value-single="true"
                   :value.sync="meterDate.f_meter_read_special_type" class="input-font"
                   :options='special_type' placeholder='现场情况内容'
                   close-on-select clear-button
                   v-model="meterDate.f_meter_read_special_type"></v-select>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/用户类型.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_gasproperties" class="font text-left">用气性质：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_gasproperties"  class="search_input input-font"
               v-model="item.f_gasproperties" readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/表类型.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_meterclassify" class="font text-left">表类型：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_meterclassify" class="search_input input-font"
               v-model="item.f_meter_classify" readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/shijian.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_tablebase" class="font text-left">上次时间：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_tablebase" class="search_input input-font"
               v-model="item.f_check_meter_data[0].f_hand_date" readonly="readonly"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/数据.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_hand_date" class="font text-left">上次底数：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_hand_date" class="search_input input-font" type="text"
               v-model="item.f_check_meter_data[0].f_tablebase" readonly="readonly"/>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/数据.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_hand_date" class="font text-left">上期剩余：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_last_surplus_gas" class="search_input input-font" type="text"
               v-model="item.f_check_meter_data[0].f_surplus_gas" readonly="readonly"/>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/数据.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_newhand_date" class="font text-left">本期底数：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_newhand_date" class="search_input input-font" type="number" placeholder="请输入本期底数"
               v-model="bottomOfTheCurrentPeriod" @input="countTotalGasDifference"
        />
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/guandao1.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="theRemainingAmount" class="font text-left">剩余量：</label>
      </div>
      <div class="col-xs-8">
        <input id="theRemainingAmount"  type="number" class="search_input input-font" placeholder="请输入当前剩余量"
               v-model="theRemainingAmount" @input="countTotalGasDifference"
        />
      </div>
    </div>
<!--  卡表和机表是累购气量，物联网表是累购金额  -->
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/housestyle.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_total_gas_total_fee" class="font text-left" v-if="item.f_meter_classify != '物联网表'">累购气量：</label>
        <label for="f_total_gas_total_fee1" class="font text-left" v-if="item.f_meter_classify == '物联网表'">累购金额：</label>
      </div>
      <div class="col-xs-8">
        <input id="f_total_gas_total_fee"  type="number" class="search_input input-font" placeholder="累购气量" v-if="item.f_meter_classify != '物联网表'"
               v-model="item.f_total_gas_total_fee" readonly="readonly"/>
        <input id="f_total_gas_total_fee1"  type="number" class="search_input input-font" placeholder="累购金额" v-if="item.f_meter_classify == '物联网表'"
               v-model="item.f_total_gas_total_fee" readonly="readonly"/>
      </div>
    </div>
    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/差值.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_difference" class="font text-left" :style="{color: errorTotalGasDifferenceClass}">累购差值：</label>
        <!--累购=当前表底数-剩余-->
        <!--物联网表的累购=当前表底数金额-剩余金额-->
      </div>
      <div class="col-xs-8">
        <input id="f_difference" class="search_input input-font" readonly="readonly" v-model="totalGasDifference"/>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/上传状态.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_difference" class="font text-left">抄表类型：</label>
        <!--累购-当前表底数-剩余-->
      </div>
      <div class="col-xs-8">
        <v-select  :close-on-select="true" search="false" :value-single="true"
                  :value.sync="meterDate.f_meter_read_type" class="input-font"
                  :options='f_meter_read_types' placeholder='抄表类型'
                  close-on-select clear-button
                  v-model="meterDate.f_meter_read_type"></v-select>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px;margin-bottom: 5px" alt="">
        <label for="f_difference" class="font text-left" >备注：</label>
      </div>
      <div class="col-xs-8">
        <textarea v-model="meterDate.f_remake" rows="2" class="input_textarea"></textarea>
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">进气铅封：</label>
      </div>
      <div class="col-xs-8">
        {{ item.f_airintake_seal_no }}
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-4">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">出气铅封：</label>
      </div>
      <div class="col-xs-8">
        {{ item.f_airouttake_seal_no }}
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-6">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">最新一次入户安检时间：</label>
      </div>
      <div class="col-xs-6">
        {{ lastSafeData.f_offsite_time }}
      </div>
    </div>

    <div class="row app-row">
      <div class="col-xs-6">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">距离当日未安检天数：</label>
      </div>
      <div class="col-xs-6">
        {{ diffInDays }}
      </div>
    </div>

    <div class="row app-row" v-if="item.f_meter_classify == '物联网表'">
      <div class="col-xs-4">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">末次通讯时间：</label>
      </div>
      <div class="col-xs-8">
        {{ lastMeterData.f_input_date }}
      </div>
    </div>

    <div class="row app-row" v-if="item.f_meter_classify == '物联网表'">
      <div class="col-xs-4">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">末次抄表底数：</label>
      </div>
      <div class="col-xs-8">
        {{ lastMeterData.f_tablebase }}
      </div>
    </div>

    <div class="row app-row" v-if="item.f_meter_classify == '物联网表'">
      <div class="col-xs-4">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">系统余额：</label>
      </div>
      <div class="col-xs-8">
        {{ lastMeterData.f_curbalance }}
      </div>
    </div>
    <div class="row app-row" v-if="item.f_meter_classify == '物联网表'">
      <div class="col-xs-12">
        <table class="table table-striped table-bordered" style="margin-bottom: 6px;width: 100%;">
          <thead>
          <tr style="border: #E9E9E9 solid 2px">
            <th colSpan="6" style="text-align: center">最后十次异常记录</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="row in tableAnomalyRecords.warninfo" style="margin-top: 5px;border-collapse: collapse;border: #E9E9E9 solid 2px">
            <td colSpan="6" style="text-align: left">
              <div class="col-xs-12 col-sm-6 col-md-6">
                上报时间: {{ row.f_insert_date }}
              </div>
              <div class="col-xs-12 col-sm-6 col-md-6">
                异常类型: {{ row.f_error_type }}
              </div>
              <div class="col-xs-12 col-sm-6 col-md-6">
                异常信息: {{ row.f_error_msg }}
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="row app-row" v-if="item.f_meter_classify.includes('卡表')">
      <div class="col-xs-6">
        <img src="../../assets/baoxiuxinxi1.png" style="width: 20px; margin-bottom: 5px;" alt="">
        <label class="font text-left">距离当日未充值天数：</label>
      </div>
      <div class="col-xs-6">
        {{ rechargeDiffDays }}
      </div>
    </div>
<!--   <div class="form-group col-sm-12" :class="style__">
      <label class="text-left font">用户签名</label>
      <div class="auto">
        <div class="panel">
          <div class="panel-body panel-self"
               style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
            <div class="row" style="height: 240px;overflow: scroll;top: 1px">
              <div class="col-sm-4">
                <img :class="style__" :src="meterDate.f_sign_path" :width="200" :height="150" alt="签名"/>
              </div>
            </div>
            <div class="row text-right div-photo">
              <button type="button" name="button" class="btn btn-primary btn-photo" @click="sign">签名</button>
            </div>
          </div>
        </div>
      </div>
    </div>-->

    <div class="form-group col-md-12 col-sm-12 col-xs-12">
      <label class="text-left font">用户表底数照片(要求能清晰反应用户表底数信息)：</label>
      <div class="auto">
        <div class="panel" style="padding: 10px 10px 5px 10px;">
          <div class="panel-body panel-self" style="background-color: #F8F8F8;width: 100%;height: 260px;position: relative">
            <div class="row" style="height: 240px;overflow: scroll;top: 1px">
              <div class="col-xs-4 col-sm-3 col-md-2" style="margin-bottom: 35px" v-for="(index,img) in meterDate.f_meter_paths">
                <img-self :src="img.f_meter_path" alt="用户表底数照片" :width="150" :height="200"></img-self>
                <img src="../../assets/删除.png" @click="delfile('f_meter_paths', img.f_meter_path,index)" style="width: 15px;margin-top: -80px" alt="">
              </div>
            </div>
            </div>
            <div class="row text-right div-photo">
              <button type="button" name="button" class="btn btn-primary btn-photo"
                      @click="takePic('f_meter_paths', '居民用户抄表照片')">拍照
              </button>
            </div>
          </div>
        </div>
      </div>

    <div class="row text-center" style="margin-top: 20px;">
      <button type="button" class="btn btn-lg btn-font btn-color" style="width: 25%;" @click="saveCheckMeterReding">
        提交
      </button>
    </div>
    <div style="height:30px;"></div>
  </form>
</template>

<script>
import Vue from 'vue'
import * as Util from '../Util'
import {HttpResetClass} from 'vue-client'
import co from 'co'

export default {
  title: '居民移动抄表',
  data () {
    return {
      totalGasDifference: 0, // 累购差值
      bottomOfTheCurrentPeriod: '', //当前底数
      theRemainingAmount: '', //剩余量
      errorTotalGasDifferenceClass: '#666666',
      f_meter_read_types: [{label: '日常抄表',value: '日常抄表'},{label: '月度抄表',value: '月度抄表'}],
      is_no: [{label: '是',value: '是'},{label: '否',value: '否'}],
      lastSafeData:{},
      tableAnomalyRecords:null,
      lastMeterData:{},
      rechargeDiffDays:0,
      warninfo:[],
      special_type: this.$appdata.getParam('现场情况内容'),
      diffInDays:0,
      meterDate: {
        f_inputtor_id: Vue.user.id,//抄表员ID
        f_sign_path: '', //签名照片
        f_total_gas_total_fee: '', //累购气量、累购金额
        f_meter_paths: [ //总体照片
        ],
        f_remake:'', //备注
        f_newmeter_paths: [],
        t_userfiles: {},
        f_meter_read_special_type:'',
        f_meter_read_type: '月度抄表'
      },
      isErrorDifference: '正常'
    }
  },
  props: ['item', 'role'],
  components: {},
  methods: {
    getposition(){
      const longitude = HostApp.getPreference('longitude')
      const latitude = HostApp.getPreference('latitude')
      this.item.f_host_meter_name = JSON.stringify([longitude.data, latitude.data])
    },
    //统计差值
    countTotalGasDifference () {
      // 当当前底数和剩余量都填入正确的值后（如果是物联网表则为 本次抄表金额 和 剩余金额）
      if (this.bottomOfTheCurrentPeriod && this.theRemainingAmount) {
        this.totalGasDifference = parseFloat(this.item.f_total_gas_total_fee + "") - parseFloat(this.bottomOfTheCurrentPeriod + "") -  parseFloat(this.theRemainingAmount+"")
        /*从参数管理中获取： 安检抄表最大异常差值 */
        if (Math.abs(this.totalGasDifference) > this.$appdata.getSingleValue('民用异常差值允许误差')) {
          this.isErrorDifference = '异常'
          this.errorTotalGasDifferenceClass = 'red'
        } else {
          this.isErrorDifference = '正常'
          this.errorTotalGasDifferenceClass = '#666666'
        }
      } else {
        console.log('值错误，当前底数和剩余量未赋值')
        this.errorTotalGasDifferenceClass = '#666666'
        this.isErrorDifference = '正常'
      }
    },

    // 保存操作
    saveCheckMeterReding () {
      if (!this.meterDate.f_meter_read_type) {
        return this.$showMessage('请选择抄表类型')
      }
      if (this.item.f_is_lc == '否' && !this.item.f_host_meter_name){
        this.$showMessage('不为楼层用户时，需在表具信息中重新定位')
        return
      }
      if (this.bottomOfTheCurrentPeriod === '' && this.theRemainingAmount === '') {
        return this.$showMessage('请填写当前表底数与剩余量')
      }
      // if (this.meterDate.f_sign_path === '' || this.meterDate.f_meter_paths.length === 0 || this.meterDate.f_meter_paths[0].f_meter_path===Vue.nopic ) {
       if (this.meterDate.f_meter_paths.length === 0 || this.meterDate.f_meter_paths[0].f_meter_path===Vue.nopic ) {
        return this.$showMessage('请拍摄用户表底数相关照片')
      }
      var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]");
      if (this.item.f_cardmeternumber===''||pattern.test(this.item.f_cardmeternumber)){
        return this.$showMessage('请检查用户现场表号！必填且不可包含特殊字符！')
      }
      if (this.meterDate.f_inputtor_id != Vue.user.id) {
        this.meterDate.f_inputtor_id = Vue.user.id
      }
      this.meterDate.f_is_lc = this.item.f_is_lc
      this.meterDate.f_meter_read_is_special = this.item.f_is_special
      this.meterDate.t_userfiles.f_cardmeternumber = this.item.f_cardmeternumber //用户表标记字段
      this.meterDate.t_userfiles.f_userfiles_id = this.item.f_userfiles_id //userfiles的主键id
      this.meterDate.t_userfiles.f_host_meter_name = this.item.f_host_meter_name //定位地址

      this.meterDate.f_difference_value = this.totalGasDifference
      this.meterDate.f_difference_state = this.isErrorDifference //差值状态。正常或异常
      // 表类型
      this.meterDate.f_meter_classify = this.item.f_meter_classify
      // 本次抄表底数
      this.meterDate.f_tablebase = this.bottomOfTheCurrentPeriod
      // 上次抄表底数
      this.meterDate.f_last_tablebase = this.item.f_check_meter_data.length>0 ? this.item.f_check_meter_data[0].f_tablebase : ''
      // 上次抄表时间 item.f_check_meter_data[0].f_hand_date
      this.meterDate.f_last_hand_date = this.item.f_check_meter_data.length>0 ? this.item.f_check_meter_data[0].f_hand_date : ''
      // 本期剩余气量
      this.meterDate.f_surplus_gas = this.theRemainingAmount
      // 累购气量/累购金额
      this.meterDate.f_total_gas_total_fee = this.item.f_total_gas_total_fee
      // 抄表员
      this.meterDate.f_inputtor = Vue.user.name
      // 操作人
      this.meterDate.f_operator = Vue.user.name
      // 公司机构ids
      this.meterDate.f_filialeids = this.item.f_filialeid
      // 分公司
      this.meterDate.f_filiale = this.item.f_orgname
      //用户表编号
      this.meterDate.f_userfiles_id = this.item.f_userfiles_id
      // 用户姓名
      this.meterDate.f_user_name = this.item.f_user_name
      this.meterDate.f_userinfo_code = this.item.f_userinfo_code
      this.meterDate.f_user_phone = this.item.f_user_phone
      this.meterDate.f_user_type = this.item.f_user_type
      this.meterDate.f_gasproperties = this.item.f_gasproperties
      this.meterDate.f_userinfo_id = this.item.f_userinfo_id
      this.meterDate.f_address = this.item.f_address
      this.meterDate.f_residential_area = this.item.f_residential_area
      this.meterDate.f_building = this.item.f_building
      this.meterDate.f_unit = this.item.f_unit
      this.meterDate.f_room = this.item.f_room
      this.meterDate.f_meternumber = this.item.f_meternumber
      this.meterDate.f_meter_brand = this.item.f_meter_brand // 气表品牌
      this.meterDate.f_meter_style = this.item.f_meter_style //气表型号
      // 取上次抄表时间和现在时间算  距离最后一次抄表时间的天数
      if (this.item.f_check_meter_data.length > 0 && this.item.f_check_meter_data[0].f_hand_date) {
        // 距离最后一次抄表时间的天数
        this.meterDate.f_lastdate_to_days = Math.round((Date.parse(new Date()) - Date.parse(this.item.f_check_meter_data[0].f_hand_date))/1000/60/60/24)
        // 距离上次抄表的日均用气量 = （ 本次抄表底数 - 上次超表底数 ）/ 期间天数
        if ((parseFloat(this.bottomOfTheCurrentPeriod + "") - parseFloat(this.item.f_check_meter_data[0].f_tablebase + "")) / ( Math.round((Date.parse(new Date()) - Date.parse(this.item.f_check_meter_data[0].f_hand_date))/1000/60/60/24)) === Infinity) {
          this.meterDate.f_lastdate_average_gas_consumption_day = 0
        }else {
          this.meterDate.f_lastdate_average_gas_consumption_day = (parseFloat(this.bottomOfTheCurrentPeriod + "" )- parseFloat(this.item.f_check_meter_data[0].f_tablebase + "")) / ( Math.round((Date.parse(new Date()) - Date.parse(this.item.f_check_meter_data[0].f_hand_date))/1000/60/60/24))
        }
      }else {
        this.meterDate.f_lastdate_to_days = 0 //距离上次抄表时间过去多少天
        this.meterDate.f_lastdate_average_gas_consumption_day = 0 //距离上次抄表日均用气量
      }
      // 当前抄表时间
      this.meterDate.f_hand_date = Util.toStandardTimeString()
      // 是否存在差值异常
      this.meterDate.f_difference_odd = this.isErrorDifference
      // 根据本次抄表的最新表号和上次抄表的表号进行判断  判断是否换过表
      if (this.item.f_check_meter_data.length > 0 && this.item.f_check_meter_data[0].f_meternumber && this.item.f_meternumber) {
        if (this.item.f_check_meter_data[0].f_meternumber !== this.item.f_meternumber) {
          this.meterDate.f_is_change_table = "期间有换表"
        }else {
          this.meterDate.f_is_change_table = "期间未换表"
        }
      }else {
        this.meterDate.f_is_change_table = "期间未换表"
      }
      // 保存抄表信息 ${this.$androidUtil.getProxyUrl()}
      let paramStr = JSON.stringify(this.meterDate)
      // 多长截断一次
      let subLength = 800
      for (let i = 0; i < paramStr.length; i += subLength) {
        HostApp.param_cache(paramStr.substr(i, subLength))
      }
      HostApp.__this__ = this
      HostApp.syncLogic({
        // logic别名，key必须为logic
        'logic': 'uploadCheckHandplan',
        // 回调执行方法名，key必须为callback
        'callback': 'javascript:HostApp.__this__.uploadCallBack()',
        // 固定key，代表是否将logic执行结果作为参数传入回调方法，1代表true，0代表false，
        // 执行回调方法传入key为backresult
        // 如需额外拼接参数，写在logic返回值的params，例如xxlogic返回:{"params": "success"}
        'backresult': 1
      })
    },
    // 上传回调
    uploadCallBack(response) {
      console.log("上传回调返回" + JSON.stringify(response))
      let obj = JSON.parse(response.result)
      if (obj.code == 200) {
        console.log('成功')
        this.$showMessage('抄表信息上传成功！')
        this.callbackChangeSpecial()
      } else {
        if (obj.msg) {
          return this.$showMessage(`${obj.msg}`)
        } else {
          return this.$showMessage('抄表信息上传失败，服务器内部错误！')
        }
      }
    },
    async callbackChangeSpecial(){
      let resp = await new HttpResetClass().load('POST', `${this.$androidUtil.getProxyUrl()}/api/af-safecheck/sql/safe_singleTable_OrderBy`, {
        data: {
          items: "id",
          tablename: `t_check_handplan `,
          condition: `f_userinfo_id = '${this.item.f_userinfo_id}'`,
          orderitem: "id desc"
        }
      }, { resolveMsg: null, rejectMsg: null })
      if (resp.data.length > 0){
        const sql = `UPDATE t_special_user
          SET f_meteread_maxid = '${resp.data[0].id}',
          f_special_type = '${this.meterDate.f_meter_read_special_type}'
        WHERE id = (
            SELECT max_id
            FROM (
                SELECT MAX(id) AS max_id
                FROM t_special_user
                WHERE f_userinfo_code = '${this.item.f_userinfo_code}'
            ) AS tmp
        )`
        new HttpResetClass().load('POST',`${this.$androidUtil.getProxyUrl()}/api/af-safecheck/logic/runSQL`, {data: {
            sql:sql
          }}, {resolveMsg: null, rejectMsg: null}).then(() => {
          this.$dispatch('confirm')
        }).catch(e=>{
          console.log(e)
        })
      }
    },
    // 签名回调
    signCallback (prop, fileName1) {
      // HostApp.alert('绑定属性:' + prop + ' 文件全路径如file:///storage/sdcard0/safecheck/abc.jpg：' + fullFileName)
      HostApp.__this__.$set('meterDate.f_sign_path', fileName1)
      HostApp.__this__.$set('meterDate.signfileName', fileName1.substring(fileName1.lastIndexOf('/') + 1, fileName1.length))
      HostApp.__callback__ = null
      HostApp.__this__ = null
    },
    // 用户签名
    sign () {
      this.delfile('f_sign_path', this.meterDate.f_sign_path,0)
      let prop = 'f_sign_path'
      let idx = 'aofeng'
      let fileName1
      if (!this.meterDate.f_sign_path) {
        fileName1 = Util.guid() + '-valve-' + idx + '-' + prop + '.jpg'
      } else {
        fileName1 = Util.getFileName(this.meterDate.f_sign_path)
      }
      HostApp.__callback__ = this.signCallback
      HostApp.__this__ = this
      HostApp.getSignature({
        file: fileName1,
        requestCode: 111,
        callback: 'javascript:HostApp.__callback__("' + prop + '", "%s");'
      })
    },
    // 拍照回调
    cameraCallBack (prop, fileName) {
      if(prop == 'f_meter_paths'){ //总体图片为多图
        HostApp.__this__.meterDate.f_meter_paths.push({
          f_meter_path:fileName
        })
      }else{
        HostApp.__this__.meterDate[prop] = fileName
      }
      HostApp.__callback__ = null
      HostApp.__this__ = null
      // HostApp.__this__.$set('meterDate.f_meter_path', fileName)
      // HostApp.__this__.$set('meterDate.imgsfilename', fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length))
    },
    // 拍照
    takePic (prop, title, index) {
      HostApp.__callback__ = this.cameraCallBack
      HostApp.__this__ = this
      let fileName
      if (prop === 'f_meter_paths') {
        if (!this.meterDate.f_meter_paths[index] || this.meterDate.f_meter_paths[index].f_meter_path.includes('nopic.png')) {
          fileName = Util.guid() + '-' + prop + '.jpg'
        } else {
          fileName = Util.getFileName(this.meterDate.f_meter_paths[index].f_meter_path)
        }
      } else {
        if (!this.meterDate[prop] || this.meterDate[prop].includes("nopic.png")) {
          fileName = Util.guid() + '-' + prop + '.jpg'
        } else {
          fileName = Util.getFileName(this.meterDate[prop])
        }
      }
      HostApp._open_a_page({
        type: 'boomerang',
        page: 'com.aofeng.hybrid.android.peripheral.CameraActivity',
        param: {
          file: fileName,
          requestCode: 111,
          callback: 'javascript:HostApp.__callback__("' + prop + '", "%s");',
          watermark: title + '\t时间：' + Util.toStandardTimeString() + '\t' + Vue.user.name + '\t' + this.item.f_address
        }
      })
    },
    // 删除文件
    delfile (prop, fileName,index) {
      if (fileName == Vue.nopic) {
        return
      } else {
        if(prop === 'f_meter_paths'){
          this.meterDate.f_meter_paths.splice(index,1)
          HostApp.delfile(fileName)
        }else{
          HostApp.delfile(fileName)
          this.meterDate[prop] = Vue.nopic
        }
      }
    },
    // 初始化数据
    clearAll () {
      console.log('清除页面中累购差值与当前底数，剩余量')
      this.totalGasDifference = 0 // 累购差值
      this.bottomOfTheCurrentPeriod = '' //当前底数
      this.theRemainingAmount = '' //剩余量
      this.errorTotalGasDifferenceClass = '#666666'
      this.isErrorDifference = '正常'
      for (let item of this.meterDate.f_meter_paths) {
        this.delfile('f_meter_paths', item.f_meter_path,0)
      }
      this.delfile('f_sign_path', this.meterDate.f_sign_path,0)
      this.meterDate= {
        f_inputtor_id: Vue.user.id,
        f_sign_path: '', //签名照片
        f_meter_paths: [],
        f_newmeter_paths: [],
        t_userfiles: {},
        f_remake:''
      }
    },

    // 本月是否进行过月度抄表,进行过月度抄表，则不允许抄月度抄表
    isMonthCheckPlan () {
      let http1 = new HttpResetClass()
      http1.load('POST',`${this.$androidUtil.getProxyUrl()}/api/af-safecheck/sql/findHandPlanIsMonth`, {data: {
          condition: ` f_meter_read_type = '月度抄表'`,
          userinfoid: `${this.item.f_userinfo_id}`
        }}, {resolveMsg: null, rejectMsg: null}).then((ress) => {
        let ressdata  = ress.data
        // 当选择的是月度抄表的时候，并且本月已有月度抄表记录，则本月只可进行日常抄表了
        if (this.meterDate.f_meter_read_type==='月度抄表' &&  ressdata.length > 0) {
          this.meterDate.f_meter_read_type = '日常抄表'
          this.f_meter_read_types = [{label: '日常抄表',value: '日常抄表'}]
          return this.$showMessage(`当前用户，已在本月${ressdata[0].f_hand_date},被抄表员${ressdata[0].f_inputtor}进行过【月度抄表】,月度抄表每月一次。已为你自动切换为【日常抄表】`)
        } else if (this.meterDate.f_meter_read_type==='日常抄表' && ressdata.length <= 0) {
          this.f_meter_read_types =  [{label: '日常抄表',value: '日常抄表'},{label: '月度抄表',value: '月度抄表'}]
          // 当选择的是日常抄表，并且本月还未进行过月度抄表，则提示未完成月度抄表任务
          return this.$showMessage("本月还未完成该用户的【月度抄表】任务，请优先完成【月度抄表】任务(该信息仅为提示信息，可忽略)");
        } else {
          console.log("月度抄表未完成，选择的也是月度抄表；选择的日常抄表但是月度抄表已完成，")
        }
      })
    },
    async getSafeData(){
      let resp = await new HttpResetClass().load('POST', `${this.$androidUtil.getProxyUrl()}/api/af-safecheck/sql/safe_singleTable_OrderBy`, {
        data: {
          items: "f_defect_content,f_offsite_time,f_entry_status",
          tablename: `(SELECT *, ROW_NUMBER() OVER (PARTITION BY f_userinfoid ORDER BY f_offsite_time DESC) as rn FROM t_check_paper WHERE f_userinfoid = '${this.item.f_userinfo_id}' AND f_entry_status = '入户' ) a `,
          condition: `a.rn = 1`,
          orderitem: "1"
        }
      }, { resolveMsg: null, rejectMsg: null })
      if (resp.data.length > 0){
        this.lastSafeData =  resp.data[0]
        const offsiteDate = new Date(resp.data[0].f_offsite_time)
        const now = new Date()
        const diffInMs = now.getTime() - offsiteDate.getTime()
        this.diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24))
      }
    },
    async getMeterData(){
      let resp = await new HttpResetClass().load('POST', `${this.$androidUtil.getProxyUrl()}/api/af-revenue/sql/sale_HandplanQuery?pageNo=1&pageSize=2`, {
        data: {
          condition: `f_userinfo_id = '${this.item.f_userinfo_id}'`,
        }
      }, { resolveMsg: null, rejectMsg: null })
      if (resp.data.length > 0){
        this.lastMeterData =  resp.data[0]
      }
    },
    getModel() {
      let http = new HttpResetClass()
      http.load('POST', `${this.$androidUtil.getProxyUrl()}/api/af-revenue/logic/getIotInfo`, {
        data: {
          f_userinfo_code: `${this.item.f_userinfo_code}`
        }
      }).then((res) => {
        this.tableAnomalyRecords = res.data
      })
    },
    async getRechargeData(){
      let resp = await new HttpResetClass().load('POST', `${this.$androidUtil.getProxyUrl()}/api/af-safecheck/sql/safe_singleTable_OrderBy?pageNo=1&pageSize=2`, {
        data: {
          items: "f_operate_date",
          tablename: `t_sellinggas a `,
          condition: `a.f_userinfo_id = '${this.item.f_userinfo_id}' and f_state = '有效'`,
          orderitem: "f_operate_date desc"
        }
      }, { resolveMsg: null, rejectMsg: null })
      if (resp.data.length > 0){
        const operate_date = new Date(resp.data[0].f_operate_date)
        const now = new Date()
        const diffInMs = now.getTime() - operate_date.getTime()
        this.rechargeDiffDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24))
      }
    },
  },
  ready () {
    this.meterDate.t_userfiles.f_cardmeternumber = this.item.f_cardmeternumber
    this.meterDate.t_userfiles.f_userfiles_id = this.item.f_userfiles_id
    this.meterDate.f_inputtor_id =  Vue.user.id //抄表员ID
    this.isMonthCheckPlan()
    this.getSafeData()
    if (this.item.f_meter_classify == '物联网表'){
      this.getMeterData()
      this.getModel()
    }
    if (this.item.f_meter_classify.includes('卡表')){
      this.getRechargeData()
    }
  },
  watch: {
    // 抄表类型变化
    'meterDate.f_meter_read_type': function (val) {
      // 当选择了日常抄表，则进行判断本月是否已经完成了月度抄表任务，如未完成则给出相应提示
      if (val=='日常抄表') {
        this.isMonthCheckPlan()
      }
    }
  }
}
</script>
<style>
.panel-self {
  border-radius: 5px;
  border: 1px solid #c5e1f7;
  background-color: #F2F6FA;
}

.text-left {
  text-align: left;
}

.font {
  font: 15px PingFang-SC-Medium;
  color: #333333;
}

.showIi {
  font: 14px PingFang-SC-Medium;
  color: #666666;
}

.info {
  margin-top: 15px;
  border-radius: 5px;
  background-color: #f3faff;
}

.btn-photo {
  border: 0;
  border-radius: 7px;
  background-color: #7dc1f4;
  font: 15px PingFang-SC-Bold;
  height: 20%;
}

.div-photo {
  width: auto;
  height: auto;
  /* margin-top: 10px; */
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.btn-voice {
  border-radius: 7px;
  border: 1px solid #dedede;
  background-color: #f5fbff;
  font: 15px PingFang-SC-Bold;
  color: #499edf;
}

.save-btn {
  width: 25%;
  background-color: #499edf;
  border-radius: 6px;
  color: #FFFFFF;
  font: 15px PingFang-SC-Bold;
}

.upload-btn {
  width: 25%;
  background-color: #ffffff;
  border: 1px solid #499edf;
  border-radius: 6px;
  color: #499edf;
  font: 15px PingFang-SC-Bold;
}

.repair-btn {
  width: 25%;
  border: 1px solid #499edf;
  border-radius: 6px;
  font: 15px PingFang-SC-Bold;
}

#el_ca_tx {
  width: 100%;
  margin: 5px;
}
</style>
