<template>
  <div id="unit" class="flex-row">
    <div class="basic-main">
      <div class="flex" v-if="!show">
        <criteria-paged :model="model" v-ref:paged>
          <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
            <div novalidate class="form-horizontal select-overspread container-fluid auto" partial
                 @keyup.enter="search()">
              <div class="row">
                <!-- 新增查询类型下拉选择框 -->
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">查询类型</label>
                  <v-select :value.sync="$parent.$parent.queryType"
                            :options="$parent.$parent.queryTypeOptions"
                            placeholder='请选择查询类型'
                            :value-single="true"
                            v-model="$parent.$parent.queryType"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">&emsp;&emsp;公司</label>
                  <right-tree @re-res="$parent.$parent.getorg"
                              :initresid='$parent.$parent.org'>
                  </right-tree>
                </div>
                <div class="col-sm-2 form-group" v-if="$parent.$parent.queryType === 'negative'">
                  <label for="startDate" class="font_normal_body">开始日期</label>
                  <datepicker id="start_Date" placeholder="开始日期" style="width:60%"
                              v-model="model.startDate"
                              :value.sync="model.startDate"
                              :format="'yyyy-MM-dd HH:mm:ss'"
                              :show-reset-button="true">
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group" v-if="$parent.$parent.queryType === 'negative'">
                  <label for="endDate" class="font_normal_body">结束日期</label>
                  <datepicker id="end_Date" placeholder="结束日期" style="width:60%"
                              v-model="model.endDate"
                              :value.sync="model.endDate"
                              :format="'yyyy-MM-dd HH:mm:ss'"
                              :show-reset-button="true">
                  </datepicker>
                </div>

                <div class="span" style="float:right;">
                  <button class="btn button_search" @click="search()">查询</button>
                  <button class="btn button_clear" @click="$parent.$parent.clear()">清空</button>
                  <export-excel :data="$parent.$parent.getCondition"
                                :field="$parent.$parent.getfield"
                                :footer="$parent.$parent.footer"
                                :header="$parent.$parent.other"
                                sqlurl="api/af-revenue/logic/openapi/exportfile"
                                :sql-name="$parent.$parent.sqlName"
                                :template-name="$parent.$parent.exportTemplateName"
                                :choose-col="true">
                  </export-excel>
                  <div style="float: right" class="button_spacing"
                       :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                       @click="$parent.$parent.hidden()">
                  </div>
                </div>
              </div>
              <div class="row" v-show="$parent.$parent.criteriaShow">
                <div class="col-sm-2  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 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"
                         condition="f_user_name 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">客户电话</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_user_phone"
                         condition="f_user_phone like '%{}%'" 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_meternumber"
                         condition="f_meternumber = '{}'" placeholder='表号'>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">客户类型</label>
                  <v-select :value.sync="model.f_user_type"
                            @change="$parent.$parent.userTypeChange()"
                            :options='$parent.$parent.usertypes'
                            placeholder='请选择'
                            v-model="model.f_user_type"
                            condition="f_user_type = '{}'"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">用气性质</label>
                  <v-select :value.sync="model.f_gasproperties"
                            v-model="model.f_gasproperties"
                            :options='$parent.$parent.gasproperties'
                            placeholder='请选择'
                            condition="f_gasproperties = '{}'"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">气表品牌</label>
                  <v-select :value.sync="model.f_meter_brand"
                            multiple
                            v-model="model.f_meter_brand"
                            :options='$parent.$parent.meterbrands'
                            placeholder='请选择'
                            condition="f_meter_brand in {}"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="f_user_usetype" class="font_normal_body ">用气类型</label>
                  <v-select :value.sync="model.f_user_usetype" :search="false"
                            @change="$parent.$parent.userUseTypeChange()"
                            v-model="model.f_user_usetype"
                            :options='$parent.$parent.userusetypes'
                            condition="f_user_usetype = '{}'"
                            placeholder='用气类型'
                            value-single="true"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="f_use_institution" class="font_normal_body">用气机构</label>
                  <v-select :value.sync="model.f_use_institution" :search="false"
                            @change="$parent.$parent.userUseInstitutionChange()"
                            v-model="model.f_use_institution"
                            :options='$parent.$parent.useinstitutions'
                            condition="f_use_institution = '{}'"
                            placeholder='用气机构'
                            value-single="true"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="f_user_usenature" class="font_normal_body ">使用性质</label>
                  <v-select :value.sync="model.f_user_usenature" :search="false"
                            v-model="model.f_user_usenature"
                            :options='$parent.$parent.userusenatures'
                            condition="f_user_usenature = '{}'"
                            placeholder='使用性质'
                            value-single="true"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group" v-if="$parent.$parent.queryType === 'lostContact'">
                  <label for="type" class="font_normal_body ">开户状态</label>
                  <v-select :value.sync="model.type" :search="false"
                            v-model="model.type"
                            :options='$parent.$parent.whetherCard'
                            condition="type = '{}'"
                            placeholder='开户状态'
                            value-single="true"
                            close-on-select>
                  </v-select>
                </div>
              </div>
            </div>
          </criteria>
          <data-grid :model="model" partial='list' class="list_area table_sy" :optional="true" v-ref:grid>
            <template partial='head'>
              <tr>
                <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>小区(单位名称)</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 v-show="$parent.$parent.$parent.queryType === 'negative'">
                  <nobr>表上余额</nobr>
                </th>
                <th v-show="$parent.$parent.$parent.queryType === 'commandException'">
                  <nobr>指令状态</nobr>
                </th>
                <th v-show="$parent.$parent.$parent.queryType === 'lostContact'">
                  <nobr>开户状态</nobr>
                </th>
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align: center;">
                <nobr>{{ $index + 1 }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>
                  <span @click="$parent.$parent.$parent.showmsg(row)"><a>{{ row.f_userinfo_code }}</a></span>
                </nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_name }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_phone }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_address }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_meternumber }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_residential_area }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_type }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_gasproperties }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_meter_brand }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_usetype }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_use_institution }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_usenature }}</nobr>
              </td>
              <td v-show="$parent.$parent.$parent.queryType === 'negative'" style="text-align: center;">
                <nobr>{{ row.f_balance_amount }}</nobr>
              </td>
              <td v-show="$parent.$parent.$parent.queryType === 'commandException'" style="text-align: center;">
                <nobr>{{ row.f_instruct_state }}</nobr>
              </td>
              <td v-show="$parent.$parent.$parent.queryType === 'lostContact'" style="text-align: center;">
                <nobr>{{ row.type }}</nobr>
              </td>
            </template>
          </data-grid>
        </criteria-paged>
      </div>
      <div class="flex" v-if="show">
        <user-info-detail-manage-new
          :f_userinfo_id="rowdata.f_userinfo_id"
          @cancel-main="cancel">
        </user-info-detail-manage-new>
      </div>
    </div>
  </div>
