// pages/workBench/components/reading/index.js
import { getMeterReadingRouteList, changeMeterRouteStatus } from "../../../../service/workBench"
import { alertError, alertSuccess, loadingFunc } from "../../../../utils/index"
import request from "../../../../utils/request"
const { OK } = request

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    park: "",
    parkName: ""
  },
  lifetimes: {
    attached() {
      if (this.data.parkName) {
        this.init();
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onParkFocus(e) {
      this.setData({
        show: true,
        title: "园区",
        type: 'park'
      })
    },
    async init() {
      const { parkName, park } = this.data;
      const { code, message, data } = await getMeterReadingRouteList(parkName)
      if (code !== OK) {
        alertError(message)
        return
      }
      this.setData({
        list: data
      })
    },
    onConfirm(e) {
      const { data } = e.detail;
      const that = this;
      this.setData({
        parkName: data.name,
        park: data.id,
      }, () => {
        loadingFunc(async () => {
          await that.init();
        })
      })
      this.onConcal();
    },
    onConcal() {
      this.setData({
        show: false,
        title: "",
        type: "",
      })
    },
    jumpToReading(e) {
      const { id } = e.currentTarget.dataset;
      wx.navigateTo({
        url: `/pages/writeReading/index?id=${id}`,
      })
    },
    async changeStartStatus(e) {
      const that = this;
      const { id } = e.currentTarget.dataset;
      const { code, message } = await changeMeterRouteStatus({ id, status: 1 })
      if (code !== OK) {
        alertError(message)
        return
      }
      alertSuccess("操作成功")
      this.init()
      setTimeout(() => {
        that.jumpToReading({ currentTarget: { dataset: { id } } })
      }, 500)
    },
    async changeEndStatus(e) {
      const { id } = e.currentTarget.dataset;
      const { code, message } = await changeMeterRouteStatus({ id, status: 0 })
      if (code !== OK) {
        alertError(message)
        return
      }
      alertSuccess("操作成功")
      this.init()
    }
  }
})