<template>
  <div>
    <div class="text-center pb-8">
      <v-img
        class="mx-auto"
        :aspect-ratio="1"
        src="@/assets/logo-title.png"
        width="250"
      ></v-img>
      <div class="text-title txt-black">ค้นหาผู้สมัคร สว.</div>
      <div class="my-5 text-sub2 px-5">
        สามารถค้นหาผู้แสดงตนเป็นผู้สมัคร สว. ใน จังหวัด / อำเภอ
        ที่ตัวเองเป็นผู้แสดงตน
      </div>
      <div class="text-small text-red-darken-3">
        * การแสดงผลเป็นแบบสุ่มไม่เรียงลำดับ
      </div>
      <v-container>
        <!-- {{ checkdata }} -->
        <v-row class="d-none" v-if="fasle">
          <v-col cols="12" md="4">
            <v-text-field
              label="จังหวัด"
              variant="solo"
              v-model="province"
              :value="province.name"
              readonly
            ></v-text-field>

            <!-- <v-autocomplete
              clearable
              label="จังหวัด"
              :items="provinceItems"
              variant="solo"
              item-title="name"
              item-value="id"
              v-model="province"
              placeholder="จังหวัด"
              @update:modelValue="filterData"
              hide-details
            ></v-autocomplete
          > -->
          </v-col>
          <v-col cols="12" md="4">
            <v-text-field
              label="อำเภอ / เขต"
              variant="solo"
              v-model="district"
              :value="district.name"
              readonly
            ></v-text-field>
            <!-- <v-autocomplete
              clearable
              label="อำเภอ / เขต"
              :items="districtItems"
              variant="solo"
              item-title="name"
              v-model="district"
              item-value="id"
              placeholder="อำเภอ / เขต"
              hide-details
              :disabled="province == null"
            ></v-autocomplete
          > -->
          </v-col>
          <v-col cols="12" md="4">
            <v-text-field
              label="กลุ่มอาชีพ"
              variant="solo"
              v-model="group"
              :value="group.id + ' ' + group.name"
              readonly
            ></v-text-field>
            <!-- <v-autocomplete
              clearable
              label="กลุ่มอาชีพ"
              :items="items"
              variant="solo"
              item-title="name"
              return-object
              placeholder="กลุ่มอาชีพ"
              hide-details
              v-model="group"
            >
              <template v-slot:item="{ props, item }">
                <v-list-item
                  v-bind="props"
                  :title="item.raw.id + ' ' + item.raw.name"
                ></v-list-item>
              </template>
            </v-autocomplete> -->
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="12" md="4">
            <!-- <v-text-field
              label="จังหวัด"
              variant="solo"
              v-model="province"

            ></v-text-field> -->

            <v-autocomplete
              clearable
              label="จังหวัด"
              :items="provinceItems"
              variant="solo"
              item-title="name"
              item-value="id"
              v-model="province"
              placeholder="จังหวัด"
              @update:modelValue="filterData"
              hide-details
            ></v-autocomplete>
          </v-col>
          <v-col cols="12" md="4" class="d-none">
            <!-- <v-text-field
              label="อำเภอ / เขต"
              variant="solo"
              v-model="district"
          
   
            ></v-text-field> -->
            <v-autocomplete
              clearable
              label="อำเภอ / เขต"
              :items="districtItems"
              variant="solo"
              item-title="name"
              v-model="district"
              item-value="id"
              placeholder="อำเภอ / เขต"
              hide-details
              :disabled="province == null"
            ></v-autocomplete>
          </v-col>
          <v-col cols="12" md="4">
            <!-- <v-text-field
              label="กลุ่มอาชีพ"
              variant="solo"
              v-model="group"
            ></v-text-field> -->

            <v-autocomplete
              v-model="group"
              clearable
              label="กลุ่มอาชีพ"
              :items="items"
              variant="solo"
              :item-title="(item) => item.id + ' ' + item.name"
              return-object
              placeholder="กลุ่มอาชีพ"
              hide-details
              @update:modelValue="filterName"
            >
              <template v-slot:item="{ props, item }">
                <v-list-item
                  v-bind="props"
                  :title="item.raw.id + ' ' + item.raw.name"
                ></v-list-item>
              </template>
            </v-autocomplete>
          </v-col>
          <v-col cols="12" md="4">
            <!-- <v-text-field
              label="กลุ่มอาชีพ"
              variant="solo"
              v-model="group"
            ></v-text-field> -->
            <!-- {{ nameUser }} -->
            <v-autocomplete
              clearable
              label="รายชื่อ"
              :items="nameUserItems"
              variant="solo"
              :item-title="(item) => item.firstName + ' ' + item.lastName"
              item-value="id"
              placeholder="รายชื่อ"
              :loading="loadname"
              hide-details
              v-model="nameUser"
              :disabled="nameUserItems.length == 0 || group == null"
            >
              <!-- <template v-slot:selection="{ item }">
                {{ item.firstName }} {{ item.lastName }}
              </template> -->
              <template v-slot:item="{ props, item }">
                <v-list-item
                  v-bind="props"
                  :title="item.raw.firstName + ' ' + item.raw.lastName"
                ></v-list-item>
              </template>
            </v-autocomplete>
          </v-col>
        </v-row>
        <v-btn
          color="#e23972"
          class="mt-8"
          elevated
          size="large"
          @click="
            searchUserApi(0, '');
            showGroup = false;
          "
          :disabled="group == null || province == null"
          :loading="load || load2"
          width="300"
          height="52px"
        >
          <span class="text-sub">ค้นหากลุ่มอาชีพตนเอง</span>
        </v-btn>
        <!-- @click="searchUserApi(0, 'all')" -->
        <v-btn
          color="#4c884c"
          class="mx-5 mt-8"
          elevated
          size="large"
          width="300"
          @click="clickShowGroup"
          :loading="load || load2"
          height="52px"
          stack
          :disabled=" group == null || province == null"
        >
          <div class="text-sub">ค้นหาต่างกลุ่มอาชีพ</div>

          <!-- <div class="txt-small">(ยกเว้นอาชีพตนเอง)</div> -->
        </v-btn>
      </v-container>
      <div v-if="!showGroup">
        <CardUser :dataProfile="result" v-if="result.length" class="mt-2" />

        <div
          v-if="result.length == 0 && this.show"
          class="my-10 text-sub2 txt-black"
        >
          <v-icon icon="mdi-alert-circle"></v-icon> ไม่พบข้อมูล
        </div>

        <div class="text-center mt-2">
          <v-pagination
            elevation="3"
            v-if="count > 1"
            v-model="page"
            :length="Math.ceil(count / 2)"
            rounded="circle"
            @update:model-value="searchUser((this.page - 1) * 2)"
            next-icon="mdi-menu-right"
            prev-icon="mdi-menu-left"
          ></v-pagination>
        </div>
      </div>
      <!-- <v-container class="my-0 py-0"> -->
      <div>
        <v-progress-linear
          v-if="showGroup && load2"
          class="px-7 mt-5"
          style="width: 90%"
          color="green"
          :indeterminate="load2"
        ></v-progress-linear>
        <v-checkbox
          v-if="showGroup"
          v-model="checkbox1"
          label="ดูเฉพาะกลุ่มอาชีพที่มีข้อมูล"
          size="large"
          class="px-7 mt-5 check-card text-subtitle"
          color="#3d763d"
          hide-details
        ></v-checkbox>
      </div>
      <!-- </v-container>  -->

      <div v-for="(groupx, i) in apiGroup" :key="groupxKey + '-' + i">
        <CardUserGroup
          :check="checkbox1"
          :group="groupx"
          :province="province"
       
          v-if="showGroup"
          @value-sent="handleValueSent"
        />
      </div>
    </div>
  </div>
