// 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"

Component({

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

  },

  /**
   * 组件的方法列表
   */
  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: Number(data?.overall || 0),
        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, park, tenement, meterId } = 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, 
          valley : valley ? Number(valley) : valley, 
        });
      if (code !== OK) {
        alertInfo(message)
        return
      }
      alertSuccess("解绑成功")
      this.triggerEvent("ok")
    }
  }
})