<style scoped>
.flex-v-center {
  display: flex;
  align-items: center;
  font-size: 1.1rem;
}
.col-form-label {
  font-weight: bold;
  font-size: 1.1rem;
  padding-top: 0;
  padding-bottom: 0;
  justify-content: end;
}
.title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #0ea1b8;
  text-align: center;
}
.border-left {
  border-left: 2px #bbbbbb solid;
}
.border-bottom {
  border-bottom: 2px #bbbbbb solid;
}
.btn {
  font-size: 1rem;
  font-weight: bold;
  transition: 0.3s;
  color: #fff;
  padding: 5px 30px;
}
.btn:hover {
  filter: brightness(80%);
}
.btn-cancel {
  background-color: #707070;
}
.btn-save {
  background-color: #0ea1b8;
}
hr {
  border: 1px #bbbbbb solid;
  opacity: 1;
}
.addon-text {
  color: #ff8114;
}
.addon-hr {
  border: 1px #ff8114 solid;
}
.topic-text {
  font-weight: bold;
  font-size: 1.1rem;
}
@media only screen and (max-width: 991px) {
  .mobile-mb {
    margin-bottom: 10px;
  }
  .col-form-label {
    justify-content: start !important;
  }
  .plan-item-name {
    flex: 1 !important;
  }
  .plan-item-amount {
    flex: 1 !important;
  }
  .value {
    justify-content: start !important;
  }
  .plan-item-name.hide {
    display: block !important;
  }
}
.plan-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 1.1rem;
}
.plan-item-name {
  flex: 2;
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: end;
  font-weight: bold;
}
.plan-item-name.hide {
  display: none;
}
.plan-item-amount {
  flex: 3;
}
.plan-item-addon {
  flex: 2;
}
.plan-item-sum {
  flex: 1;
}
.item {
  justify-content: start;
}
.value {
  justify-content: end;
}
.warning {
  font-size: 1.1rem;
  font-weight: bold;
  color: red;
  text-align: center;
}
</style>
<template>
  <p class="title">{{ $t('backend.activate.activation_and_renewal') }}</p>
  <div class="d-flex mt-3">
    <div class="flex-1">
      <div class="row gy-sm-3 m-0">
        <label for="name" class="col-md-3 col-form-label flex-v-center">{{ $t('backend.plan.select_system') }}</label>
        <div class="col-md-9 mobile-mb flex-v-center pe-5">
          <select class="form-select" v-model="sub_system_id" :disabled="type == '@edit'">
            <option disabled selected value>{{ $t('backend.plan.please_select_system') }}</option>
            <option
              v-for="subSystem in filteredSubSystems"
              :key="subSystem.id"
              :value="subSystem.id"
            >
              {{ subSystem.name }}
            </option>
          </select>
        </div>

        <template v-if="selectedSystem && type == '@show'">
          <label for="name" class="col-md-3 col-form-label flex-v-center">{{ $t('global.status') }}</label>
          <div class="col-md-9 mobile-mb flex-v-center pe-5">
            {{ checkUserSystem.user_plan_id != null ? $t('global.renew') : $t('global.activate') }}
          </div>
        </template>

        <label for="name" class="col-md-3 col-form-label d-flex pt-2">{{ $t('backend.activate.select_plan') }}</label>
        <div class="col-md-9 mobile-mb flex-column pe-5">
          <select
            class="form-select"
            v-model="data.plan_id"
          >
            <option disabled selected value>{{ $t('backend.activate.please_select_plan') }}</option>
            <option v-for="plan in filteredPlans" :key="plan.id" :value="plan.id">
              {{ plan.name }}
            </option>
          </select>
          <div class="mt-2 border-left" v-if="selectedPlan">
            <div class="flex-1"></div>
            <div class="plan-item">
              <span class="plan-item-name">{{ $t('backend.plan.plan_duration') }}：</span>
              <span class="plan-item-amount text-end">{{ selectedPlan.years }}年</span>
            </div>
            <div v-for="item in selectedPlan.items" :key="item.id" class="plan-item">
              <span class="plan-item-name">{{ item.item.item }}：</span>
              <span class="plan-item-amount text-end">{{ item.amount }}</span>
            </div>
            <div class="plan-item">
              <span class="plan-item-name">{{ $t('backend.plan.plan_price') }}：</span>
              <span class="plan-item-amount text-end text-danger fw-bold">{{ selectedPlan.price }}元</span>
            </div>
          </div>
        </div>

        <template
          v-if="selectedSystem && type == '@show' && checkUserSystem.user_plan_id != null"
        >
          <label for="name" class="col-md-3 col-form-label flex-v-center"
            >{{ $t('backend.activate.previous_expiration_date') }}</label
          >
          <div class="col-md-9 mobile-mb flex-v-center pe-5">
            {{ checkUserSystem.expiry_date }}
          </div>
        </template>

        <label for="name" class="col-md-3 col-form-label flex-v-center">{{ $t('backend.activate.activation_date') }}</label>
        <div class="col-md-9 mobile-mb flex-v-center pe-5">
          <input
            class="form-control"
            type="date"
            v-model="data.open_date"
            :min="type == '@show' && checkUserSystem.user_plan_id != null ? checkUserSystem.expiry_date : null"
          />
        </div>

        <label for="name" class="col-md-3 col-form-label flex-v-center">{{ $t('backend.activate.expiration_date') }}</label>
        <div class="col-md-9 mobile-mb flex-v-center pe-5">
          {{ selectedPlan ? data.expiry_date : "---" }}
        </div>

        <label for="name" class="col-md-3 col-form-label flex-v-center mt-4 addon-text"
          >{{ $t('backend.activate.add_on_service') }}</label
        >
        <div class="col-md-9 mobile-mb flex-v-center mt-4 pe-5">
          <hr class="w-100 addon-hr" />
        </div>
        <div class="col-md-12 mobile-mb flex-column pe-5 mt-0" v-if="selectedPlan">
          <div class="plan-item">
            <span class="plan-item-name"></span>
            <span class="plan-item-addon text-center fw-bold">
              {{ $t('global.count') }}
            </span>
            <span class="flex-v-center px-1">X</span>
            <span class="plan-item-addon text-center fw-bold">
              {{ $t('global.unit_price') }}
            </span>
            <span class="flex-v-center px-1">=</span>
            <span class="plan-item-sum flex-v-center justify-content-end fw-bold">
              {{ $t('global.price') }}
            </span>
          </div>
        </div>
        <div class="col-md-12 mobile-mb flex-column pe-5 mt-0" v-if="selectedPlan">
          <div v-for="item in selectedPlan.items" :key="item.id" class="plan-item">
            <span class="plan-item-name">{{ item.item.item }}：</span>
            <span class="plan-item-addon">
              <input
                type="number"
                class="form-control text-end"
                v-model.number="data.addon[item.item_id].amount"
                @blur="handleBlur(item.item_id)"
              />
            </span>
            <span class="flex-v-center px-1">X</span>
            <span class="plan-item-addon">
              <input
                type="number"
                class="form-control text-end"
                v-model.number="data.addon[item.item_id].price"
                @blur="handleBlur(item.item_id)"
              />
            </span>
            <span class="flex-v-center px-1">=</span>
            <span class="plan-item-sum flex-v-center justify-content-end">{{ data.addon[item.item_id].amount * data.addon[item.item_id].price }}</span>
          </div>
        </div>
        <div><hr /></div>
        <div class="col-md-12 mobile-mb flex-column pe-5">
          <div class="plan-item">
            <span class="plan-item-name"></span>
            <span class="plan-item-addon text-center fw-bold"></span>
            <span class="plan-item-addon flex-v-center justify-content-end fw-bold text-danger">
              {{ $t('backend.activate.add_on_total') }}：
            </span>
            <span class="plan-item-amount flex-v-center justify-content-end fw-bold text-danger">
              {{ addon_total }} 元
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-1 border-left">
      <div class="row gy-sm-3 m-0 ms-3">
        <div>
          <p class="topic-text text-center">{{ $t('backend.activate.detail_content') }}</p>
          <hr />
        </div>
        <label for="name" class="col-md-4 col-form-label flex-v-center item"
          >{{ $t('backend.activate.activated_system_name') }}</label
        >
        <div class="col-md-8 mobile-mb flex-v-center value">
          {{ selectedSystem ? selectedSystem.name : "---" }}
        </div>

        <label for="name" class="col-md-4 col-form-label flex-v-cente item"
          >{{ $t('backend.activate.select_activation_plan') }}</label
        >
        <div class="col-md-8 mobile-mb flex-v-center value">
          {{ selectedPlan ? selectedPlan.name : "---" }}
        </div>

        <template
          v-if="selectedSystem && type == '@show' && checkUserSystem.user_plan_id != null"
        >
          <label for="name" class="col-md-4 col-form-label flex-v-cente item"
            >{{ $t('backend.activate.previous_expiration_date') }}</label
          >
          <div class="col-md-8 mobile-mb flex-v-center value">
            {{ checkUserSystem.expiry_date }}
          </div>
        </template>

        <label for="name" class="col-md-4 col-form-label flex-v-center item"
          >{{ $t('backend.activate.activation_date') }}</label
        >
        <div class="col-md-8 mobile-mb flex-v-center value">
          {{ selectedPlan ? data.open_date : "---" }}
        </div>

        <label for="name" class="col-md-4 col-form-label flex-v-center item"
          >{{ $t('backend.plan.plan_duration') }}</label
        >
        <div class="col-md-8 mobile-mb flex-v-center value">
          {{ selectedPlan ? selectedPlan.years + "年" : "---" }}
        </div>

        <label for="name" class="col-md-4 col-form-label flex-v-center item"
          >{{ $t('backend.activate.expiration_date') }}</label
        >
        <div class="col-md-8 mobile-mb flex-v-center value">
          {{ selectedPlan ? data.expiry_date : "---" }}
        </div>

        <div><hr /></div>

        <div class="col-md-8 mobile-mb flex-column" v-if="selectedPlan">
          <p class="topic-text text-end">{{ $t('backend.activate.existing_items') }}</p>
          <div v-for="item in selectedPlan.items" :key="item.id" class="plan-item">
            <span class="plan-item-name">{{ item.item.item }}：</span>
            <span class="plan-item-amount text-end">
              {{ item.amount }}
            </span>
          </div>
        </div>
        <div class="col-md-4 mobile-mb flex-column" v-if="selectedPlan">
          <p class="topic-text text-end">{{ $t('backend.activate.add_on_items') }}</p>
          <div v-for="item in selectedPlan.items" :key="item.id" class="plan-item">
            <span class="plan-item-name hide">{{ item.item.item }}：</span>
            <span class="plan-item-amount text-end">
              {{
                data.addon[item.item_id].amount +
                (checkUserSystem.addonTotal[item.item_id]?.amount ?? 0)
              }}
            </span>
          </div>
        </div>

        <div><hr /></div>
        <div class="col-md-4"></div>
        <div class="col-md-8 mobile-mb flex-column" v-if="selectedPlan">
          <p class="topic-text text-end">{{ $t('global.total') }}</p>
          <div v-for="item in selectedPlan.items" :key="item.id" class="plan-item">
            <span class="plan-item-name">{{ item.item.item }}：</span>
            <span class="plan-item-amount text-end">
              {{ data.total[item.item_id].amount }}
            </span>
          </div>
        </div>

        <div><hr /></div>
        <div class="col-md-4"></div>
        <div class="col-md-8 mobile-mb flex-column">
          <div class="plan-item">
            <span class="plan-item-name text-danger">{{ $t('global.total_amount') }}：</span>
            <span class="plan-item-amount text-end text-danger fw-bold">
              {{ price_total }} 元
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="text-center mt-3">
    <button
      type="button"
      class="btn btn-cancel rounded-pill mx-2"
      data-bs-dismiss="modal"
    >
      {{ $t('global.cancel') }}
    </button>
    <button type="submit" class="btn btn-save rounded-pill mx-2" @click="saveData">
      {{ $t('global.save') }}
    </button>
  </div>
