<template>
  <div>
    <q-page-sticky
      position="top-right"
      :offset=[0,100]
    >
      <q-btn
        v-if="$root.VarIsRightMenu && showArrowButton && !isRightMenuOpen"
        dense
        :style="{'width':($root.VarIsDesktop?'20px':'30px')}"
        :class="'arrow-button'+(isSelectedBlink && selectItemValue!=''? '-select':'')"
        @click="toggleRightMenu"
      >{{ isRightMenuOpen ? '&gt' : '&lt' }}</q-btn>
    </q-page-sticky>
    <q-layout-drawer
      :overlay="true"
      side="right"
      v-model="isRightMenuOpen"
    >
      <div class="w3-display-container w3-container main-menu">
        <button
          class="w3-display-topright w3-hover-shadow close-menu"
          @click="toggleRightMenu"
        ><i class="material-icons">close</i></button>
        <br><br>
        <q-input
          color="secondary"
          :stack-label="$t('sys.search')"
          v-model="textFilter"
          clearable
        ></q-input>
        <br>
        <!--<q-tree
          :nodes="stationCityListTree"
          node-key="value"
          label-key="label"
          :filter="textFilter"
          :selected.sync="selectItem"
          default-expand-all
        ></q-tree>-->
        <q-list no-border>
          <div
            v-for="colls in stationCityListTree"
            :key="colls.value"
          >
            <q-collapsible
              :icon="colls.icon"
              :label="colls.label"
              v-if="colls.children && colls.children.length>0"
              v-model="cityOpendMap[colls.value]"
            >
              <!--
              :opened="autoCollapse && colls.value == selectItemParent" 因為只支援首次render, 所以要用cityOpendMap來控制
            -->
              <q-list no-border>
                <q-item
                  v-for="itm in colls.children"
                  :key="itm.value"
                  :class="selectItemValue==itm.value ? 'select-color' : ''"
                  style="cursor:pointer;"
                >
                  <q-item-main
                    :label="itm.label"
                    @click.native="onSelect(itm)"
                  ></q-item-main>
                  <q-item-side right>
                    <q-item-tile
                      v-show="!mustSelect && selectItemValue==itm.value"
                      icon="close"
                      class="item-btn-remove"
                      @click.native="removeSelectItem"
                    ></q-item-tile>
                  </q-item-side>
                </q-item>
              </q-list>
            </q-collapsible>
            <div v-if="!colls.children">
              <q-item :class="selectItemValue==colls.value ? 'select-color' : ''">
                <q-item-side
                  v-if="colls.icon"
                  :icon="colls.icon"
                ></q-item-side>
                <q-item-main
                  :label="$t('taiwan_place.'+colls.value)"
                  @click.native="onSelect(colls)"
                  style="cursor:pointer;"
                ></q-item-main>
                <q-item-side right>
                  <q-item-tile
                    v-show="selectItemValue==colls.value"
                    icon="close"
                    class="item-btn-remove"
                    @click.native="removeSelectItem"
                  ></q-item-tile>
                </q-item-side>
              </q-item>
            </div>
          </div>
        </q-list>
      </div>
    </q-layout-drawer>
  </div>
</template>

