<template>
  <div id="unit" class="flex-row three" v-show="listpage">
    <div class="binary-left" style="overflow: scroll;width:15%" >
      <mulitinfo :warninginfo="warningInfo" style="height:auto" @deal-msg="dealMsg" :data="row" :card-data="cardInfo" v-ref:info></mulitinfo>
    </div>
    <div class="binary-right" style="width:68%;overflow-y: scroll" >
      <div :style="{height:(row?'auto':'100%')}">
        <!--<div class="auto" v-if="sustainMoney != null">-->
          <!--<h2 style="margin-top: 10px">当前连续收款金额: {{sustainMoney}}</h2>-->
        <!--</div>-->
        <div>
          <charge-list :row="row" @select-oper="showWork" @dblclick="toBusiness" @deal-msg="dealMsg"
                       v-ref:list></charge-list>

          <div class="auto" style="margin-top: 1%;" v-if="row">
            <charge-oper :data.sync="row" :card-info="cardInfo" v-ref:oper></charge-oper>
          </div>
      </div>
      </div>
    </div>
    <div class="binary-right" style="width:22%" >
      <ul class="nav nav-pills span" style="height:auto;margin:8px 0px;padding:4px 0;border-bottom: 1px solid #e7e7e7;" class="nav nav-tabs" >
        <li ><a :style="selectFiled == '其他信息'?'color:#333333!important;':'color:#666666!important;'" :class="{'tel_voiceActive':selectFiled == '其他信息','tel_f_size':selectFiled != '其他信息'}" href="#" @click="setField('其他信息')">其他信息</a></li>
        <li ><a :style="selectFiled == '历史操作'?'color:#333333!important;':'color:#666666!important;'" :class="{'tel_voiceActive':selectFiled == '历史操作','tel_f_size':selectFiled != '历史操作'}" href="#" @click="setField('历史操作')">历史操作</a></li>
        <li v-if="row ?row.f_meter_type=='机表' : false"><a :style="selectFiled == '历史抄表'?'color:#333333!important;':'color:#666666!important;'" :class="{'tel_voiceActive':selectFiled == '历史抄表','tel_f_size':selectFiled != '历史抄表'}" href="#" @click="setField('历史抄表')">历史抄表</a></li>
      </ul>
      <div class="tab-content span" style="overflow-y: auto">
        <otherinfo v-show="worktype === '其他信息'" style="height:auto" @deal-msg="dealMsg" :data="row" :card-data="cardInfo" v-ref:info></otherinfo>
        <card-list v-show="worktype === '历史操作'" :btns="operatebtn" :f_orgid="f_orgid" :userinfoid="row ? row.f_userinfo_code : ''" @list-select-oper="recordCancel"
                   v-ref:card></card-list>
        <hand-list  v-if="worktype === '历史抄表'" :f_userfiles_id="row ? row.f_userfiles_id : ''" v-ref:hand></hand-list>
      </div>

    </div>

  </div>
  <div v-if="!listpage">
    <user-info-detail-manage-new parentname="charge-manage" :f_userfiles_id="rowData.f_userfiles_id" @cancel-main="cancel" @cancel-re="cancelAndRefresh"></user-info-detail-manage-new>
  </div>
  <div v-if="showModal">
    <charge-modal :warninginfo="warningInfo" :row="modalrow" :modal-show.sync="showModal" @close="close" @modalsuccess="modalsuccess"></charge-modal>
  </div>
</template>
<script>
  import ChargeOper from './ChargeOper'
  import {HttpResetClass} from "vue-client";