</template>
<script>
/**
 * 统一异常查询组件（关阀/失联/负值）
 */
import plugin from 'system-clients/src/plugins/GetLoginInfoService'
import {PagedList} from 'vue-client'

let readySomething = async function (self) {
  await self.$MagLoadParams.loadParam()
  self.initParams()
}

export default {
  title: '异常查询',
  data() {
    return {
      queryType: 'negative',
      queryTypeOptions: [
        {label: '负值异常', value: 'negative'},
        {label: '关阀异常', value: 'closeValve'},
        {label: '失联异常', value: 'lostContact'},
        {label: '指令异常', value: 'commandException'}
      ],
      other: [],
      footer: [],
      org: [this.$login.f.orgid],
      criteriaShow: false,
      filialeNameStr: null,
      meterbrands: [],
      useinstitutions: [],
      userusenatures: [],
      filialeCodeStr: `and f_orgid = '${this.$login.f.orgid}'`,
      userid: this.$login.f.id,
      source: `tool.getFullTree(this.getRights().where(row.getType() == $organization$))`,
      getfield: {}, // 动态更新字段映射
      model: new PagedList('api/af-revenue/sql/manage_negativeAbnormalQuery', 50, {
        startDate: 'this.model.startDate',
        endDate: 'this.model.endDate'
      }),
      rows: null,
      show: false,
      rowdata: {},
      gasproperties: [],
      sumsmodel: {},
      config: {
        defaultPrint: ['f_userinfo_code', 'f_user_id']
      },
      defaultfield: [],
      _waitTimer: null,
      _waitAttempt: 0,
    }
  },
  watch: {
    sumsmodel: {
      handler: function (val) {
        this.getotherfooter()
      },
      deep: true
    },
    // 监听查询类型变化
    queryType: {
      handler: function (newVal) {
        this.initQueryConfig(newVal)
      }
    }
  },
  computed: {
    userusetypes () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('用气类型')]
    },
    whetherCard(){
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('开户状态')]
    },
    // 动态获取SQL名称
    sqlName() {
      const sqlNameMap = {
        closeValve: 'manage_closeValveAbnormalQuery',
        lostContact: 'manage_lostContactAbnormalQuery',
        negative: 'manage_negativeAbnormalQuery',
        commandException: 'manage_commandExceptionAbnormalQuery'
      }
      return sqlNameMap[this.queryType] || ''
    },
    // 动态获取导出模板名称
    exportTemplateName() {
      const templateNameMap = {
        closeValve: '关阀异常查询导出',
        lostContact: '失联异常查询导出',
        negative: '负值异常导出',
        commandException: '指令异常导出'
      }
      return templateNameMap[this.queryType] || ''
    },
    usertypes() {
      return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('用户类型')]
    },
    getCondition() {
      let result = {
        condition: '',
        diffDay: ' 1=1 ',
        startDate: this.$refs.paged.$refs.cri.model.startDate || '',
        endDate: this.$refs.paged.$refs.cri.model.endDate || ''
      }
      result.condition = this.$refs.paged.$refs.cri.condition + this.filialeCodeStr || this.filialeCodeStr

      return result
    }
  },
  ready() {
    // 初始化默认查询配置
    this.waitForChild(() => {
      this.initQueryConfig(this.queryType)
      if (this.$refs.paged.$refs.cri.model) {
        this.$refs.paged.$refs.cri.model.startDate = this.$login.toStandardDateString() + ' 00:00:00'
        this.$refs.paged.$refs.cri.model.endDate = this.$login.toStandardDateString() + ' 23:59:59'
      }
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
      // 添加回车键监听
      document.addEventListener('keyup', this.handleKeyUp)
    })
  },
  methods: {
    waitForChild(callback) {
      // 如果组件已销毁，停止等待
      if (this._isDestroyed) return;

      // 检查子组件是否就绪
      if (this.$refs.paged && this.$refs.paged.$refs.cri) {
        // 就绪，执行回调
        callback();
      } else {
        // 未就绪，继续轮询（最多尝试 100 次，约 2 秒）
        if (this._waitAttempt > 100) {
          console.error('子组件加载超时');
          this.$message.error('组件加载失败，请刷新页面');
          return;
        }
        this._waitAttempt++;
        this._waitTimer = setTimeout(() => {
          this.waitForChild(callback);
        }, 20);
      }
    },
    userUseInstitutionChange () {
      this.userusenatures = []
      this.$refs.paged.$refs.cri.model.f_user_usenature = ''
      if (this.$refs.paged.$refs.cri.model.f_use_institution) {
        let str = this.$refs.paged.$refs.cri.model.f_use_institution + '使用性质'
        this.userusenatures = this.$appdata.getParam(str)
      }
    },
    userUseTypeChange () {
      this.useinstitutions = []
      this.$refs.paged.$refs.cri.model.f_use_institution = ''
      if (this.$refs.paged.$refs.cri.model.f_user_usetype) {
        let str = this.$refs.paged.$refs.cri.model.f_user_usetype + '机构'
        this.useinstitutions = this.$appdata.getParam(str)
      }
    },
    // 初始化查询配置
    initQueryConfig(queryType) {
      // 字段映射配置
      const fieldConfigMap = {
        closeValve: {
          'f_userinfo_code': '客户编号',
          'f_user_name': '客户名称',
          'f_user_phone': '客户电话',
          'f_address': '客户地址',
          'f_meternumber': '表号',
          'f_residential_area': '小区(单位名称)',
          'f_user_type': '客户类型',
          'f_gasproperties': '用气性质',
          'f_meter_brand': '气表品牌',
          'f_user_usetype': '用气类型',
          'f_use_institution': '用气机构',
          'f_user_usenature': '使用性质'
        },
        lostContact: {
          'f_userinfo_code': '客户编号',
          'f_user_name': '客户名称',
          'f_user_phone': '客户电话',
          'f_address': '客户地址',
          'f_meternumber': '表号',
          'f_residential_area': '小区(单位名称)',
          'f_user_type': '客户类型',
          'f_gasproperties': '用气性质',
          'f_meter_brand': '气表品牌',
          'f_user_usetype': '用气类型',
          'f_use_institution': '用气机构',
          'f_user_usenature': '使用性质',
          'type': '开户状态'
        },
        negative: {
          'f_userinfo_code': '客户编号',
          'f_user_name': '客户名称',
          'f_user_phone': '客户电话',
          'f_address': '客户地址',
          'f_meternumber': '表号',
          'f_residential_area': '小区(单位名称)',
          'f_user_type': '客户类型',
          'f_gasproperties': '用气性质',
          'f_meter_brand': '气表品牌',
          'f_balance_amount': '表上余额',
          'f_user_usetype': '用气类型',
          'f_use_institution': '用气机构',
          'f_user_usenature': '使用性质'
        },
        commandException: {
          'f_userinfo_code': '客户编号',
          'f_user_name': '客户名称',
          'f_user_phone': '客户电话',
          'f_address': '客户地址',
          'f_meternumber': '表号',
          'f_residential_area': '小区(单位名称)',
          'f_user_type': '客户类型',
          'f_gasproperties': '用气性质',
          'f_meter_brand': '气表品牌',
          'f_instruct_state': '指令状态',
          'f_user_usetype': '用气类型',
          'f_use_institution': '用气机构',
          'f_user_usenature': '使用性质'
        }
      }

      // 更新字段映射
      this.getfield = fieldConfigMap[queryType] || fieldConfigMap.closeValve

      // 初始化PagedList
      const apiUrlMap = {
        closeValve: 'api/af-revenue/sql/manage_closeValveAbnormalQuery',
        lostContact: 'api/af-revenue/sql/manage_lostContactAbnormalQuery',
        negative: 'api/af-revenue/sql/manage_negativeAbnormalQuery',
        commandException: 'api/af-revenue/sql/manage_commandExceptionAbnormalQuery'
      }
      const apiUrl = apiUrlMap[queryType] || apiUrlMap.closeValve

      console.log('最终查询的apiUrl', apiUrl)
      this.model.url = apiUrl
      this.clear()
      // 重新初始化模型后触发查询
      this.search()
    },
    initParams() {
      // 初始化气表品牌
      let brandArr = []
      this.$MagGetSaleParam.getGasbrand().forEach((item) => {
        if ( item.value.f_meter_type === '物联网表') {
          let temp = {}
          temp.label = item.label
          temp.value = item.value.f_meter_brand
          brandArr.push(temp)
        }
      })
      this.meterbrands = [{label: '全部', value: ''}, ...brandArr]
      //初始化气表价格
      this.prices = this.$MagGetSaleParam.getPrices();
    },
    // 处理回车键查询
    handleKeyUp(e) {
      if (e.key === 'Enter') {
        this.search()
      }
    },
    userTypeChange() {
      this.gasproperties = []
      if (this.$refs.paged.$refs.cri.model) {
        this.$refs.paged.$refs.cri.model.f_gasproperties = ''
        this.gasproperties = this.$appdata.getParam(this.$refs.paged.$refs.cri.model.f_user_type[0])
      } else {
        this.gasproperties = [{label: '全部', value: ''}]
      }
    },
    getotherfooter() {
      this.other = []
      this.footer = []
      let otherInData = []
      otherInData.push(`导出时间: ${this.$login.toStandardTimeString()}`)
      let footerData = []
      let exportfield = this.getfield
      footerData.push('合计')
      let self = this
      for (var field in self.sumsmodel) {
        footerData.push(`${exportfield[field]}合计:${self.sumsmodel[field]}`)
      }
      this.footer.push(footerData)
      this.other.push(otherInData)
    },
    getorg(obj) {
      if (obj.resids.length > 0) {
        this.filialeCodeStr = ' and f_orgid in ' + plugin.convertToIn(obj.resids)
      } else {
        this.filialeCodeStr = ' and f_orgid = ' + this.$login.f.orgid
      }
    },
    cancel() {
      this.show = false
    },
    showmsg(obj) {
      this.rowdata = obj
      this.show = true
    },
    search() {
      if (!this.queryType) {
        this.$message.warning('请先选择查询类型')
        return
      }
      this.$refs.paged.$refs.cri.search()
    },
    selfSearch(args) {
      args.condition = args.condition + ` ${this.filialeCodeStr}`
      this.model.search(args.condition, args.model)
    },
    hidden() {
      this.criteriaShow = !this.criteriaShow
    },
    clear() {
      if (this.$refs.paged.$refs.cri.model) {
        Object.keys(this.$refs.paged.$refs.cri.model).forEach((key) => {
          if (key != 'startDate' && key != 'endDate') {
            this.$refs.paged.$refs.cri.model[key] = []
          }
        })
        this.$refs.paged.$refs.cri.model.startDate = this.$login.toStandardDateString() + ' 00:00:00'
        this.$refs.paged.$refs.cri.model.endDate = this.$login.toStandardDateString() + ' 23:59:59'
      }
    }
  },
  beforeDestroy() {
    // 清理定时器和事件监听
    if (this._waitTimer) {
      clearTimeout(this._waitTimer);
    }
    document.removeEventListener('keyup', this.handleKeyUp);
    this._isDestroyed = true; // 自定义标志，用于停止轮询
  }
}
</script>
<style media="screen">
.divtext {
  min-width: 50px;
  max-width: 200px;
  border: 1px solid green;
  display: inline-block;
}
</style>
