<template>
  <div class="view-container">
    <div class="view-content" v-loading="loading">
      <el-form
        ref="userRef"
        :model="userModel"
        :rules="rules"
        label-width="140px"
        label-position="left">
        <div class="section-title">
          Profile
        </div>
        <el-row>
          <el-col :xs="24" :md="12">
            <el-form-item
              prop='profile.nickName'
              label="Display Name:">
              <el-input
                class="input-text"
                v-model="userModel.profile.nickName"
              />
            </el-form-item>
            <el-form-item
              label="Email Address:"
              prop="profile.email"
            >
              <el-input
                class="input-text"
                v-model="userModel.profile.email" />
            </el-form-item>
            <el-form-item
              label="Phone Number:"
              prop="profile.phoneNumber"
            >
              <div style="display: flex;">
                <el-select
                  v-model="userModel.profile.areaCode"
                  class="area-code">
                  <el-option
                    v-for="areaCode in areaCodeOptions"
                    :label="'+'+areaCode.callingCode"
                    :value="areaCode.callingCode"
                    :key="areaCode.callingCode" />
                </el-select>
                <el-input
                  class="phone-number"
                  v-model="userModel.profile.phoneNumber" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12" v-if="isEdit">
            <el-form-item
              label="Charging History:">
              <div class="flexc">
                <el-input
                  class="input-text input-text-1"
                  v-model="userInfo.chargingCount"
                  readonly
                />
                <el-button
                  type="primary"
                  @click="toHistoryCharge">
                  VIEW HISTORY
                </el-button>
              </div>
            </el-form-item>
            <el-form-item
              label="Top-up History:">
              <div class="flexc">
                <el-input
                  class="input-text input-text-1"
                  v-model="userInfo.topUpCount"
                  readonly
                />
                <el-button
                  type="primary"
                  @click="toHistoryTopup">
                  VIEW HISTORY
                </el-button>
              </div>
            </el-form-item>
            <el-form-item
              label="Credit Amount:">
              <div class="flexc">
                <el-input
                  class="input-text input-text-1"
                  :value="userInfo.currencySymbol + ' ' + userInfo.credit"
                  readonly
                />
                <el-button
                  type="success"
                  @click="showTopupModal">
                  TOP UP
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="sparator" ></div>
        <div class="section-title">
          Address
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Country:">
              <el-select
                v-model="userModel.address.country"
                class="input-text">
                <el-option
                  v-for="item in countryOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Street:"
            >
              <el-input
                class="input-text"
                v-model="userModel.address.street" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="City:"
            >
              <el-input
                class="input-text"
                v-model="userModel.address.city" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Postal Code:"
            >
              <el-input
                class="input-text"
                v-model="userModel.address.zipCode" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="sparator" ></div>
        <div class="section-title">
          Vehicle
        </div>
        <div
          class="vehicle-list-view-item"
          v-for="(vehicle, index) in userModel.vehicleList"
          :key="vehicle.vehiclePk">
          <el-form-item
            label-width="60px"
            label="Brand:"
          >
            <el-input
              class="vehicle-input"
              v-model="vehicle.brand" />
          </el-form-item>
          <el-form-item
            label-width="60px"
            label="Model:"
          >
            <el-input
              class="vehicle-input"
              v-model="vehicle.model" />
          </el-form-item>
          <el-form-item
            label-width="120px"
            label="License Plate:"
          >
            <el-input
              class="vehicle-input"
              v-model="vehicle.licensePlate" />
          </el-form-item>
          <div>
            <img
              class="list-item-icon"
              @click="handleClickSubVehicleButton(vehicle, index)"
              src="../../assets/form-list-sub.png"/>
            <img
              v-if="index === userModel.vehicleList.length - 1"
              class="list-item-icon"
              @click="handleClickAddVehicleButton"
              src="../../assets/form-list-add.png"/>
          </div>
          
        </div>

        <div class="sparator" style="margin: 10px -80px;"></div>
        <div class="buttons">
          <el-button
            class="cancel-button"
            type="primary"
            @click="handleClickCancleButton">
              Cancel
          </el-button>
          <el-button
            class="confirm-button"
            type="primary"
            @click="handleClickConfirmButton">
              Save
          </el-button>
        </div>
      </el-form>
    </div>
    <TopUp
      :visible="showTopup"
      :userInfo="userInfo"
      @hide="hideTopupModal"
      @success="hideTopupModal(true)"/>
  </div>