<script>
/* usage:
 <right-menu-station select-type="station" :show-stn-id="false" :auto-collapse="true" :mounted-force-send-select="true" :show-arrow-button="true" @on-select="OnSelect"></right-menu-station>
    select-type: "station" or "city" (default: station) 案場或者區域
    set-item-value: 若select-type是station則可用案場編號指定,若是city則可用如:penghu_county指定 <right-menu-station select-type="station" :set-item-value="4" @on-select=" OnSelect"></right-menu-station> or <right-menu-station select-type="city" :set-item-value="taichung_city" @on-select=" OnSelect"></right-menu-station>
    show-stn-id: true or false (default: false) 是否顯示案場編號
    auto-collapse: true or false (default: true) 是否自動收合(true: 預設收合但被選擇的案場區域會開啟, false: 預設全部展開)
    mounted-force-send-select: true or false (default: true) 是否強制送出選擇的值(避免在mounted時沒有送出)
    show-arrow-button: true or false (default: true) 是否顯示箭頭按鈕
    must-select: ture or false (default: false) 是否必須選擇一項(如果沒有選擇, 會自動選擇第一項, 且不能取消選擇)
    is-selected-blink: ture or false (default: true) 有選擇項目時是否閃爍
    on-select: function (data) { // data = { "select-type": "station", "value": "1" } or { "select-type": "city", "value": "taipei_city" }
        console.log(data);
    }
    select-item.sync: 可用來取代 @on-select="onSelect" <right-menu-station select-type="station" :select-item.sync="selectItem"></right-menu-station>
*/
module.exports = {
  data () {
    return {
      cityList: [],
      stationCityList: [],
      cityOpendMap: {}, // 個別城市是否展開(因為 opend 只支援首次render, 所以要用這個來控制)
      textFilter: "",
      selectItem: null,
      taiwanPlaceOrder: [ // 為了讓城市按照台灣地圖的順序排列, 對應 Station_Spec 資料表的 City 欄位
        "keelung_city", // 基隆市
        "new_taipei_city", // 新北市
        "taipei_city", // 台北市
        "taoyuan_city", // 桃園市
        "hsinchu_county", // 新竹縣
        "hsinchu_city", // 新竹市
        "miaoli_city", // 苗栗市
        "miaoli_county", // 苗栗縣
        "taichung_city", // 台中市
        "changhua_county", // 彰化縣
        "changhua_city", // 彰化市
        "nantou_city", // 南投市
        "nantou_county", // 南投縣
        "yunlin_county", // 雲林縣
        "chiayi_county", // 嘉義縣
        "chiayi_city", // 嘉義市
        "tainan_city", // 台南市
        "kaohsiung_city", // 高雄市
        "pingtung_county", // 屏東縣
        "pingtung_city", // 屏東市
        "yilan_county", // 宜蘭縣
        "yilan_city", // 宜蘭市
        "hualien_county", // 花蓮縣
        "hualien_city", // 花蓮市
        "taitung_city", // 台東市
        "taitung_county", // 台東縣
        "penghu_county", // 澎湖縣
        "green_island", // 綠島
        "orchid_island", // 蘭嶼
        "kinmen_county", // 金門縣
        "matsu", // 馬祖
        "lienchiang_county" // 連江縣
      ],
    }
  },
  props: {
    "select-type": { // "station" or "city"
      "type": "String",
      "default": "station",
    },
    "auto-collapse": { // 自動收合(true: 預設收合但被選擇的案場區域會開啟, false: 預設全部展開)
      "type": "Boolean",
      "default": true,
    },
    "mounted-force-send-select": { // 是否強制送出選擇的值(避免在mounted時沒有送出)
      "type": "Boolean",
      "default": true,
    },
    "show-stn-id": { // 是否案場編號
      "type": "Boolean",
      "default": false,
    },
    "show-arrow-button": { // 是否顯示箭頭按鈕
      "type": "Boolean",
      "default": true,
    },
    "must-select": { // 是否必須選擇一項(如果沒有選擇, 會自動選擇第一項, 且不能取消選擇)
      "type": "Boolean",
      "default": false,
    },
    "is-selected-blink": {  // 有選擇項目時是否閃爍
      "type": "Boolean",
      "default": true,
    },
    "set-item-value": { // 若select-type是station則可用案場編號指定,若是city則可用如:penghu_county指定
      "type": "String",
      "default": "",
    },
    "filter-stn": {
      "type": "Array",
      "default": [],
    },
  },
  computed: {
    isRightMenuOpen: {
      get () {
        return this.$root.VarIsRightMenuOpen;
      },
      set (val) {
        this.$root.VarIsRightMenuOpen = val;
      }
    },
    filterStnMap () {
      return _.reduce(this.filterStn, (result, stn) => {
        result[stn] = stn;
        return result;
      }, {});
    },
    dataList () {
      if (this.selectType == "station") {
        // Yen，新增功能 判斷有沒有傳可看案場內容進來
        if (this.filterStn.length > 0) {
          var ftStn = _.filter(this.stationCityList, (item) => {
            return !_.isUndefined(this.filterStnMap[item.STN]);
          });
          return ftStn;

        } else {
          return this.stationCityList;
        }

      } else if (this.selectType == "city") {
        return this.cityList;
      }
    },
    dataKeyMap () { // 用來取得單一項目的資料
      let dataMap = {};
      this.dataList.forEach((item) => {
        if (this.selectType == "station") {
          dataMap[item.STN] = item;
        } else {
          dataMap[item.City] = item;
        }
      });
      // console.log(dataMap)
      return dataMap;
    },
    cityStationMap () {
      let cityMap = {};
      this.dataList.forEach((item) => {
        if (_.isUndefined(cityMap[item.City])) {
          cityMap[item.City] = [];
        }
        cityMap[item.City].push(item);
      });
      return cityMap;
    },
    stationCityListTree () {
      let cityListTree = [];
      for (let place in this.taiwanPlaceOrder) {
        if (_.isUndefined(this.cityStationMap[this.taiwanPlaceOrder[place]])) {
          continue;
        }
        let city = this.taiwanPlaceOrder[place];
        if (this.selectType == "city" && this.textFilter != "" && this.$t('taiwan_place.' + city).toLowerCase().indexOf(this.textFilter.toLowerCase()) == -1) {
          continue;
        }
        let cityItem = {
          label: this.$t('taiwan_place.' + city), // 多國語系
          value: city,
        };
        if (this.selectType == "station") {
          cityItem.children = [];
          this.cityStationMap[city].forEach((item) => {
            // 檢查是否有符合搜尋文字
            if (this.textFilter == "" || item.Name.toLowerCase().indexOf(this.textFilter.toLowerCase()) > -1) {
              if (this.showStnId) {
                cityItem.children.push({
                  label: item.STN + "." + item.Name,
                  value: item.STN,
                });
              } else {
                cityItem.children.push({
                  label: item.Name,
                  value: item.STN,
                });
              }
            }
          });
        }
        cityListTree.push(cityItem);
      }
      return cityListTree;
    },
    selectItemValue () { // 選擇的值(放在html)
      if (this.selectItem == "" || this.selectItem == null) {
        return "";
      } else {
        return this.selectItem.value;
      }
    },
    selectItemLabel () { // 選擇的值的標籤(放在html)
      // console.log(this.dataKeyMap, this.selectItemValue, typeof (this.dataKeyMap[this.selectItemValue]));
      if (this.selectItem == "" || this.selectItem == null) {
        return "";
      } else {
        if (this.selectType == "city") {
          return this.dataKeyMap[this.selectItemValue].City_Name;
        } else if (this.selectType == "station") { // Yen如果切換回CCTV沒有此案場選線，選擇的值的標籤不顯示
          if (this.filterStn.length > 0 && this.dataKeyMap[this.selectItemValue] == undefined) {
            return "";
          } else {
            return this.dataKeyMap[this.selectItemValue].Name;
          }
        }
      }
    },
    selectItemParent () { // 選擇的值的父層(放在html判斷用)
      if (this.selectItem == "" || this.selectItem == null) {
        return "";
      } else {
        if (this.selectType == "station") {
          for (let city in this.cityStationMap) {
            let cityItem = this.cityStationMap[city].find((item) => {
              return item.STN == this.selectItem.value;
            });
            if (cityItem != null) {
              return city;
            }
          }
          return "";
        } else if (this.selectType == "city") {
          return "";
        }
      }
    }
  },
  watch: {
    selectItemParent (nv) {
      // 試過寫在 computed selectItemParent 但無效, 須寫在 watch 才有效
      if (this.autoCollapse) { // 是否自動收合(true: 預設收合但被選擇的案場區域會開啟, false: 預設全部展開)
        this.cityOpendMap[nv] = true;
      }
    }
  },
  async beforeMount () {
    this.$root.VarIsRightMenu = true; // 有放 <right-menu-xxx></right-menu-xxx> 在.php 就直接啟用(也會讓more_menu會增加此選項)
    if (this.selectType == "station") {
      await this.getStationList();
    } else if (this.selectType == "city") {
      await this.getCityList();
    }
    let storageSelect = this.getStorageSelect();
    if (this.setItemValue != "" && !_.isUndefined(this.dataKeyMap[this.setItemValue.toString()])) {
      storageSelect = { "select-type": this.selectType, "value": this.setItemValue.toString() };
      this.onSelect(storageSelect, false); // 寫入sessionStorage, 但不觸發on-select
    }
    // 判斷是否有傳可看案場內容進來
    if (!_.isEmpty(this.filterStn) && !_.isNull(storageSelect) && _.isUndefined(this.filterStnMap[storageSelect["value"]])) {
      this.$root.FnNotify( this.$root.$t('layout.right_menu_msg.noselect')+storageSelect['label']+this.$root.$t('layout.right_menu_msg.nocctv'), 'warning'); 
      storageSelect = null;
    }
    if (this.mustSelect && storageSelect == null) {
      let tmpItm = _.first(this.dataList);
      if (!_.isUndefined(tmpItm) && tmpItm != null) {
        if (this.selectType == "station") {
          storageSelect = { "select-type": this.selectType, "value": tmpItm.STN };
          this.$root.FnNotify( this.$root.$t('layout.right_menu_msg.select')+storageSelect['value'], 'success');
        } else if (this.selectType == "city") {
          storageSelect = { "select-type": this.selectType, "value": tmpItm.City };
        }
        this.onSelect(storageSelect, false); // 寫入sessionStorage, 但不觸發on-select
      }
    }
    if (storageSelect != null) {
      this.selectItem = storageSelect;
      this.selectItem.label = this.selectItemLabel;
      
    }
    if (this.mountedForceSendSelect) {
      this.throwSelectItem();
    }
  },
  methods: {
    toggleRightMenu () {
      this.isRightMenuOpen = !this.isRightMenuOpen;
    },
    getCityList () {
      let params = {
        "Action": "StationCityList",
        "menu_page": "sys_component",
        "Datas": { "is_only_city": "1" },
      };
      return this.$root.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          this.cityList = res.data.data;
        }
      });
    },
    getStationList () {
      let params = {
        "Action": "StationCityList",
        "menu_page": "sys_component",
        "Datas": {},
      };
      return this.$root.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          _.each(res.data.data, (itm) => {
            this.stationCityList.push(itm);
            this.cityOpendMap[itm.City] = false;
          });
        }
      });
    },
    getStorageSelect () {
      if (this.selectType == "station") {
        return this.$q.sessionStorage.get.item('$$select_station');
      } else {
        return this.$q.sessionStorage.get.item('$$select_city');
      }
    },
    setStorageSelect (data) {
      if (this.selectType == "station") {
        this.$q.sessionStorage.set('$$select_station', data);
      } else {
        this.$q.sessionStorage.set('$$select_city', data);
      }
    },
    removeStorageSelect () {
      if (this.selectType == "station") {
        this.$q.sessionStorage.remove('$$select_station');
      } else {
        this.$q.sessionStorage.remove('$$select_city');
      }
    },
    onSelect (itm, isThorowSelectItem = true) {
      let data = { "select-type": this.selectType, "value": itm.value };
      this.selectItem = data;
      this.selectItem.label = this.selectItemLabel;
      this.setStorageSelect(data);
      if (isThorowSelectItem) {
        this.throwSelectItem();
      }
    },
    removeSelectItem () {
      this.selectItem = null;
      this.removeStorageSelect();
      this.throwSelectItem();
    },
    throwSelectItem () {
      this.$emit('on-select', this.selectItem);
      this.$emit('update:selectItem', this.selectItem);
    }
  }
}
</script>

