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

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

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    meterInfo: Object,
    showLeft: Boolean,
    showRight: Boolean,
    routeId: String, 
    disabled: Boolean,
  },
  observers: {
    "routeId": function(newValue) {
      if (!newValue) {
        return;
      }
      this.checkFinish(newValue)
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    currentNumber: null,
    diff: "-"
  },
  lifetimes: {
    attached() {
      
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {

    handlePrev() {
      this.triggerEvent("prev")
    },
    handleNext() {
      this.triggerEvent("next")
    },
    onChange(e) {
      this.setData({
        currentNumber: e.detail,
        calcNumber: isNaN(Number(e.detail)) ? 0 : Number(e.detail),
        diff: isNaN(Number(e.detail)) ? "-" : (Number(e.detail) - this.data.meterInfo?.overall).toFixed(2)
      })
    },
    handleClear() {
      this.setData({
        currentNumber: null,
      })
    },
    async changeEndStatus() {
      const { routeId: id } = this.data;
      const { code, message } = await changeMeterRouteStatus({ id, status: 0 })
      if (code !== OK) {
        alertError(message)
        return
      }
      alertSuccess("操作成功")
      wx.navigateBack()
    },
    onPhotoFinish(e) {
      const { number, success, url } = e.detail;
      const { meterInfo } = this.data;
      if (success) {
        this.setData({ 
          currentNumber: `${Number(number)}`,  
          calcNumber: isNaN(Number(number)) ? 0 : Number(number),
          diff: isNaN(Number(number)) ? "-" : (Number(number || 0) - Number(meterInfo.overall)).toFixed(2),
          url,
        })
        alertSuccess("获取成功")
      } else {
        alertInfo("未能识别数字")
      }
    },
    async onSubmit() {
      const { meterInfo, currentNumber, routeId, url } = this.data;
      const { parkId, id } = meterInfo;
      const { code, message } = await createReading(parkId, id, routeId, {
        overall: `${currentNumber}`,
        flat: `${currentNumber}`,
        readAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        source: 1,
        url
      })
      if (code !== OK) {
        alertError(message)
        return
      }
      this.setData({
        currentNumber: null,
        calcNumber: null,
        diff: "-"
      })
      alertSuccess("录入成功")
      const that = this;
      that.triggerEvent("onSubmit")
      setTimeout(async () => {
        const isFinished = await that.checkFinish()
        if (isFinished) {
          
          wx.showModal({
            title: '提示',
            content: '所有电表都已抄完，是否返回？',
            complete: async (res) => {
              if (res.cancel) {
                
              }
          
              if (res.confirm) {
                // await that.changeEndStatus()
                wx.navigateBack()
                // const pages = getCurrentPages();
                // const prevPage = pages[pages.length - 2];
                // if (prevPage.init){
                //   prevPage.init()
                // }
              }
            }
          })
        } else {
          that.handleNext()
          that.handleClear()
        }
      }, 300)

    },
    async checkFinish(id) {
      const { code, message, data, num } = await checkReadingFinish(id || this.data.routeId);
      if (code !== OK) {
        alertError(message)
        return;
      }
      this.triggerEvent("finishNumber", num)
      return data;
    },
    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 - meterInfo.overall) {
              wx.showModal({
                title: '提示',
                content: '本次用电量已抄过历史平均水平的100%，是否确认录入？',
                complete: (res) => {
                  if (res.cancel) {
                    
                  }
              
                  if (res.confirm) {
                    that.onSubmit()
                  }
                }
              })
            } else {
              that.onSubmit()
            }
          }
        }
      })
      
    }
  }
})