<template>
  <div class="auto">
    <validator name='v'>
      <form class="form-horizontal">
        <p class="bg-info text-center" style="padding: 8px;">销户信息</p>
        <div class="row" style="margin-top:10px;">
          <span class="col-sm-2 col-sm-offset-1"><strong>已选中户数: {{model.count}}</strong></span>
        </div>
        <div class="row" style="margin-top:10px;">
          <div  :class="[$v.f_meter_base.required ? 'has-error' : 'has-success']">
            <label for="f_meter_base" class="ch font_normal_body">&emsp;底数&emsp;</label>
            <input class="input_search" type="number" style="width:20%" v-model="model.f_meter_base" v-validate:f_meter_base='{required: true, dctest: [useraccount[0].f_meter_base, ">=" ]  }' placeholder="表底数">
            <p style="color:darkred" class="font_normal_body" v-if="parseFloat(model.f_meter_base) < parseFloat(useraccount[0].f_meter_base)">表底数为{{useraccount[0].f_meter_base}},本次录入的底数不能小于表底数</p>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <div  :class="[$v.f_reason.required ? 'has-error' : 'has-success']">
            <label for="f_reason" class=" font_normal_body">销户原因</label>
            <input class="input_search" style="width:80%" v-model="model.f_reason" v-validate:f_reason='{required: true }' rows="3" placeholder="请填写原因">
          </div>
        </div>
      </form>
      <upload :blodid="useraccount[0].f_userinfo_id"  isremark="true" fusetype="销户" v-ref:caneclfile></upload>

      <div style="text-align:right;height:auto;margin-top:30px;margin-right:50px;">
        <button class="button_search" @click="createHand()"  :disabled='!$v.valid'>确认</button>
        <button class="button_clear" @click="clean()">取消</button>
      </div>
    </validator>
  </div>
</template>
<script>
import Vue from 'vue'
import {HttpResetClass} from 'vue-client'

