<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;
}
.title {
  font-size: 1.2rem;
  font-weight: bold;
  line-height: 0.5;
}
.title::before {
  display: flex;
  align-items: baseline;
  content: "\2022";
  margin-right: 8px;
  color: #0ea1b8;
  font-size: 3rem;
}
.btn-save {
  background-color: #0071b3;
}
@media only screen and (max-width: 991px) {
  .mobile-mb {
    margin-bottom: 10px;
  }
}
.text {
  color: #000;
  font-size: 1rem;
  font-weight: bold;
}
</style>
<template>
  <form @submit.prevent="saveData">
    <div class="container-fluid">
      <div class="mb-3" v-if="Object.keys(validationErrors).length > 0">
        <div class="alert alert-danger">
          <ul class="mb-0">
            <li class="text" v-for="(value, key) in validationErrors" :key="key">
              {{ value[0] }}
            </li>
          </ul>
        </div>
      </div>
      <div class="row gy-sm-3 mb-2">
        <label for="newsDate" class="col-md-2 col-form-label flex-v-center">{{ $t('backend.plan.select_system') }}：</label>
        <div class="col-md-10 mobile-mb flex-v-center">
          <select class="form-select" v-model="plan.sub_system_id" required>
            <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>
        <label class="col-md-2 col-form-label flex-v-center">{{ $t('backend.plan.plan_name') }}：</label>
        <div class="col-md-10 mobile-mb flex-v-center">
          <input
            type="text"
            class="form-control"
            v-model="plan.name"
            required
          />
        </div>
        <label class="col-md-2 col-form-label flex-v-center">{{ $t('backend.plan.plan_duration') }}：</label>
        <div class="col-md-10 mobile-mb flex-v-center">
          <input
            type="number"
            class="form-control"
            v-model.number="plan.years"
            required
          />
        </div>
        <label class="col-md-2 col-form-label flex-v-center">{{ $t('backend.plan.plan_price') }}：</label>
        <div class="col-md-10 mobile-mb flex-v-center">
          <input
            type="number"
            class="form-control"
            v-model.number="plan.price"
            required
          />
        </div>
        <div><hr /></div>
        <!-- 這邊要加迴圈顯示item & amount -->
        <template v-for="item in selectedSystem?.items" :key="item.id">
          <label class="col-md-2 col-form-label flex-v-center">{{ item.item }}</label>
          <div class="col-md-10 mobile-mb flex-v-center">
            <input
              type="number"
              class="form-control"
              v-model="plan.items.find((s) => s.id == item.id).amount"
            />
          </div>
        </template>
      </div>
    </div>
    <div class="modal-footer pb-0">
      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ $t('global.cancel') }}</button>
      <button type="submit" class="btn btn-primary btn-save">{{ $t('global.save') }}</button>
    </div>
  </form>
</template>
<script>
import { api } from "@/global/axios";
import { sendSuccessSwal, sendFailedSwal } from "@/global/swal";
import { isAuthenticated, systemRole } from "@/global/request";
export default {
  data() {
    return {
      subSystems: [],
      plan: {
        sub_system_id: "",
        name: "",
        years: "",
        price: "",
        items: []
      },
      validationErrors: {},
      isAuthenticated: isAuthenticated(),
      systemRole: systemRole(),
    };
  },
  computed: {
    filteredSubSystems() {
      return this.subSystems.filter((s) => this.systemRole[s.id]) || [];
    },
    selectedSystem() {
      return this.subSystems.find((s) => s.id === this.plan.sub_system_id) || null;
    },
  },
  watch: {
    selectedSystem(newSystem, oldSystem) {
      if (newSystem) {
        this.plan.items = newSystem.items.map(item => ({
          id: item.id,
          amount: 0,
        }));
      }
    },
  },
  mounted() {
    const vm = this;
    vm.fetchData();
  },
  methods: {
    fetchData: async function () {
      const vm = this;
      await api
        .get(`/api/getSubSystemWithItem`)
        .then((res) => {
          vm.subSystems = res.data.data;
        })
        .catch(sendFailedSwal);
    },
    saveData: function () {
      api
        .post(`/api/plan`, this.plan)
        .then(() => {
          sendSuccessSwal(() => window.location.reload());
        })
        .catch((err) => {
          sendFailedSwal(err);
          if (err.response.status == 500)
            this.validationErrors = err.response.data.errors;
        });
    },
  },
};
</script>