// pages/workBench/components/tenement/components/bindMeter/index.js

import { unbindMeter, } from "../../../../../../service/tenement"
import request from "../../../../../../utils/request"
import { alertInfo, alertSuccess } from "../../../../../../utils/index";
const { OK } = request
import { getWorkMeterDetail } from "../../../../../../service/meter"
import dayjs from "../../../../../../utils/dayjs"

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    tenement: String,
    park: String,
    tenementName: String,
    meterId: String,
    meterAddress: String,
    visible:Boolean,
  },
  observers: {
    "meterId": function(newValue) {
      this.getMeterDetail(newValue)
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    dateTimeShow: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onMeterFocus(e) {
      const { park } = this.data;
      if (!park) {
        alertInfo("请先选择园区")
        return;
      }
      this.setData({
        show: true,
        title: "电表",
        type: 'meter'
      })
    },
    async getMeterDetail(id) {
      const { code, message, data } = await getWorkMeterDetail(id)
      if (code !== OK) {
        alertInfo(message)
        return;
      }
      this.setData({
        overall: data?.overall ? Number(data?.overall || 0) : null,
        critical: data?.overall ? Number(data?.sharp || 0) : null,
        peak: data?.overall ? Number(data?.peak || 0) : null,
        flat: data?.overall ? Number(data?.flat || 0) : null,
        valley: data?.overall ? Number(data?.valley || 0) : null,
        deepValley: data?.deepValley ? Number(data?.deepValley || 0) : null,
        meter04kvType: data?.meter04kvType,
        status: data?.breakType ? '合闸' : "分闸"
      })
    },
    onClose() {
      this.triggerEvent("close")
    },
    onChange(e) {
      const { name } = e.currentTarget.dataset;
      this.setData({
        [name]: e.detail
      })
    },
    async onSubmit() {
      const { overall, critical, peak, valley, deepValley, park, tenement, meterId,readAt, flat } = this.data;
      const { code, message, } = await unbindMeter(
        park, 
        tenement, 
        meterId, 
        { 
          overall:overall? Number(overall) : overall, 
          critical : critical ? Number(critical) : critical, 
          peak: peak ? Number(peak) : peak, 
          flat: flat ? Number(flat) : flat,
          valley : valley ? Number(valley) : valley, 
          deepValley: deepValley ? Number(deepValley) : deepValley, 
          readAt: readAt || dayjs().format('YYYY-MM-DD HH:mm:ss') 
        });
      if (code !== OK) {
        alertInfo(message)
        return
      }
      alertSuccess("解绑成功")
      this.triggerEvent("ok")
    },
    dateTimeConfirm(e) {
      this.setData({ readAt: e.detail.time, dateTimeShow: false })
    },
    dateTimeCancal(e) {
      this.setData({ dateTimeShow: false })
    },
    onTimeFocus() {
      this.setData({ dateTimeShow: true })
    }
  }
})