<style scoped>
.main-menu {
  background-color: #334048;
  color: #fff;
  height: 100%;
  font-size: 12pt !important;
}

.main-menu .q-list {
  background-color: #334048;
}

.main-menu .q-list .q-item {
  font-size: 12pt;
}
/*.main-menu .q-list .q-item:hover {
  font-size: 12pt;
  background-color: #676f76;
  color: #fff;
}*/

.item-btn {
  color: #ffffff2b;
  cursor: pointer;
}

.item-btn-remove {
  color: #fff;
  cursor: pointer;
}

.item-btn:hover,
.item-btn-remove:hover {
  background-color: #fff;
  color: #000;
  cursor: pointer;
}

.main-menu .q-item-side {
  color: #fff !important;
}

.main-menu .q-list-header {
  color: #f7e6cc;
  font-size: 12pt;
}

.main-menu .select-color {
  background-color: #676f76;
  color: #fff;
}

.close-menu {
  cursor: pointer;
  border: none;
  outline: none;
  background-color: #ffffff9f;
  margin: 10px 10px 10px 10px;
}

.close-menu:hover {
  cursor: pointer;
  border: none;
  outline: none;
  background-color: #ffffff;

  margin: 10px 10px 10px 10px;
}

@keyframes blink {
  0% {
    opacity: 1;
    background-color: #334048;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
    background-color: #334048;
  }
}
.arrow-button {
  background-color: #33404849;
  color: #fff;
}

.arrow-button-select {
  color: #fff;
  animation: blink 3s infinite;
}

.arrow-button:hover {
  background-color: #334048;
  color: #fff;
}

input {
  color: white !important;
}
</style>