</template>
<script>
// import Provinces from "@/components/form/provinces.json";
// import Districts from "@/components/form/districts.json";
import CardUser from "./CardUser.vue";
import CardUserGroup from "./CardUserGroup.vue";
import { client } from "@/utils/trpc";
import { mapGetters } from "vuex";

export default {
  computed: {
    ...mapGetters(["getUsername", "getImg"]),
  },
  components: {
    CardUser,
    CardUserGroup,
  },
  data() {
    return {
      groupxKey: 0,
      loadname: false,
      nameUser: null,
      nameUserItems: [],
      load2: false,
      checkbox1: true,
      showGroup: false,
      apiGroup: [],
      allg: "",
      checkdata: "",
      show: false,
      load: false,
      result: [],
      page: 1,
      province: null,
      district: null,
      districtItems: [],
      provinceItems: [],
      items: [],
      group: null,
      offset: 0,
      count: 0,
    };
  },
  methods: {
    clickShowGroup() {
      // this.showGroup = false;
      this.groupxKey += 1;
      this.showGroup = true;
    },
    filterName() {
      // console.log("grop", this.group);
      this.nameUser = null;
      this.getUserItems(0);
      let filteredGroup = [...this.items].filter((x) => x.id !== this.group.id);
      this.apiGroup = filteredGroup;
    },
    handleValueSent(value) {
      this.load2 = value;
      console.log("Received value from child:", value);
      // ทำงานกับค่าที่ได้รับ
    },
    getUserItems(offset) {
      this.show = false;
      this.loadname = true;
      if (offset == 0) {
        this.page = 1;
      }
      let data = {
        offset: offset,
      };
      if (this.province) {
        data.province = this.province;
        // data.province = this.province;
      }
      if (this.group && this.group.id) {
        // console.log(this.group.id);
        data.group = this.group.id;
      }

      // if (this.district) {
      //   data.zone = this.district;
      // }

      // let param = { input: JSON.stringify({ 0: data }) };
      // var axios = require("axios");
      // var config = {
      //   method: "get",
      //   url: "http://localhost:3000/api/user.getAllUser",
      //   params: param,
      //   headers: {},
      // };

      // axios(config)
      //   .then((response) => {
      //     this.nameUserItems = response.data.result.data;
      //     this.loadname = false;
      //     console.log("nameUserItems", this.nameUserItems);
      //   })
      //   .catch((error) => {
      //     this.loadname = false;
      //     console.log(error);
      //   });

      client.user.getAllUser
        .query(data)
        .then((rs) => {
          this.nameUserItems = rs;
          console.log(rs);
          this.loadname = false;
        })
        .catch((error) => {
          this.loadname = false;
          alert("ไม่สามารถโหลดข้อมูลรายชื่อได้ได้");
          console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
        });
    },
    searchUser(offset) {
      this.show = false;
      this.load = true;
      if (offset == 0) {
        this.page = 1;
      }
      let data = {
        offset: offset,
        limit: 2,
      };
      if (this.province) {
        data.province = this.province;
        // data.province = this.province;
      }
      if (this.group) {
        if (this.allg !== "all") {
          data.group = this.group.id;
        }
      }
      // if (this.district) {
      //   data.zone = this.district;
      // }
      if (this.nameUser) {
        data.userId = this.nameUser;
      }

      client.user.getAllUser
        .query(data)
        .then((rs) => {
          this.result = rs;
          console.log(rs);
          this.load = false;
          if (rs.length == 0) {
            this.show = true;
          }
        })
        .catch((error) => {
          this.load = false;

          alert("ไม่สามารถโหลดข้อมูลได้");
          console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
        });
    },
    searchUserApi(offset, checkg) {
      this.allg = checkg;
      this.show = false;
      this.load = true;
      if (offset == 0) {
        this.page = 1;
      }
      // this.offset = (this.page - 1) * 10;
      let data = {
        offset: offset,
        limit: 2,
      };
      if (this.province) {
        data.province = this.province;
        // data.province = this.province;
      }

      if (this.group) {
        if (checkg !== "all") {
          data.group = this.group.id;
        }
      }
      // if (this.district) {
      //   data.zone = this.district;
      // }

      if (this.nameUser) {
        data.userId = this.nameUser;
      }

      // let param = { input: JSON.stringify({ 0: data }) };
      // var axios = require("axios");
      // if (this.nameUser) {
      //   this.count = 1;
      // } else {
      //   var config = {
      //     method: "get",
      //     url: "http://localhost:3000/api/user.getAllUserCount",
      //     params: param,
      //     headers: {},
      //   };

      //   axios(config)
      //     .then((response) => {
      //       this.count = response.data.result.data;
      //       console.log("getAllUserCount", this.count);
      //     })
      //     .catch((error) => {
      //       console.log(error);
      //     });
      // }
      if (this.nameUser) {
        this.count = 1;
      } else {
        client.user.getAllUserCount
          .query(data)
          .then((rs) => {
            this.count = rs;
          })
          .catch((error) => {
            alert("ไม่สามารถโหลดข้อมูลได้");
            console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
          });
      }
      // var config2 = {
      //   method: "get",
      //   url: "http://localhost:3000/api/user.getAllUser",
      //   params: param,
      //   headers: {},
      // };

      // axios(config2)
      //   .then((response) => {
      //     this.result = response.data.result.data;
      //     this.load = false;
      //     console.log("nameUserItems", this.nameUserItems);
      //   })
      //   .catch((error) => {
      //     this.load = false;

      //     console.log(error);
      //   });

      client.user.getAllUser
        .query(data)
        .then((rs) => {
          this.result = rs;
          console.log(rs);
          this.load = false;
          if (rs.length == 0) {
            this.show = true;
          }

        })
        .catch((error) => {
          this.load = false;
          // alert("ไม่สามารถโหลดข้อมูลได้");
          console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
        });
    },
    filterData() {
      // กรองข้อมูลอันที่สองโดยใช้ข้อมูลจากอันแรก
      this.district = null;
      if (this.province) {
        client.info.getAllZones
          .query({ provice_id: this.province })
          .then((data) => {
            this.districtItems = data;
          })
          .catch((error) => {
            // alert("ไม่สามารถโหลดข้อมูลได้");
            console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
          });
      }
    },
    getUser(datap) {
      client.user.getSelf
        .mutate({})
        .then((data) => {
          let province = datap.filter((x) => x.id === data.zone.province);
          // let g =[...this.items].filter((x) => x.id === data.group);
          this.province = province[0];
          this.district = data.zone;
          this.checkdata = { ...data };
          this.group = data.group;
          let filteredGroup = [...this.items].filter(
            (x) => x.id !== data.group.id
          );
          this.apiGroup = filteredGroup;
          console.log("filteredGroup", filteredGroup);
        })
        .catch((error) => {
          // alert("ไม่สามารถโหลดข้อมูลได้");
          console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
        });
    },
  },
  mounted() {
    client.info.getAllGroups
      .query({})
      .then((groups) => {
        this.items = groups;
      })
      .catch((error) => {
        // alert("ไม่สามารถโหลดข้อมูลได้");
        console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
      });

    client.info.getAllProvinces
      .query({})
      .then((data) => {
        this.provinceItems = data;
        // if (this.getUsername) {
        //   this.getUser(data);
        // }
      })
      .catch((error) => {
        // alert("ไม่สามารถโหลดข้อมูลได้");
        console.error("เกิดข้อผิดพลาดในการโหลดข้อมูล:", error);
      });
  },
};
</script>
<style>
.v-input__control {
  background: white;
}
.check-card .v-selection-control {
  align-items: center !important;
  font-size: 25px;
}
.v-pagination .v-btn {
  font-size: large;
  background-color: white;
}

/* .v-pagination .v-pagination__item .v-btn {
  display: none;
} */
.v-pagination .v-btn .pagination__prev {
  font-size: 80px;
  display: block !important;
}
.v-pagination .v-btn .pagination__next {
  display: block !important;
  font-size: 80px;
}
</style>
