<style scoped>
.bg-color {
  background-color: #fffbdd;
  height: 100%;
  overflow: auto;
}
table {
  min-width: 600px;
}
table thead,
tbody tr {
  border-bottom: 2px #bbbbbb solid;
}
table th,
td {
  border: 0;
  vertical-align: middle;
}
table th {
  background-color: transparent;
}
.div-box {
  background-color: #fff;
  border-radius: 1rem;
  border: 1px solid #bbbbbb;
}
.title {
  font-size: 1.5rem;
  font-weight: bold;
}
.btn {
  font-size: 1rem;
  font-weight: bold;
  border-radius: 0.5rem;
  transition: 0.3s;
  color: #fff;
}
.btn:hover {
  filter: brightness(80%);
}
.btn-record {
  background-color: #ff9100;
}
.btn-edit {
  background-color: #12a5bc;
}
.btn-cancel {
  background-color: #ff5e5e;
}
.btn-activate {
  background-color: #16a4ba;
  padding: 5px 10px;
  font-size: 1rem;
  font-weight: bold;
}
.select-text {
  font-size: 1.2rem;
  font-weight: bold;
  white-space: nowrap;
}
.form-select {
  width: auto;
}
.system-card {
  display: flex;
  overflow: auto;
}
.system-card .div-box {
  min-width: 23rem;
}
.system-card .div-box .usaged {
  display: inline-block;
  border-bottom: 1px #000 solid;
  font-size: 2rem;
  font-weight: bold;
}
.system-card .div-box .limit {
  color: #0000ff;
  font-size: 0.8rem;
  font-weight: bold;
}
.system-card .div-box .left-name {
  color: #0066ff;
  font-size: 1.1rem;
  font-weight: bold;
}
.system-card .div-box .right-date {
  color: #000;
  font-size: 0.9rem;
  font-weight: bold;
}
.system-card .div-box .box-num {
  display: flex;
  justify-content: space-between;
}
.system-card .div-box .box-none {
  font-size: 2rem;
  font-weight: bold;
  text-align: center;
}
</style>
<template>
  <div class="main-view px-4 pt-2">
    <div class="d-flex align-items-center mb-3">
      <button class="btn-goback me-2" @click="$router.back()">
        <i class="bi bi-chevron-left me-1"></i>{{ $t('global.go_back') }}
      </button>
      <nav style="--bs-breadcrumb-divider: '>'" aria-label="breadcrumb">
        <ol class="breadcrumb m-0">
          <li class="breadcrumb-item"><a href="#">{{ $t('global.homepage') }}</a></li>
          <li class="breadcrumb-item">
            <a href="javascript:;" @click="$router.back()">{{ $t('sidebar.member_service_activation') }}</a>
          </li>
          <li class="breadcrumb-item active" aria-current="page">{{ user.name }}</li>
        </ol>
      </nav>
    </div>
    <h1>{{ user.name }}</h1>
  </div>
  <div class="bg-color p-4 mt-2">
    <div class="system-card mb-3">
      <div class="div-box p-3 me-3" v-for="system in filteredUserSystemState" :key="system.id">
        <div class="d-flex justify-content-between align-items-center">
          <span class="left-name">{{ system.name }}</span>
          <span class="right-date">{{ system.expiry_date }}</span>
        </div>
        <div class="box-num mt-3" v-if="system.user_plan">
          <div
            class="flex-1 text-center"
            v-for="item in system.user_plan.items"
            :key="item.id"
          >
            <p class="usaged px-3">{{ item.usaged ?? 0 }}</p>
            <p class="limit mt-1">{{ item.item.item }} {{ item.amount }} {{ item.unit }}</p>
          </div>
        </div>
        <p class="box-none mt-3" v-else>{{ $t('backend.activate.not_activated') }}</p>
      </div>
    </div>

    <div class="div-box p-3">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <span class="title">{{ $t('backend.activate.activation_records') }}</span>
        <button
          type="button"
          class="btn btn-activate rounded mx-2"
          data-bs-toggle="modal"
          data-bs-target="#activateModal"
          @click="type = '@show'"
        >
          {{ $t('backend.activate.activation_and_renewal') }}
        </button>
      </div>
      <div class="d-inline-flex align-items-center mb-3">
        <span class="select-text w-100 pe-3">{{ $t('global.display_items') }}</span>
        <select class="form-select" v-model="selectType" @change="updateDataTableSearch">
          <option selected value="全部">{{ $t('global.all') }}</option>
          <option
            v-for="subSystem in filteredSubSystems"
            :key="subSystem.id"
            :value="subSystem.name"
          >
            {{ subSystem.name }}
          </option>
        </select>
      </div>
      <table class="table table-hover" id="table">
        <thead>
          <tr>
            <th class="text-center">{{ $t('backend.activate.system_name') }}</th>
            <th class="text-center">{{ $t('backend.activate.activation_plan') }}</th>
            <th class="text-center">{{ $t('backend.activate.activation_date') }}</th>
            <th class="text-center">{{ $t('backend.activate.duration') }}</th>
            <th class="text-center">{{ $t('backend.activate.expiration_date') }}</th>
            <th class="text-center">{{ $t('global.status') }}</th>
            <th class="text-center">{{ $t('global.operation') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="data in filteredDatas" :key="data.id">
            <td class="text-center">{{ data.subsystem.name }}</td>
            <td class="text-center">{{ data.plan_name }}</td>
            <td class="text-center">{{ data.open_date }}</td>
            <td class="text-center">{{ data.years }}年</td>
            <td class="text-center">{{ data.expiry_date }}</td>
            <td class="text-center">{{ plan_state[data.state] }}</td>
            <td class="text-end">
              <template v-if="data.state == 1 || data.state == 3">
                <router-link to=""> </router-link>
                <button class="btn btn-cancel mx-1" @click="userPlanCancel(data.id)">
                  {{ $t('global.cancel') }}
                </button>
                <button
                  type="button"
                  class="btn btn-edit mx-1"
                  data-bs-toggle="modal"
                  data-bs-target="#activateModal"
                  @click="
                    type = '@edit';
                    system_id = data.sub_system_id;
                    user_plan_id = data.id;
                  "
                >
                  {{ $t('global.edit') }}
                </button>
              </template>
              <router-link
                :to="`/activate/record/${data.id}`"
                class="btn btn-record mx-1"
              >
                {{ $t('global.record') }}
              </router-link>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div
    class="modal fade"
    id="activateModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="activateModalLabel"
    aria-hidden="true"
    data-bs-backdrop="static"
    data-bs-keyboard="false"
  >
    <div class="modal-dialog modal-xl modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-body">
          <ActivateShow
            :user_id="id"
            :system_id="system_id"
            :type="type"
            :key="type + system_id"
            v-if="type=='@show'"
          />
          <ActivateEdit
            :user_id="id"
            :user_plan_id="user_plan_id"
            :key="type + system_id + user_plan_id"
            v-if="type=='@edit'"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { api } from "@/global/axios";
import { sendSuccessSwal, sendFailedSwal, swalCancel } from "@/global/swal";
import { isAdmin, systemRole } from "@/global/request";
import ActivateShow from "./Show.vue";
import ActivateEdit from "./Edit.vue";
export default {
  components: {
    ActivateShow,
    ActivateEdit,
  },
  data() {
    return {
      id: this.$route.params.id ?? null,
      isAdmin: isAdmin(),
      systemRole: systemRole(),
      plan_state: [this.$t('global.canceled'), this.$t('global.activated'), this.$t('global.expired'), this.$t('global.pending_activation')],
      datas: [],
      user: {},
      dataTable: null,
      subSystems: [],
      selectType: "全部",
      type: "@show",
      system_id: null,
      user_plan_id: null,
      userSystemState: [],
    };
  },
  computed: {
    filteredSubSystems() {
      return this.subSystems.filter((s) => this.systemRole[s.id]) || [];;
    },
    filteredUserSystemState() {
      return this.userSystemState.filter((s) => this.systemRole[s.id]) || [];;
    },
    filteredDatas() {
      return this.datas.filter((s) => this.systemRole[s.sub_system_id]) || [];;
    },
  },
  mounted() {
    const vm = this;
    vm.fetchData().then(() => {
      vm.$nextTick(() => {
        vm.dataTable = $("#table").DataTable();
      });
    });
  },
  methods: {
    updateDataTableSearch: function () {
      const vm = this;
      $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
        const isSelectMatch = vm.selectType == "全部" || data[0].includes(vm.selectType);
        return isSelectMatch;
      });

      vm.dataTable.draw();
      $.fn.dataTable.ext.search.pop();
    },
    fetchData: async function () {
      const vm = this;
      await api
        .get(`/api/getOneUserSubSystemWithPlan/${this.id}`)
        .then((res) => {
          vm.datas = res.data.data;
          vm.user = res.data.user;
        })
        .catch(sendFailedSwal);

      await api
        .get(`/api/getSubSystemWithPlan`)
        .then((res) => {
          vm.subSystems = res.data.data;
        })
        .catch(sendFailedSwal);

      await api
        .get(`/api/getOneUserSubSystemState/${this.id}`)
        .then((res) => {
          vm.userSystemState = res.data.data;
        })
        .catch(sendFailedSwal);
    },
    userPlanCancel: function (user_plan_id) {
      swalCancel((res) => {
        if (res.value) {
          api
            .post(`/api/userPlanCancel/${user_plan_id}`)
            .then(() => {
              sendSuccessSwal(() => window.location.reload());
            })
            .catch((err) => {
              sendFailedSwal(err);
              if (err.response.status == 500)
                this.validationErrors = err.response.data.errors;
            });
        }
      });
    },
  },
};
</script>
