// pages/writeReading/components/readingInfo/index.js

import { createReading } from "../../../../service/workBench"
import { alertError, alertInfo, alertSuccess } from "../../../../utils/index"
import request from "../../../../utils/request"
const { OK } = request

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    meterInfo: Object,
    showLeft: Boolean,
    showRight: Boolean,
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentNumber: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    jumpToHistory() {
      const { meterInfo } = this.data;
      wx.navigateTo({
        url: `/pages/readingHistory/index?meter=${meterInfo?.id}&park=${meterInfo?.parkId}`,
      })
    },
    handlePrev() {
      this.triggerEvent("prev")
    },
    handleNext() {
      this.triggerEvent("next")
    },
    onChange(e) {
      this.setData({
        currentNumber: e.detail ? Number(e.detail) : 0
      })
    },
    handleClear() {
      this.setData({
        currentNumber: null,
      })
    },
    async onSubmit() {
      const { meterInfo, currentNumber } = this.data;
      const { parkId, id } = meterInfo;
      const { code, message } = await createReading(parkId, id, {
        overall: `${currentNumber}`,
        flat: `${currentNumber}`
      })
      if (code !== OK) {
        alertError(message)
        return
      }
      alertSuccess("录入成功")
      this.handleNext()
      this.handleClear()
    },
    handleCreateReading() {
      const { meterInfo, currentNumber } = this.data;
      if (currentNumber == null || currentNumber == undefined) {
        alertInfo("请填写本次表字后保存")
        return;
      }
      const that = this;
      wx.showModal({
        title: '提示',
        content: '确定要录入吗？',
        complete: (res) => {
          if (res.cancel) {
            
          }
      
          if (res.confirm) {
            if (meterInfo.consumption < currentNumber) {
              wx.showModal({
                title: '提示',
                content: '本次用电量已抄过历史平均水平的100%，是否确认录入？',
                complete: (res) => {
                  if (res.cancel) {
                    
                  }
              
                  if (res.confirm) {
                    that.onSubmit()
                  }
                }
              })
            } else {
              that.onSubmit()
            }
          }
        }
      })
      
    }
  }
})