export default {
    title: '收费(综合)',
    components: { ChargeOper },
    data () {
      return {
        sustainMoney: null,
        // 页面开关
        listpage: true,
        f_orgid: '',
        row: null,
        cardInfo: null,
        warningInfo: null,
        modalrow: null,
        showModal: false,
        rowData: {},
        dibao_remind: this.$appdata.getSingleValue('低保快到期提醒') ? this.$appdata.getSingleValue('低保快到期提醒') : 0,
        clear_state: this.$appdata.getSingleValue('业务完成是否自动清条件') ? this.$appdata.getSingleValue('业务完成是否自动清条件') : '是',
        reSearchShowMsy: !!this.$appdata.getSingleValue('收费后验证'),
        reSearchShowBusiness: !!this.$appdata.getSingleValue('业务完成重新加载'),
        shouldNavigateToEvaluation: false, // 标记是否应该导航到评价页面
        activeBusiness: null, // 当前激活的业务
        show: [true],
        selectFiled: '其他信息',
        worktype: '其他信息',
        searchTime: 1000,
        interval: null
      }
    },
    destroyed () {
      if(this.$appdata.getSingleValue('磁条卡读卡间隔')) {
        clearInterval(this.interval)
      }
    },
    ready () {
        if(this.$appdata.getSingleValue('磁条卡读卡间隔')){
          this.searchTime = this.$appdata.getSingleValue('磁条卡读卡间隔')
          this.readCiTiaoCard()
        }
        this.setsustainMoney()
    },
    methods: {
      async readCiTiaoCard () {
        console.log('读磁条卡，开始，不停的循环')
        let data = {}
        let getUser = {data: []}
        let forgid = this.$login.convertToIn([this.$login.f.orgid])
        try {
          this.interval = setInterval(() => {
            // 1秒一轮回
            let http = new HttpResetClass()
            http.load('POST', 'http://127.0.0.1:8003/ReadCard_HEC', data, {
              resolveMsg: null,
              rejectMsg: null
            }).then(async res => {
              if (res.data.CardID !== '') {
                if (res.data.Err === null && res.data.Exception) {
                  this.$showAlert(res.data.Exception, 'danger', 2000)
                  // clearInterval(interval)
                } else {
                  if (res.data.Factory === 'CiTiao') {
                    // 获取用户信息
                    getUser = await this.$resetpost('rs/sql/sale_getUser', {
                      data: {
                        condition: `u.f_filialeid in ${forgid}  and gb.f_meter_type in ('机表','物联网表') and i.f_userinfo_code='${res.data.CardID}'`,
                        orderitem: `f_userinfo_id`
                      }
                    }, {resolveMsg: null, rejectMsg: '读卡失败'})
                    this.$refs.list.model.rows = getUser.data
                    if (!this.row || (this.row && this.row.f_userinfo_code != getUser.data[0].f_userinfo_code)) {
                      await this.toBusiness(getUser.data[0])
                    }
                  }
                }
              }
            })
          }, this.searchTime * 1000)
        } catch (error) {
          console.log('捕获到异常', error)
        }
      },
      setsustainMoney () {
        this.sustainMoney = window.localStorage.getItem('sustainMoney')
      },
      setField (type) {
        this.selectFiled = type
        this.worktype = type
      },
      async toBusiness (obj) {
        console.log('双击列表的时候传进来的数据：', obj)
        if (!(obj instanceof Event)) {
        // 对此数据进行验证
          if (await this.validateRow(obj)) {
            this.shouldNavigateToEvaluation = false
          // 获取未写卡或者写卡失败记录
            let getUnWriteSell = await this.$SqlService.singleTable('t_sellinggas', `f_state = '有效' and (f_write_card = '未写卡' or (f_write_card = '写卡失败' and f_operate_date >= DATEADD(HOUR, -3, GETDATE()))) and f_userfiles_id = '${obj.f_userfiles_id}'`)
            console.log('获取未写卡记录', getUnWriteSell)
            if (getUnWriteSell.data.length > 1) {
              this.$showAlert('此卡已缴费多次未写卡。请核实后处理！！', 'warning', 5000)
            } else {
              this.row = obj
              this.shouldNavigateToEvaluation = false
              this.row.unWriteSell = getUnWriteSell.data
              this.cardInfo = this.$refs.list.cardInfo
              this.$refs.list.criteriaShow = false
            // 将列表只显示该条数据
              this.$refs.list.refreshRow(obj)
            }
          }
        }
      },
      close () {
        this.showModal = false
        this.warningInfo = null
        this.clean()
        this.$refs.list.search()
        // this.$refs.card.search()
      },
      async validateRow (obj) {
        console.log('查看传进来的参数:', obj)
        this.warningInfo = await this.$resetpost('rs/logic/getWarningMsg',
          {data: {
            f_userfiles_id: obj.f_userfiles_id,
            f_userinfo_code: obj.f_userinfo_code,
            f_userinfo_id: obj.f_userinfo_id
          }
          }
          , {resolveMsg: '', rejectMsg: '获取提示失败'})
        if (this.warningInfo.data.warningNum > 0 && obj.f_user_state !== '预备') {
          this.modalrow = obj
          this.showModal = true
          return false
        } else {
          return true
        }
      },
      clean () {
        this.row = null
        this.cardInfo = null
      },
      clearCondition () {
        Object.keys(this.$refs.list.$refs.paged.$refs.cri.model).forEach((key) => {
          console.log('key', key)
          console.log('对应啥数据', this.$refs.list.$refs.paged.$refs.cri.model[key])
          this.$refs.list.$refs.paged.$refs.cri.model[key] = []
        })
        // console.log('清数据。。。', this.$refs.list.$refs.paged.$refs.grid.model.rows)
        // this.$set('$refs.list.$refs.paged.$refs.grid.model.rows', [])
      },
      dealMsg (obj) {
        console.log('==================obj', obj)
        this.listpage = false
        this.rowData = obj
      },
      cancel (obj) {
        this.listpage = true
      },
      cancelAndRefresh (obj) {
        this.listpage = true
        this.clean()
        this.clearCondition()
        this.$refs.list.searchNoData()
        this.$refs.card.search()
      },
      async modalsuccess (obj) {
        this.showModal = false
        let getUnWriteSell = await this.$SqlService.singleTable('t_sellinggas', `f_state = '有效' and (f_write_card = '未写卡' or (f_write_card = '写卡失败' and f_operate_date >= DATEADD(HOUR, -3, GETDATE()))) and f_userfiles_id = '${obj.f_userfiles_id}'`)
        console.log('获取未写卡记录', getUnWriteSell)
        if (getUnWriteSell.data.length > 1) {
          this.$showAlert('此卡已缴费多次未写卡。请核实后处理！！', 'warning', 5000)
        } else {
          this.$refs.list.criteriaShow = false
          this.row = obj
          this.row.unWriteSell = getUnWriteSell.data
          this.cardInfo = this.$refs.list.cardInfo
          this.$refs.list.criteriaShow = false
          // 将列表只显示该条数据
          await this.$refs.list.refreshRow(obj)
          // 如果应该导航到评价页面，则执行评价业务
          if (this.shouldNavigateToEvaluation && this.$refs.oper) {
            this.activeBusiness = '评价'
            this.$nextTick(() => {
              this.$refs.oper.business({name: '评价', value: {routeName: 'service-evaluation'}})
              // 执行完后清除标志
              this.shouldNavigateToEvaluation = false;
            }, 100)
          } else {
            // 清除标志（普通业务场景）
            this.shouldNavigateToEvaluation = false;
          }
          console.log('this.row', this.row)
        }
      },
      // 监听业务切换
      onBusinessChange(businessName) {
        this.activeBusiness = businessName
      },
      async serRow (obj, evaluationFlag = false) {
        // 设置标志
        this.shouldNavigateToEvaluation = evaluationFlag;

        let newdata = await this.$resetpost('rs/sql/sale_getUser', {
          data: {condition: `i.f_userinfo_code='${obj.f_userinfo_code}' and u.f_filialeid = '${obj.f_filialeid}'`, orderitem: `f_userinfo_id Desc`}
        }, {resolveMsg: null, rejectMsg: '获取用户信息失败'})
        await  this.toBusiness(newdata.data[0])
        // this.$refs.list.search()
        if(evaluationFlag){
          this.$refs.oper.business({name: '评价', value: {routeName: 'service-evaluation'}})
        }
      },
      hasEvaluatePermission (name) {
        if (!this.$login.r || !Array.isArray(this.$login.r)) {
          console.warn('权限列表不存在或不是数组')
          return false
        }
        const permissionName = `${name}评价权限`
        return this.$login.r.includes(permissionName)
      }
    },
    events: {
      'error' (name, row, res) {
        this.clean()
      },
      'row' (val) {

      },

      'success' (name, row, res) {
        this.setsustainMoney()
        // name === '发卡售气' ? this.$refs.list.toNext(this.index) : null
        if (name === '机表收费确认') {
          this.serRow(row)
          return
        }
        if (name === '卡表收费' && this.reSearchShowMsy) {
          this.$refs.list.$refs.paged.$refs.cri.$refs.readcard.readCard()
          this.$refs.oper.noButton = false
          return
        }
        if (name === '物联网收费' && this.reSearchShowMsy) {
          this.serRow(row)
          return
        }
        if (this.hasEvaluatePermission(name) && this.reSearchShowBusiness) {
          console.log('row', row)
          this.$refs.oper.noButton = false
          this.$showMessage('要进行业务评价吗？', ['confirm', 'cancel']).then((res) => {
            if(res !== 'confirm') {
              if (row) {
                this.serRow(row)
                this.activeBusiness = null
              } else {
                this.serRow(this.row)
              }
              return
            } else {
              if (row) {
                this.serRow(row,true)
              } else {
                this.serRow(this.row,true)
              }
            }
          })
          return
        }
        console.log('成功事件')
        this.clean()
        if (this.clear_state === '是') {
          this.clearCondition()
        }
        this.$refs.list.search()
        // this.clearCondition()
        // this.$refs.card.search()
        // this.$refs.info.$refs.recordstoryinfo.getdata()
      },
      'clean' (row) {
        // this.$refs.list.singleRefresh(row)
        this.clean()
      },
      'refresh' () {
        this.setsustainMoney()
        this.clean()
        this.clearCondition()
        this.$refs.list.searchNoData()
        this.$refs.card.search()
      },
      'resflushvalue' () {
        this.$refs.info.$refs.valueaddinfo.reflush()
      },
      'resflushrowdata' () {
        this.toBusiness(this.row)
      },
      'resflushdata' (data) {
        this.toBusiness(data)
      },
      'refreshrow' (val) {
        console.log(val)
        this.row = val
        this.$refs.list.refreshRow(val)
        // this.$refs.card.search()
      },
      'cancelclean' (row) {
        this.clean()
        this.$refs.list.searchNoData()
        // this.$refs.card.search()
      }
    },
    watch: {
      'row' () {
        // this.$refs.tab.$el.click()
      }
    }
  }
</script>
<style>
  .basic-main {
    width: 79%;
  }
  .tel_voiceActive{
    font-family: PingFang-SC-Bold;
    font-size: 16px;
    font-weight: normal!important;
    font-stretch: normal!important;
    line-height: 18px;
    letter-spacing: 0px;
    color: #333333!important;
    border-bottom: 3px solid #599fe5;
    padding:10px 10px!important;
  }
  .tel_f_size{
    font-family: PingFang-SC-Medium;
    font-size: 16px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 18px;
    letter-spacing: 0px;
    color: #666666!important;
    padding:10px 10px!important;
  }
</style>