</template>
<script>
import { api } from "@/global/axios";
import { sendSuccessSwal, sendFailedSwal, swalWarning } from "@/global/swal";
import { systemRole } from "@/global/request";
export default {
  props: ["user_id", "type", "system_id"],
  data() {
    return {
      systemRole: systemRole(),
      subSystems: [],
      sub_system_id: "",
      data: {
        user_id: this.user_id,
        plan_id: "",
        open_date: new Date().toISOString().slice(0, 10),
        expiry_date: "",
        plan: {},
        addon: {},
        total: {},
        type: 0,
        state: 1,
        user_plan_id: null,
      },
      userSystemState: [],
      checkUserSystem: {},
      addon_total: "",
      price_total: "",
    };
  },
  computed: {
    filteredSubSystems() {
      return this.subSystems.filter((s) => this.systemRole[s.id]) || [];;
    },
    selectedSystem() {
      return this.subSystems.find((s) => s.id === this.sub_system_id) || null;
    },
    filteredPlans() {
      const system = this.subSystems.find((s) => s.id === this.sub_system_id);
      return system ? system.plans : [];
    },
    selectedPlan() {
      if (this.data.plan_id === 0 || this.sub_system_id === 0) {
        return null;
      }
      for (const system of this.subSystems) {
        const plan = system.plans.find((p) => p.id === this.data.plan_id);
        if (plan) return plan;
      }
      return null;
    },
  },
  watch: {
    sub_system_id(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.data.plan_id = "";

        this.checkUserSystem = this.userSystemState.find(
          (s) => s.id === this.sub_system_id
        );

        this.data.plan_id = this.checkUserSystem.plan_id ?? "";
        if (this.type == "@edit") {
          this.data.type = 2;
          this.data.user_plan_id = this.checkUserSystem.user_plan_id;
          this.data.open_date = new Date(this.checkUserSystem.open_date)
            .toISOString()
            .slice(0, 10);
        } else {
          this.data.type = 0;
          this.data.state = 1;
          if (this.checkUserSystem.user_plan_id != null) {
            this.data.type = 3;
            this.data.state = 3;
            this.data.user_plan_id = this.checkUserSystem.user_plan_id;
            this.data.open_date = new Date(this.checkUserSystem.expiry_date)
              .toISOString()
              .slice(0, 10);
          }
        }
      }
    },
    selectedPlan(newPlan) {
      if (newPlan && newPlan.items) {
        this.data.addon = {};
        this.data.total = {};
        this.data.plan = newPlan;
        newPlan.items.forEach((item) => {
          this.data.addon[item.item_id] = {
            id: item.item_id,
            amount: 0,
            price: 0,
          };
          this.data.total[item.item_id] = {
            id: item.item_id,
            amount: item.amount,
            price: 0,
          };
        });
      }
    },
    "data.plan_id"(newVal) {
      if (newVal) {
        this.calculateExpiryDate();
      }
    },
    "data.open_date"() {
      if (this.data.plan_id) {
        this.calculateExpiryDate();
      }
    },
    "data.addon": {
      handler(newAddon) {
        let sum = 0;
        for (const id in newAddon) {
          if (newAddon.hasOwnProperty(id)) {
            const addonAmount = newAddon[id];
            const beforeAddonAmount = this.checkUserSystem.addonTotal[id];
            const baseAmount = this.selectedPlan.items.find(
              (item) => item.item_id === parseInt(id)
            );

            sum += addonAmount.amount * addonAmount.price;

            this.data.total[id] = {
              id: addonAmount.id,
              amount:
                Number(baseAmount.amount) +
                Number(addonAmount.amount) +
                (beforeAddonAmount?.amount ?? 0),
            };
          }
        }
        this.addon_total = sum;
        this.price_total = sum + this.selectedPlan.price;
      },
      deep: true,
    },
  },
  mounted() {
    const vm = this;
    vm.fetchData();
  },
  methods: {
    handleBlur(itemId) {
      if (this.data.addon[itemId].amount === "") {
        this.data.addon[itemId].amount = 0;
      }
      if (this.data.addon[itemId].price === "") {
        this.data.addon[itemId].price = 0;
      }
    },
    fetchData: async function () {
      const vm = this;
      await api
        .get(`/api/getSubSystemWithPlan`)
        .then((res) => {
          vm.subSystems = res.data.data;
        })
        .catch(sendFailedSwal);

      await api
        .get(`/api/getOneUserSubSystemState/${this.user_id}`)
        .then((res) => {
          vm.userSystemState = res.data.data;
        })
        .catch(sendFailedSwal);

      vm.sub_system_id = vm.type == "@edit" ? vm.system_id : "";
    },
    calculateExpiryDate: function () {
      let date = new Date(this.data.open_date);
      date.setFullYear(date.getFullYear() + this.selectedPlan.years);
      this.data.expiry_date = date.toISOString().slice(0, 10);
    },
    saveData: function () {
      if (this.data.plan_id == "" || this.data.plan_id == null) {
        swalWarning("尚未選擇方案！");
        return;
      }
      api
        .post(`/api/userPlanActivate`, this.data)
        .then(() => {
          sendSuccessSwal(() => window.location.reload());
        })
        .catch((err) => {
          sendFailedSwal(err);
          if (err.response.status == 500)
            this.validationErrors = err.response.data.errors;
        });
    },
  },
};
</script>