</template>

<script>
import {
  deleteUserVehicle,
  getUser,
  updateUser,
  addUser,
} from '@/http/api/userManagement'
import { mapState } from 'vuex'
import site from '../../http/api/site'
import {getCountryList} from '../../utils/index.js'
import TopUp from './views/TopUp.vue'
import settings from '../../settings.js'
export default {
  name: 'UserDetial',
  computed: {
    ...mapState('userManagement', ['selectedUser']),
  },
  components: {TopUp},
  data() {
    return {
      loading: false,
      countryOptions: [],
      areaCodeOptions: [],
      userInfo: {
        credit: 0,
        currencySymbol: "$"
      },
      userModel: {
        profile: {
          userPk: '',
          nickName: '',
          email: '',
          areaCode: settings.defaultCalling,
          hasAreaCode: false,
          phoneNumber: '',
        },
        address: {
          zipCode: '',
          street: '',
          city: '',
          country: settings.defaultCountry,
          addressPk: '',
        },
        vehicleList: [],
      },
      rules: {
        profile: {
          nickName: [
            {
              required: true,
              trigger: 'blur',
              message: 'Display Name is required',
            },
          ],
          email: [
            {
              required: true,
              trigger: 'blur',
              message: 'Email is required',
            },
          ],
          phoneNumber: [
            {
              required: true,
              trigger: 'blur',
              message: 'Phone Number is required',
            },
          ],
        },
        address: {
          zipCode: [{
            required: true,
            trigger: 'blur',
            message: 'Postal Code is required',
          }],
          street: [{
            required: true,
            trigger: 'blur',
            message: 'Street is required',
          }],
          city: [{
            required: true,
            trigger: 'blur',
            message: 'City is required',
          }],
          country: [{
            required: true,
            trigger: 'blur',
            message: 'Country is required',
          }],
        },
        vehicle: {
          brand: [{
            required: true,
            trigger: 'blur',
            message: 'Brand is required',
          }],
          model: [{
            required: true,
            trigger: 'blur',
            message: 'Model is required',
          }],
          licensePlate: [{
            required: true,
            trigger: 'blur',
            message: 'License Plate is required',
          }],
        }
      },
      isEdit: false,
      showTopup: false
    }
  },
  mounted() {
    this.getCountryList()
    if (this.$route.params.id) {
      this.isEdit = true;
      this.getUserInfo()
    } else {
      this.userModel.profile.hasAreaCode = true
      this.userModel.vehicleList.push({
        brand: '',
        model: '',
        licensePlate: '',
      })
    }
  },
  beforeRouteLeave(to, form, next) {
    this.$store.commit('userManagement/RESET_SELECTED_USER')
    next()
  },
  methods: {
    handleClickSubVehicleButton(vehicle, index) {
      const callback = () => {
        this.userModel.vehicleList.splice(index, 1)
        if (this.userModel.vehicleList.length === 0) {
          this.userModel.vehicleList.push({
            brand: '',
            model: '',
            licensePlate: '',
          })
        }
      }
      this.$confirm(
        "Are you sure you want to delete this vehicle ?",
        "Delete",
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning'
        },
      ).then(() => {
        this.loading = true
        if (vehicle.vehiclePk) {
          deleteUserVehicle(vehicle.vehiclePk)
            .then(() => {
              callback()
            }).catch((error) => {
              this.$message({
                message: error,
                type: 'error',
              })
            }).finally(() => {
              this.loading = false
            })
        } else {
          callback()
          this.loading = false
        }
      })
    },
    handleClickAddVehicleButton() {
      this.userModel.vehicleList.push({
        brand: '',
        model: '',
        licensePlate: '',
      })
    },
    handleClickCancleButton() {
      this.$router.go(-1)
    },
    handleClickConfirmButton() {
      this.$refs.userRef.validate((valid) => {
        if (valid) {
          //const phone = this.getPhone()

          const params = {
            userPk: this.userModel.profile.userPk,
            nickName: this.userModel.profile.nickName,
            email: this.userModel.profile.email,
            phone: this.userModel.profile.phoneNumber,
            callingCode: this.userModel.profile.areaCode,
            address: this.userModel.address,
            userVehicleRequests: [...this.userModel.vehicleList.filter(vehicle =>
              (vehicle.brand && vehicle.model && vehicle.licensePlate))],
            // ocppTagRequest: this.userModel.ocppTagResponse,
          }
          if (this.isEdit) {
            this.updateUser(params)
          } else {
            this.addUser(params);
          }
        }
      })
    },
    updateUser(params) {
      this.loading = true
      updateUser(params).then(() => {
        this.$message({
          message: 'Update User successfully',
          type: 'success'
        })
        this.$router.go(-1)
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error'
        })
      }).finally(() => {
        this.loading = false
      })
    },
    addUser(params) {
      this.loading = true
      addUser(params).then(() => {
        this.$message({
          message: 'Update User successfully',
          type: 'success'
        })
        this.$router.go(-1)
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error'
        })
      }).finally(() => {
        this.loading = false
      })
    },
    getCountryList() {
      site.getCountryList().then(({ data }) => {
        this.countryOptions.push(...data)
        if (!this.selectedUser.userId
          && this.countryOptions
          && this.countryOptions.length > 0) {
          this.userModel.address.country = this.countryOptions[0].value
        }
      })
      getCountryList(list => {
        this.areaCodeOptions = list
      })
    },
    getPhone() {
      const {areaCode, phoneNumber, hasAreaCode} = this.userModel.profile
      if (hasAreaCode) {
        return areaCode + phoneNumber
      }
      return phoneNumber
    },
    /*getPhoneNumber(phone) {
      if (phone.startsWith(AREA_CODE)) {
        this.userModel.profile.hasAreaCode = true
        return phone.substring(AREA_CODE.length)
      }
      return phone
    },*/
    getUserInfo() {
      getUser(this.$route.params.id)
      .then(({ data }) => {
        const {
          userPk,
          nickName,
          email,
          phone,
          callingCode,
          ocppTagResponse,
          address,
          countryCode,
          userVehicleResponses,
        } = data
        this.userModel.profile.nickName = nickName
        this.userModel.profile.email = email
        this.userModel.profile.areaCode = callingCode + ""
        this.userModel.profile.phoneNumber = phone //this.getPhoneNumber(phone)
        this.userModel.profile.userPk = userPk
        this.userInfo = data;

        this.userModel.address = address || {}
        if (!this.userModel.address.country) {
          this.userModel.address.country = countryCode || "SG"
        }

        // this.userModel.vehicleList = userVehicleResponses || []

        const vehicleList = userVehicleResponses || []
        this.userModel.vehicleList = [
          ...vehicleList,
          {
            brand: '',
            model: '',
            licensePlate: '',
          },
        ]

        this.userModel.ocppTagResponse = ocppTagResponse
      })
    },
    showTopupModal() {
      this.showTopup = true
    },
    hideTopupModal(success) {
      this.showTopup = false;
      if (success) {
        this.getUserInfo()
      }
    },
    toHistoryCharge() {
      this.$router.push("/user-management/charging-history/" + this.$route.params.id)
    },
    toHistoryTopup() {
      this.$router.push("/user-management/topup-history/" + this.$route.params.id)
    }
  }
}
</script>

<style scoped lang='scss'>
  @import '../../styles/element-ui.scss';
  @import '../../styles/variables.scss';

  .view-container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }

  .view-content {
    padding: 15px 80px;
    border-radius: 6px;
    background-color: white;
  }

  .sparator {
    margin: 10px -40px;
    height: 2px;
    background-color: #F0F5FC;
  }

  .section-title {
    color: #333333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 16px;
    line-height: 24px;
    font-weight: 500;
    font-family: sans-serif;
    text-transform: uppercase;
  }

  .input-text {
    width: 100%;
    max-width: 300px;
  }
  
  .input-text-1 {
    flex: 1;
    margin-right: 10px;
  }

  .area-code {
    width: 80px;
    margin-right: 10px;
  }

  .phone-number {
    width: 100%;
    max-width: 210px;
  }

  .vehicle-list-view-item {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }

  .vehicle-input {
    max-width: 150px;
    padding-right: 14px;
  }

  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0 10px 22px;
  }

  .cancel-button {
    width: 94px;
    height: 40px;
  }

  .confirm-button {
    width: 94px;
    height: 40px;
    margin-left: 20px;
    background: $--color-primary;
    border: 1px solid $--color-primary;
    box-sizing: border-box;
    border-radius: 4px;
  }

</style>