<template>
  <div>
    <a-drawer
      id="agencyManageDetail"
      title="用户详情信息"
      placement="right"
      :body-style="{padding:0}"
      :destroy-on-close="true"
      :z-index="200"
      width="85vw"
      :closable="false"
      :visible="userInfoDetailVisible"
      @close="onClose">
      <a-spin :spinning="detailLoading" tip="加载中..." style="min-height: 200px; display: block;">
      <a-page-header v-if="userInfoDetailVisible && userInfo" :title="`用户编号：${ userInfo ? userInfo.f_userinfo_code : '' }`">
        <x-descriptions
          :title="null"
          :content="userInfo"
          serviceName="af-revenue"
          :getRealData="true"
          :column="4"
          config-name="User_Info_Desc_Config">
          <template #addonAfter>
            <div style="text-align: right">
              <a-statistic title="用户状态" :value="userInfo.f_user_state || 0"/>
              <a-statistic title="表具状态" :precision="0" :value="userInfo.f_table_state || 0"/>
            </div>
          </template>
        </x-descriptions>
        <user-info-detail-query-tabs :userInfo="userInfo"/>
        <template #extra>
          <a-button type="primary" v-if="openUserBtnShow" @click="openUser">开户</a-button>
          <a-button type="primary" v-if="valveBtnShow" @click="valvecontrol">开关阀</a-button>
          <a-button type="dashed" @click="refresh">刷新</a-button>
        </template>
      </a-page-header>
      </a-spin>
    </a-drawer>
    <!-- 阀控管理弹框 -->
    <a-modal
      title="阀控管理"
      :visible="valve"
      :width="600"
      @cancel="closeValveModal"
      :body-style="{ padding: '24px' }"
    >
      <!-- 阀控状态选择 -->
      <div style="margin-bottom: 16px;">
        <label style="display: block; font-size: 14px; color: #555; margin-bottom: 8px;">阀控状态</label>
        <a-select
          v-model="selectedOption"
          style="width: 100%;"
          placeholder="请选择"
        >
          <a-select-option v-for="item in networkValveOptions" :value="item" :key="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </div>

      <!-- 操作原因输入框 -->
      <div style="margin-bottom: 16px;">
        <label
          style="display: block; font-size: 14px; color: #555; margin-bottom: 8px;"
          class="ant-form-item-required"
        >
          操作原因
        </label>
        <a-textarea
          v-model="operateReason"
          placeholder="请填写操作原因"
          :rows="2"
          style="width: 100%;"
          :class="{ 'error-border': operateReasonError }"
          @blur="checkOperateReason"
        />
        <div v-if="operateReasonError" style="color: red; margin-top: 8px;">
          请填写操作原因
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div style="display: flex; justify-content: flex-end; align-items: center;">
          <!-- 右侧开阀和关阀按钮 -->
          <div>
            <a-button
              type="primary"
              :disabled="!operateReason"
              @click="valveoperate(true, 1)"
              style="border-radius: 4px; margin-right: 8px;"
            >
              开阀
            </a-button>
            <a-button
              type="primary"
              :disabled="!operateReason"
              @click="valveoperate(false, 1)"
              style="border-radius: 4px;"
            >
              关阀
            </a-button>
          </div>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import XDescriptions from '@vue2-client/base-client/components/common/XDescriptions/XDescriptions.vue'
import {mapState} from 'vuex'
import {runLogic} from '@vue2-client/services/api/common'
import userInfoDetailQueryTabs from '@vue2-client/pages/userInfoDetailManage/userInfoDetailQueryTabs'
import Vue from 'vue'

