var page_function = {
  components: {},
  data() {
    return {
      VarMenuPage: "chart_pie",
      VarMenu: "area",
      VarPageContainerCss: "padding:30px",

      deviceKey: null, //	Var_Config 設定檔 對應的key
      fromPage: null, //	從哪個頁面來的
      itemLabel: "區域", //類型
      itemType: null,
      search: {
        date: new Date(),
        year_month: new Date(),
        item: [],
        range: "day",
        id_list: [],
      },
      itemOptions: [],
      pieOptions: {
        title: {
          text: "指定比較",
          subtext: "當日總計",
          right: "10%",
          top: "10%",
          textStyle: {
            fontSize: 30,
            color: "#fff",  // 標題顏色設為白色
          },
          subtextStyle: {
            fontSize: 20,
            color: "#fff",  // 副標題顏色設為白色
          },
        },
        tooltip: {
          trigger: "item",
          textStyle: {
            fontSize: 20,
            color: "#fff",  // 提示文字顏色設為白色
          }
        },
        legend: {
          orient: "vertical",
          right: "27.5%",
          top: "25%",
          textStyle: {
            fontSize: 20,
            color: "#fff",  // 圖例文字顏色設為白色
          },
        },
        series: [
          {
            name: "區域",
            type: "pie",
            radius: "80%",
            center: ["35%", "50%"],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              fontSize: 20,
              color: "#fff",  // 圖表數據標籤設為白色
            }
          },
        ],
      },
      // specialId: { // 特殊處理id
      //   "656667": {
      //     "id_list": "65,66,67",
      //     "fomula": "65-(66+67)"
      //   },
      //   "2610": {
      //     "id_list": "26,10",
      //     "fomula": "26-10"
      //   },
      // },
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.MenuSetup.opened = false;
    this.VarMenuIsOverlay = false;
    this.initPage();
  },
  methods: {
    initPage() {
      // 載入url參數
      var that = this;
      let sp = new URLSearchParams(decodeURIComponent(window.location.search));
      this.deviceKey = sp.get("options");
      this.$set(this.WebSetup, "caption", this.deviceKey); // 頁面標題
      this.fromPage = sp.get("from_page");
      this.itemType = sp.get("item_type");
      // 項目類型
      if (this.fromPage.includes("power")) {
        this.itemLabel = "電錶";
      } else if (this.fromPage.includes("steam")) {
        this.itemLabel = "區域";
      } else if (this.fromPage.includes("gas")) {
        this.itemLabel = "區域";
      } else if (this.fromPage.includes("water")) {
        this.itemLabel = "水錶";
      }
      // console.log(device_item);
      if (device_item[this.itemType][this.deviceKey]) {
        this.itemOptions = device_item[this.itemType][this.deviceKey]["options"];
        _.each(this.itemOptions, (op)=> {
          let temp_id_list = [];
          if (!isNaN(Number(op.value, 10))) {
            temp_id_list.push(op.value);
          } else {
            that.get_options_id(temp_id_list, op.label, that.itemType);
          }
          op.id_list = temp_id_list.join(",");
        });
        // 全選
        this.search.item = _.map(this.itemOptions, "value");
        this.searchData();
      } else {
        this.FnNotify("查無設定資料", "error");
      }
    },
    async searchData() {
      this.search.id_list = [];
      this.itemOptions.forEach((el) => {
        if (this.search.item.includes(el.value)) {
          if (el.id_list.trim() != "") {
            // if(this.specialId.hasOwnProperty(el.id_list)) {
            //   // 特殊id，需要經過計算
            //   this.search.id_list.push(this.specialId[el.id_list]['id_list']);
            // } else {
            // }
              this.search.id_list.push(el.id_list);
            
          }
        }
      });
      // await this.FnAlert(JSON.stringify(this.search.id_list))
      var params = {
        Action: "PieData",
        Datas: {
          date: this.search.date,
          year_month: moment(this.search.year_month).format("YYYY-MM"),
          range: this.search.range,
          id_list: this.search.id_list,
          data_group: this.itemType,
        },
      };
      // 設定標題
      var searchDate = null;
      if (this.search.range == "day") {
        searchDate = moment(this.search.date).format("YYYY-MM-DD");
      } else if (this.search.range == "month") {
        searchDate = moment(this.search.year_month).format("YYYY-MM");
      }
      var titleStr = "";
      var subTitleStr = "";
      var unit = energy_unit[this.itemType];
      if (this.fromPage.includes("power")) {
        titleStr = "電錶用電";
        subTitleStr = "用電";
      } else if (this.fromPage.includes("steam")) {
        titleStr = "區域蒸汽用量";
        subTitleStr = "用蒸汽";
      } else if (this.fromPage.includes("gas")) {
        titleStr = "區域瓦斯用量";
        subTitleStr = "用瓦斯";
      } else if (this.fromPage.includes("water")) {
        titleStr = "區域水錶用量";
        subTitleStr = "用水";
      }
      this.pieOptions.title.text = `[${searchDate}]指定${titleStr}比較`;

      // 設定項目
      var selectedOp = _.map(
        _.filter(this.itemOptions, (op) => this.search.item.includes(op.value)),
        (d) => {
          return { name: d.label, value: 0, id: d.value, id_list: d.id_list.split(",") };
        }
      );
      this.pieOptions.series[0].data = selectedOp;
      var totalAmount = 0;
      await this.FnWebAPIGet(params)
      .then((res) => {
        var resData = res.data.data;
        if(resData.length > 0) {
          _.each(this.pieOptions.series[0].data, (d)=> {
            var usedVal = 0;
            _.each(resData, (rd)=> {
              if(d.id_list.includes(rd.ID.toString())) {
                usedVal += Number(rd[`dosage`]);
              }
            });
            // 特殊id計算用量
            // if (this.specialId.hasOwnProperty(d.id)) {
            //   var fomula = this.specialId[d.id]['fomula'];
            //   var fomula_temp = fomula;
            //   _.each(fomula.match(/\d+/g), (n)=> {
            //     var val = 0;
            //     var foundId = _.find(resData, {"ID": n});
            //     if(foundId) {
            //       val = foundId.dosage;
            //     }
            //     fomula_temp = fomula_temp.replaceAll(n,val)
            //   });
            //   usedVal = eval(fomula_temp);
            // }
            d.value = this.FnRoundToDecimal(usedVal);
            totalAmount += usedVal;
          });
        }
      })
      .catch(async (err) => {
        console.log(err);
      });
      // 副標題
      this.pieOptions.title.subtext = `當${
        this.search.range == "day" ? "日" : "月"
      }總${subTitleStr} ${this.FnRoundToDecimal(totalAmount)} ${unit}`;
    },
    //樹狀陣列平扁化
    get_options_id(array, key, group) {
      var that = this;
      // console.log(key, group);
      if (device_item[group][key]) {
        device_item[group][key]["options"].forEach((el) => {
          if (!isNaN(Number(el.value, 10))) {
            array.push(el.value);
          } else if (device_item[group].hasOwnProperty(el.label)) {
            return that.get_options_id(array, el.label, group);
          }
        });
      }
    },
  },
};
