// pages/workBenchNew/components/createMeter/index.js
import dayjs from "../../../../utils/dayjs"
import { alertInfo, alertSuccess, loadingFunc } from "../../../../utils/index"
import { uploadInstallMeter } from "../../../../service/public"
import request from "../../../../utils/request"
import { installMeter } from "../../../../service/meter"
const { OK } = request

Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: "",
    area: "",
    placeholder: "",
    collections: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      time: dayjs().format("YYYY-MM-DD HH:mm:ss")
    })
  },
  onParkFocus(e) {
    this.setData({
      show: true,
      title: "园区",
      type: 'park'
    })
  },
  onMeterFocus(e) {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "电表",
      type: 'inventoryMeter'
    })
  },
  onBuildingFocus() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "建筑",
      type: 'building'
    })
  },
  clearImage() {
    this.setData({
      url: ""
    })
  },
  onMeterBoxFocus() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "电表箱",
      type: 'meterBox'
    })
  },
  onMeterTypeFocus() {
    this.setData({
      show: true,
      title: "电表类型",
      type: 'meterType'
    })
  },
  onBindCard() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "卡",
      type: 'card'
    })
  },
  onBindCollectionA() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "互感器A",
      type: 'collection',
      collection: "A"
    })
  },
  onBindCollectionB() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "互感器B",
      type: 'collection',
      collection: "B"
    })
  },
  onBindCollectionC() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "互感器C",
      type: 'collection',
      collection: "C"
    })
  },
  onBindCollector() {
    const { park } = this.data;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "采集器",
      type: 'collector',
    })
  },
  clearCollector() {
    this.setData({
      show: false,
      title: "",
      type: 'collector',
      collector: null,
      collectorName: null,
    })
  },
  uploadImage() {
    const that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: async function(res) {
        const path = res.tempFiles?.[0]?.tempFilePath.toLowerCase()
        if (!/(\.jpg|\.png|\.jpeg)$/.test(path)) {
          wx.showToast({
            title: '请上传jpg、png或jpeg格式的图片',
            icon: 'none',
          });
          return;
        }
        var tempFilePaths = path;
        loadingFunc(async () => {
          const { code, message, url } = await uploadInstallMeter(tempFilePaths)
          if (code !== OK) {
            alertError(message)
            return
          }
          that.setData({
            url: url
          })
        }) 
      }
    })
  },
  changeSn(e) {
    this.setData({
      sn: e.detail,
    })
  },
  clearData() {
    this.setData({
      tenement: null,
      tenementName: null,
      building: null,
      buildingName: null,
      meterBox: null,
      meterBoxName: null,
      meter: null,
      meterName: null,
      card: null,
      cardName: null,
      collectionA: null,
      collectionAName: null,
      collectionB: null,
      collectionBName: null,
      collectionB: null,
      collectionBName: null,
      address: null,
      sharp: null,
      peak: null,
      flat: null,
      valley: null,
      deepValley: null,
      area: null,
      collector: null,
      collectorName: null,
      collections: [],
    })
  },
  onConfirm(e) {
    console.log("e", e)
    const { type, data = {}, way } = e.detail;
    const {collection, park, meterType, tenement, tenementName, overall, sharp, flat, peak, valley, deepValley} = this.data;
    switch(type) {
      case "park":
        this.setData({
          park: data.id,
          parkName: data.name,
          selfManagement: data.selfManagement,
        })
        if (park !== data.id) {
          this.clearData()
        }
        break;
      case "tenement":
        this.setData({
          tenement: data.id,
          tenementName: data.name,
        })
        break;
        case "inventoryMeter":
          this.setData({
            meter: data.id,
            meterName: data?.sn,
          })
          break;
      case "building":
        this.setData({
          building: data.id,
          buildingName: data.name,
        });
        break;
      case "meterBox":
        this.setData({
          meterBox: data.id,
          meterBoxName: data.address,
        });
        break;
      case "tenement":
        this.setData({
          tenement: data.id,
          tenementName: data.name,
        })
        break;
      case "meterType":
        let newMeterData = {};
        if (way !== 0) {
          newMeterData = {
            tenement: null,
            tenementName: null,
            overall: null,
            sharp: null,
            peak: null,
            flat: null,
            valley: null,
            deepValley: null,
          }
        }
        this.setData({
          meterType: way,
          meterTypeName: data,
          ...newMeterData,
        });
        break;
        case "collector":
          this.setData({
            collector: data?.id,
            collectorName: `${data.collectorAddress}-${data.manufacturer}`,
          });
          break;
      case "meter":
        this.setData({
          meter: data.id,
          meterName: data.address,
        });
        break;
      case "card":
        this.setData({
          card: data.id,
          cardName: data.sim_number,
        });
        break;
      case "collection":
        const newCollects = this.data.collections;
        let newData = {}
        if (collection === "A") {
          newCollects[0] = data.id
          newData = {
            collectionA: data.id,
            collectionAName: `${data.transformerId}-倍率:${data.ratio}-${data.manufacturer}`,
            collectionARatio: data.ratio,
            collections: newCollects
          }
        }
        if (collection === "B") {
          newCollects[1] = data.id
          newData = {
            collectionB: data.id,
            collectionBName: `${data.transformerId}-倍率:${data.ratio}-${data.manufacturer}`,
            collectionBRatio: data.ratio,
            collections: newCollects
          }
        }
        if (collection === "C") {
          newCollects[2] = data.id
          newData = {
            collectionC: data.id,
            collectionCName: `${data.transformerId}-倍率:${data.ratio}-${data.manufacturer}`,
            collectionCRatio: data.ratio,
            collections: newCollects
          }
        }
        this.setData(newData);
        break;
    }
    this.onCancel();
  },
  clearCard() {
    this.setData({
      card: null,
      cardName: null,
    })
  },
  clearCollectionA() {
    const newCollects = this.data.collections;
    newCollects[0] = null;
    this.setData({
      collectionA: null,
      collectionAName: null,
      collections: newCollects,
    })
  },
  clearCollectionB() {
    const newCollects = this.data.collections;
    newCollects[1] = null;
    this.setData({
      collectionB: null,
      collectionBName: null,
      collections: newCollects,
    })
  },
  clearCollectionC() {
    const newCollects = this.data.collections;
    newCollects[2] = null;
    this.setData({
      collectionC: null,
      collectionCName: null,
      collections: newCollects,
    })
  },
  changeAddress(e) {
    this.setData({
      address: e.detail
    })
  },
  changeArea(e) {
    this.setData({
      area: e.detail
    })
  },
  changeOverall(e) {
    this.setData({
      overall: e.detail
    })
  },
  changeSharp(e) {
    this.setData({
      sharp: e.detail
    })
  },
  changePeak(e) {
    this.setData({
      peak: e.detail
    })
  },
  changeFlat(e) {
    this.setData({
      flat: e.detail
    })
  },
  changeValley(e) {
    this.setData({
      valley: e.detail
    })
  },
  changeDeepValley(e) {
    this.setData({
      deepValley: e.detail
    })
  },
  changeRatio(e) {
    this.setData({
      ratio: e.detail,
    })
  },
  onCancel() {
    this.setData({
      show: false,
      title: "",
      type: "",
    })
  },
  onTenementFocus(e) {
    const { park } = this.data;
    const that = this;
    if (!park) {
      alertInfo("请先选择园区")
      return;
    }
    this.setData({
      show: true,
      title: "商户",
      type: 'tenement'
    })
  },
  async handleSubmit() {
    const { 
      park, meter, address, building, meterBox, meterType,  
      ratio, area, card, collectionA, collectionB, collectionC,
      tenement, sharp, peak, flat, valley, deepValley, overall, url, sn, 
      collectionARatio, collectionBRatio, collectionCRatio, collector,
    } = this.data;
    if (!park || !(meter || sn) || !address || meterType == null || !building || !meterBox || ratio == null) {
      alertInfo("请填写必填项后保存")
      return;
    }
    if (
      (collectionA == collectionB && collectionA != null && collectionB != null) || 
      (collectionA == collectionC&& collectionA != null && collectionC != null) || 
      (collectionC == collectionB && collectionB != null && collectionC != null)
    ) {
      alertInfo("互感器不能重复选择")
      return;
    }
    if (
      (collectionARatio != collectionBRatio && collectionARatio != null && collectionBRatio != null) || 
      (collectionARatio != collectionCRatio&& collectionARatio != null && collectionCRatio != null) || 
      (collectionCRatio != collectionBRatio && collectionBRatio != null && collectionCRatio != null)
    ) {
      alertInfo("互感器倍率不一致")
      return;
    }
    const { code, data, message } = await installMeter({
      park, meterSn: meter, address, building, meterBox, meterType,  
      ratio, area, card, collectionA, collectionB, collectionC,
      tenement, 
      sharp: sharp === "" ? null : sharp, 
      peak: peak === "" ? null : peak, 
      flat: flat === "" ? null : flat, 
      valley: valley === "" ? null : valley, 
      overall: overall === "" ? null : overall, 
      deepValley: deepValley == "" ? null : deepValley,

      url, sn, collector
    })
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    alertSuccess("新增成功")
    this.setData({
      park: null,
      parkName: null,
    })
    this.clearData()
    wx.navigateTo({
      url: '/pages/workBenchTodoList/index',
    })
  },
  goback() {
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})