/**
*综合业务
表具停用组件
*/
export default {
  title: '批量销户',
  data () {
    return {
      config: {
        upload: false // 默认附件不必传
      },
      model: {
        count: 0,
        discount: 0,
        f_meter_base: null,
        f_reason: '',
        userinfo: {}
      },
      infoIds: []
    }
  },
  props: ['useraccount'],
  async ready () {
    await this.$getConfig(this, 'UserFiles')
    this.useraccount.forEach((item) => {
      if (item.f_user_state !== '销户') {
        this.model.count = this.model.count + 1
        this.model.userinfo = item
      } else if (item.f_user_state === '销户') {
        this.model.discount = this.model.discount + 1
      }
    })
  },
  // ready () {
  //   if(this.useraccount.length===1){
  //     // 单户销户
  //     if (this.useraccount[0].f_user_state === '正常') {
  //       this.model.count = 1
  //       this.model.userinfo = this.useraccount[0]
  //     }else{
  //       this.model.discount = 1
  //     }
  //   }else{
  //     console.log("!!!!!!批量销户")
  //     //批量销户
  //     this.useraccount.forEach((item) => {
  //       if (item.f_user_state === '正常') {
  //       this.model.count = this.model.count + 1
  //       this.model.userinfo.push(item)
  //       this.infoIds.push(item.f_userinfo_id)
  //     } else if (item.f_user_state = '销户') {
  //       this.model.discount = this.model.discount + 1
  //     }
  //   })
  //     console.log("!!!!!!传过来的数据组织一下",this.infoIds)
  //   }
  // },

  methods: {

    async createHand () {
      if (this.config.upload) {
        if (this.$refs.caneclfile.fileInfoData && this.$refs.caneclfile.fileInfoData.length > 0) {
          console.log(this.$refs.caneclfile.fileInfoData)
        } else {
          this.$showMessage(`请上传图片`)
          return
        }
      }
      if ((this.model.userinfo.f_meter_classify === '机表') && (parseFloat(this.model.f_meter_base) > parseFloat(this.useraccount[0].f_meter_base))) {
        this.$showMessage(`该用户表底数大于上次抄表底数，请确定是否继续生成欠费记录`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            this.saveHand()
          }
        })
      } else {
        await this.confirm()
      }
    },

    async saveHand () {
      let data = {
        downDate: this.$login.toStandardTimeString(),
        startDate: this.$login.toStandardDateString(),
        endDate: this.$login.toStandardDateString(),
        condition: `f_userfiles_id = '${this.useraccount[0].f_userfiles_id}'`,
        f_operator: this.$login.f.name,
        f_operatorid: this.$login.f.id,
        f_meternumber: this.useraccount[0].f_meternumber,
        f_userinfo_id: this.useraccount[0].f_userinfo_id,
        f_userfiles_id: this.useraccount[0].f_userfiles_id,
        f_serial_number: '',
        f_meter_classify: this.useraccount[0].f_meter_classify,
        f_meterbase: this.model.f_meter_base,
        f_meter_brand: this.useraccount[0].f_meter_brand,
        f_price_id: this.useraccount[0].f_price_id
      }
      await this.$resetpost('rs/logic/changeMeterHand', {data: data}, {resolveMsg: '生成欠费记录成功', rejectMsg: '生成欠费记录失败'})
      this.model.userinfo.version = this.model.userinfo.version + 1
      await this.confirm()
    },

    async confirm () {
      let http = new HttpResetClass()
      let owe = await http.load('POST', 'rs/sql/singleTable_OrderBy', {
        data: {
          items: 'f_whether_pay',
          tablename: 't_handplan',
          condition: ` f_userfiles_id  = '${this.useraccount[0].f_userfiles_id}' and  f_hand_state = '有效' and f_meter_state='已抄表' and f_whether_pay='否'`,
          orderitem: ' id desc'
        }
      }, {resolveMsg: null, rejectMsg: null}
      )
      console.log('获取到的欠费记录', owe)
      // 如果是机表/物联网表，验证是否有欠费

      if (owe.data.length > 0 && (!this.useraccount[0].f_meter_classify.includes('卡表'))) {
        this.$showAlert('该表有欠费，无法销户', 'warning', 3000)
        // this.$dispatch('button-specifies', {name:'机表收费', value: 'machine-charge'}, this.row)
      } else {
        await this.cancellation()
      }
    },
    async cancellation () {
      this.model.f_reality_count = this.model.count
      await this.$FileService.batchOperate(this.model, '销户').then((res) => {
        this.$dispatch('success')
      }).catch((error) => {
        if (error.state === 603) {
          this.$error('重复提交')
          return
        }
        this.$dispatch('error', '批量销户', this.row, error)
      })
    },
    // confirm () {
    //   this.model.f_reality_count = this.model.count
    //
    //   if(this.useraccount.length===1){
    //     this.$FileService.batchOperate(this.model, '销户').then((res) => {
    //       this.$dispatch('success')
    //   }).catch((error) => {
    //       if (error.state === 603) {
    //       this.$error('重复提交')
    //       return
    //     }
    //     this.$dispatch('error', '批量销户', this.row, error)
    //   })
    //   }else{
    //     console.log("点了confirm，this.infoIds!!!!!",this.infoIds)
    //     this.$FileService.batchOperate(this.model, '销户', this.infoIds).then((res) => {
    //       this.$emit('success')
    //     console.log("调用success了吗！！！！！！")
    //   }).catch((error) => {
    //       if (error.state === 603) {
    //       this.$error('重复提交')
    //       return
    //     }
    //     this.$dispatch('error', '批量销户', this.row, error)
    //   })
    //   }
    //
    // },
    //
    clean () {
      this.$info('取消操作')
      this.$dispatch('clean', '批量销户', this.row)
    }
  }
}
</script>

<style>
</style>
