<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (!loading && evt.keyCode == 27) {
          show_dialog = false;
        }
      }
    "
  >
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 60vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("weather") }}
            </div>
            <q-space />
            <div>
              <q-btn
                :loading="loading"
                flat
                round
                icon="close"
                color="red"
                :disable="loading"
                v-close-popup
              >
                <q-tooltip>
                  {{ $t("close") }}
                </q-tooltip>
              </q-btn>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section style="max-height: 68vh; width: 55vw" class="scroll">
          <q-list>
            <q-item>
              <q-item-section>
                <q-checkbox
                  left-label
                  v-model="weather_entity.auto_location"
                  :label="$t('auto location')"
                />
              </q-item-section>

              <q-item-section>
                <q-checkbox
                  left-label
                  v-model="weather_entity.background_transparent"
                  :label="$t('background transparent')"
                />
              </q-item-section>
              <q-item-section></q-item-section>
            </q-item>

            <q-item v-if="!weather_entity.auto_location">
              <q-item-section avatar class="head_1">
                {{ $t("location") }}
              </q-item-section>
              <q-item-section v-if="false">
                <q-select
                  :label="$t('city_country')"
                  v-model="country"
                  :loading="loading"
                  :disable="loading"
                  :options="country_options"
                  emit-value
                  map-options
                  :rules="[(val) => !!val || 'Field is required']"
                />
              </q-item-section>
              <q-item-section>
                <q-select
                  :label="$t('city_province')"
                  v-model="province"
                  :loading="loading"
                  :disable="loading"
                  :options="province_options"
                  @update:model-value="refresh_city_options"
                  emit-value
                  map-options
                />
              </q-item-section>
              <q-item-section>
                <q-select
                  :label="$t('city_city')"
                  v-model="city"
                  :loading="loading"
                  :disable="loading"
                  :options="city_options"
                  @update:model-value="refresh_area_options"
                  emit-value
                  map-options
                />
              </q-item-section>
              <q-item-section>
                <q-select
                  :label="$t('city_area')"
                  v-model="area"
                  :loading="loading"
                  :disable="loading"
                  :options="area_options"
                  @update:model-value="on_area_selected"
                  emit-value
                  map-options
                />
              </q-item-section>
            </q-item>

            <q-item>
              <q-item-section avatar class="head_1">
                {{ $t("background color") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  :disable="weather_entity.background_transparent"
                  v-model="weather_entity.background_color"
                  :rules="['anyColor']"
                >
                  <template v-slot:append>
                    <q-icon name="colorize" class="cursor-pointer">
                      <q-popup-proxy
                        cover
                        transition-show="scale"
                        transition-hide="scale"
                      >
                        <q-color v-model="weather_entity.background_color" />
                      </q-popup-proxy>
                    </q-icon>
                  </template>
                </q-input>
              </q-item-section>
            </q-item>

            <q-item v-if="false">
              <q-item-section avatar class="head_1">
                {{ $t("font color") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  v-model="weather_entity.text_color"
                  :rules="['anyColor']"
                >
                  <template v-slot:append>
                    <q-icon name="colorize" class="cursor-pointer">
                      <q-popup-proxy
                        cover
                        transition-show="scale"
                        transition-hide="scale"
                      >
                        <q-color v-model="weather_entity.text_color" />
                      </q-popup-proxy>
                    </q-icon>
                  </template>
                </q-input>
              </q-item-section>
            </q-item>

            <q-item>
              <q-item-section avatar class="head_1">
                {{ $t("font size") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  v-model="weather_entity.font_size"
                  type="number"
                  lazy-rules
                  :rules="[
                    (val) =>
                      (val && val.toString().length > 0) ||
                      $t('Please type something'),
                  ]"
                >
                  <template v-slot:append>
                    <span>pt</span>
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-separator />
        <q-card-actions>
          <q-space />
          <q-btn
            :loading="loading"
            flat
            no-caps
            :label="$t('close and reset')"
            color="primary"
            v-close-popup
          />
          <q-btn
            ref="accept"
            flat
            no-caps
            :label="$t('close and save')"
            :loading="loading"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.head_1 {
  width: 15%;
}

.head_2 {
  width: 8%;
}
</style>

<script lang="ts">
import { defineComponent, ref, Ref, watch, computed, reactive } from "vue";
import { useStore } from "src/store";
import GlobalData from "src/common/GlobalData";
import { useQuasar, date as DateHelper, Cookies } from "quasar";
import { useI18n } from "vue-i18n";
import WeatherWindowParamEntity from "src/entities/WeatherWindowParamEntity";
import { api } from "src/boot/axios";

export default defineComponent({
  name: "ComponentWeatherSignalSourceDialog",
  components: {},

  setup() {
    let $store = useStore();
    let $q = useQuasar();
    let $t = useI18n();

    const weather_entity = ref(new WeatherWindowParamEntity());

    let show_dialog = ref(false);
    let loading = ref(false);

    const country: Ref<string | null> = ref(null);
    const country_options: Ref<any[]> = ref([]);
    const province: Ref<string | null> = ref(null);
    const province_options: Ref<any[]> = ref([]);
    const city: Ref<string | null> = ref(null);
    const city_options: Ref<any[]> = ref([]);
    const area: Ref<string | null> = ref(null);
    const area_options: Ref<any[]> = ref([]);

    let all_city_data: any[] | null = null;

    let get_all_city_data: any = null;

    let refresh_city_options: any = null;
    let refresh_area_options: any = null;
    let on_area_selected: any = null;

    const refresh_province_options = () => {
      if (!country.value) {
        if (country_options.value.length) {
          country.value = country_options.value[0].value;
        } else {
          console.error(
            "country is null and country_options is empty",
            country.value,
            country_options.value
          );
          return;
        }
      }

      if (!all_city_data) {
        if (get_all_city_data && typeof get_all_city_data == "function") {
          get_all_city_data();
        }
      } else {
        const countrt_data = all_city_data.find(
          (e) => e && e.country == country.value
        );
        if (countrt_data) {
          if (Array.isArray(countrt_data.provinces)) {
            province_options.value = [];
            for (const _province of countrt_data.provinces) {
              province_options.value.push({
                label: _province.province,
                data: _province,
                value: _province.province,
              });
            }

            const find = province_options.value.find(
              (e) => e && e.label == province.value
            );
            if (!find && province_options.value.length) {
              province.value = province_options.value[0].value;
            }
            refresh_city_options();
          } else {
            console.error("countrt_data is not array", countrt_data);
          }
        } else {
          console.error(
            "countrt_data is null!",
            countrt_data,
            all_city_data,
            country.value
          );
        }
      }
    };

    refresh_city_options = () => {
      if (!province.value) {
        if (province_options.value.length) {
          province.value = province_options.value[0].value;
        } else {
          console.error(
            "province is null and province_options is empty",
            province.value,
            province_options.value
          );
        }
      }

      const province_data = province_options.value.find(
        (e) => e && e.value == province.value
      );
      if (province_data) {
        if (province_data.data && Array.isArray(province_data.data.citys)) {
          city_options.value = [];
          for (const _city of province_data.data.citys) {
            city_options.value.push({
              label: _city.city,
              value: _city.city,
              data: _city,
            });
          }
          const find = city_options.value.find(
            (e) => e && e.label == city.value
          );
          if (!find && city_options.value.length) {
            city.value = city_options.value[0].value;
          }
          refresh_area_options();
        } else {
          console.error("province_data is invalid!", province_data);
        }
      } else {
        console.error(
          "can't find province_data",
          province.value,
          province_options.value
        );
      }
    };

    refresh_area_options = () => {
      if (!city.value) {
        if (city_options.value.length) {
          city.value = city_options.value[0].value;
        } else {
          console.error(
            "city is null and city_options is empty",
            city.value,
            city_options.value
          );
        }
      }

      const city_data = city_options.value.find(
        (e) => e && e.value == city.value
      );

      if (city_data) {
        if (city_data.data && Array.isArray(city_data.data.areas)) {
          area_options.value = [];
          for (const _area of city_data.data.areas) {
            let area_value = _area.area;
            /*if (_area.area == city.value) {
              area_value = $t.t("city_city_area");
            }*/
            area_options.value.push({
              label: area_value,
              value: area_value,
              data: _area,
            });
          }

          const find = area_options.value.find(
            (e) => e && e.label == area.value
          );
          if (!find && area_options.value.length) {
            area.value = area_options.value[0].value;
          }
          on_area_selected();
        } else {
          console.error("city_data is invalid!", city_data);
        }
      } else {
        console.error("can't find city_data", city.value, area_options.value);
      }
    };

    get_all_city_data = () => {
      const global_data = GlobalData.getInstance().getCurrentClient();
      if (global_data) {
        let language = Cookies.get("language");

        global_data
          .getCityList(language ?? "")
          .then((resposne) => {
            if (!resposne) {
              return;
            }
            const data = resposne.city_list;
            if (Array.isArray(data)) {
              all_city_data = data;
              country_options.value = [];
              for (const _country of all_city_data) {
                country_options.value.push({
                  data: _country,
                  label: _country.country,
                  value: _country.country,
                });
              }
            } else {
              console.error("data is not array!", data);
            }
          })
          .catch((e) => {
            console.error(e);
          });
      } else {
        console.error(
          "get_all_city_data failed, current client connection is null!"
        );
        setTimeout(() => {
          if (get_all_city_data) {
            get_all_city_data();
          }
        }, 500);
      }
    };

    on_area_selected = () => {
      if (!area.value) {
        if (area_options.value.length) {
          area.value = area_options.value[0].value;
        } else {
          console.error(
            "area is null and area_options is empty",
            area.value,
            area_options.value
          );
        }
      }

      const area_data = area_options.value.find(
        (e) => e && e.value == area.value
      );

      if (area_data) {
        if (area_data && area_data.data && area_data.data.code) {
          weather_entity.value.location_code = area_data.data.code;
          return;
        } else {
          console.error("area_data is invalid!", area_data);
        }
      } else {
        console.error("can't find area_data", area.value, area_options.value);
      }
      area.value = null;
    };

    get_all_city_data();

    let _resolove: any = null;

    const initialize_properties = (json: string) => {
      if (json) {
        try {
          const temp = JSON.parse(json);
          for (const item of Object.keys(weather_entity.value)) {
            if (typeof temp[item] != "undefined") {
              (<any>weather_entity.value)[item] = temp[item];
            }
          }
        } catch {}
      }
    };

    return {
      show_dialog,
      loading,
      weather_entity,
      country,
      country_options,
      province,
      province_options,
      city,
      city_options,
      area,
      area_options,

      refresh_province_options,
      refresh_city_options,
      refresh_area_options,
      on_area_selected,

      showDialogAsync(options: any) {
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
        show_dialog.value = true;
        initialize_properties(options);

        let find_flag = false;
        if (Array.isArray(all_city_data)) {
          if (weather_entity.value.location_code) {
            for (const _country of all_city_data) {
              if (find_flag) {
                break;
              }
              if (_country) {
                for (const _province of _country.provinces) {
                  if (find_flag) {
                    break;
                  }
                  if (_province) {
                    for (const _city of _province.citys) {
                      if (find_flag) {
                        break;
                      }
                      if (_city) {
                        for (const _area of _city.areas) {
                          if (find_flag) {
                            break;
                          }
                          if (
                            _area.code == weather_entity.value.location_code
                          ) {
                            // 找到地区码对应的地区、城市、省、国家
                            country.value = _country.country;
                            province.value = _province.province;
                            city.value = _city.city;
                            area.value = _area.area;
                            find_flag = true;
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        if (!find_flag && country_options.value.length) {
          country.value = country_options.value[0].value;
        }

        refresh_province_options();

        return new Promise((resolove) => {
          _resolove = resolove;
        });
      },
      resetData() {
        loading.value = false;
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
      },
      async onSubmit() {
        loading.value = true;
        try {
          if (_resolove) {
            try {
              weather_entity.value.font_size = parseInt(
                weather_entity.value.font_size.toString()
              );
              _resolove(JSON.stringify(weather_entity.value));
            } catch {
              _resolove();
            }
          }
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
    };
  },
});
</script>