export default {
  name: 'UserInfoDetailManage',
  components: {
    XDescriptions,
    userInfoDetailQueryTabs
  },
  data () {
    return {
      userInfo: undefined,
      userInfoDetailVisible: false,
      openUserBtnShow: false,
      valveBtnShow: false,
      valve: false,
      networkValveOptions: [
        '手动',
        '自动',
        '1小时后自动',
        '3小时后自动',
        '6小时后自动',
        '12小时后自动'
      ],
      selectedOption: '手动',
      operateReason: '',
      operateReasonError: false,
      detailLoading: false
    }
  },
  watch: {
    userInfo: {
      handler (userInfo) {
        if (userInfo) {
          const meterType = userInfo.f_meter_type || ''
          this.openUserBtnShow = meterType.includes('物联网表')
          this.valveBtnShow = meterType.includes('物联网表') && userInfo.f_user_state !== '停用'
        } else {
          this.openUserBtnShow = false
          this.valveBtnShow = false
        }
      },
      deep: true
    }
  },
  methods: {
    checkOperateReason () {
      if (this.operateReason.trim() === '') {
        this.operateReasonError = true
      } else {
        this.operateReasonError = false
      }
    },
    async fetchUserDetail (userInfo = this.userInfo) {
      if (!userInfo) return
      this.detailLoading = true
      try {
        const detail = await runLogic('getUserInfoDetailV4', { ...userInfo }, 'af-revenue')
        this.userInfo = { ...detail }
      } catch (e) {
        this.$message.error(e.message || '加载用户详情失败')
      } finally {
        this.detailLoading = false
      }
    },
    refresh () {
      return this.fetchUserDetail()
    },
    openUser () {
      this.$confirm({
        title: '开户确认',
        content: '是否需要给用户进行开户?',
        onOk: () => {
          const data = {
            f_userfiles_id: this.userInfo.f_userfiles_id
          }
          runLogic('StartUp', data, 'af-revenue').then(res => {
            this.$message.success('开户成功')
          })
        }
      })
    },
    // 阀控管理
    valvecontrol () {
      if (this.$login.r.includes('开关阀权限')) {
        this.valve = true
      } else {
        this.$message.error('您没有【开关阀权限】,请联系管理员！！')
      }
    },
    closeValveModal () {
      this.valve = false
      this.selectedOption = '手动'
      this.operateReason = ''
      this.operateReasonError = false
    },
    async init (user) {
      this.operateReasonError = false
      this.userInfoDetailVisible = true
      this.userInfo = undefined
      await this.fetchUserDetail(user)
    },
    onClose () {
      this.userInfoDetailVisible = false
      this.$emit('close')
    },
    // 开关阀操作
    async valveoperate (oper, value) {
      const msg = oper ? '开阀' : '关阀'
      let delaySeconds = 0 // 初始化 delaySeconds 变量
      const currentTime = new Date() // 获取当前时间
      const adjustedTime = new Date(currentTime) // 创建一个新的 Date 对象用于计算延迟后的时间

      const beijingTime = new Date(currentTime.getTime() + 8 * 60 * 60 * 1000)
      const formattedBeijingTime = beijingTime.toISOString().slice(0, 19).replace('T', ' ')

      const datas = {
        instructType: '阀门控制',
        instructTitle: `手动${msg}`,
        condition: `t_userfiles.f_userfiles_id='${this.userInfo.f_userfiles_id}'`,
        meterBrandName: this.userInfo.f_alias,
        f_instruct_state: '待发送',
        inputtor: Vue.$login.f.name,
        inputtorid: Vue.$login.f.id,
        reasonInfo: this.operateReason,
        meternumberf: this.userInfo.f_meternumber,
        contentData: { isOpen: oper ? 1 : 0 },
        auto_adjust_option: this.selectedOption,
        delaySeconds: delaySeconds,
        executeDelayedOperation: true,
        f_timestamp: formattedBeijingTime, // 使用北京时间
        f_userfiles_id: this.userInfo.f_userfiles_id,
        f_userinfo_id: this.userInfo.f_userinfo_id
      }
      console.log('看看datas', datas)
      const _this = this
      // 计算延迟时间
      switch (_this.selectedOption) {
        case '1小时后自动':
          delaySeconds = 3600 // 1小时 = 3600秒
          break
        case '3小时后自动':
          delaySeconds = 10800 // 3小时 = 10800秒
          break
        case '6小时后自动':
          delaySeconds = 21600 // 6小时 = 21600秒
          break
        case '12小时后自动':
          delaySeconds = 43200 // 12小时 = 43200秒
          break
        default:
          delaySeconds = 0
      }

      adjustedTime.setSeconds(adjustedTime.getSeconds() + delaySeconds)
      const adjustedBeijingTime = new Date(adjustedTime.getTime() + 8 * 60 * 60 * 1000)
      const formattedAdjustedBeijingTime = adjustedBeijingTime.toISOString().slice(0, 19).replace('T', ' ')

      // 更新 datas 对象
      datas.delaySeconds = delaySeconds
      datas.f_current_timestamp = formattedAdjustedBeijingTime // 使用延迟后的北京时间
      runLogic('iot_saveInstruct', datas, 'af-revenue').then(res => {
        _this.valve = false
        _this.operateReason = ''
        if (_this.selectedOption !== '手动') {
          const msg = _this.selectedOption !== '自动' ? `阀控状态将在${_this.selectedOption}后自动调整为【自动】` : `阀控状态自动调整为 【自动】`
          this.$message.success(msg)
          runLogic('iot_processDelayedOperations', datas, 'af-revenue').then(res => {
            this.$emit('refresh')
            console.log('延时操作逻辑已执行')
          })
        } else {
          this.$emit('refresh')
        }
        this.$message.success('操作成功')
      })
    }
  },
  created () {
  },
  mounted () {},
  computed: {
    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', { isMobile: 'isMobile' })
  }
}
</script>

<style scoped>
.error-border {
  border-color: red;
}
</style>
