<template>
  <div class="card-container">
    <div class="card-content">
      <el-form
        :model="form"
        :rules="rule"
        v-loading="loading"
        ref="addForm"
        label-position="right"
        label-width="180px">
        <div class="section-title" v-if="isEdit">Edit device</div>
        <div class="section-title" v-else>Add device</div>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Device Serial Number"
              prop="deviceSerialNo">
              <el-input
                class="add-text"
                v-model="form.deviceSerialNo"
                placeholder="Add text"
                maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Status"
              prop="deviceStatus">
              <el-select
                class="add-text"
                v-model="form.deviceStatus"
                placeholder="Select">
                <el-option
                  v-for="(item, index) in statusOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Site"
              prop="sitePk">
              <el-select
                class="add-text"
                v-model="form.sitePk"
                placeholder="Select"
                @change="getStationOptions()"
                filterable>
                <el-option
                  v-for="(item, index) in siteList"
                  :key="index"
                  :label="item.siteName"
                  :value="item.sitePk"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Station ID"
              prop="chargeBoxPk">
              <el-select
                class="add-text"
                v-model="form.chargeBoxPk"
                placeholder="Select"
                multiple
                v-loading="loadingBox">
                <el-option
                  v-for="(item, index) in stationList"
                  :key="index"
                  :label="item.chargeBoxId"
                  :value="item.chargeBoxPk"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="showProvider">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Service Provider"
              prop="providerPk">
              <el-select
                class="add-text"
                v-model="form.providerPk"
                placeholder="Select">
                <el-option
                  v-for="(item, index) in providerList"
                  :key="index"
                  :label="item.providerName"
                  :value="item.providerPk"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="hr-full"/>
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="handleClickCancleButton">
            Cancel
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            @click="handleClickSaveButton">
            Save
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import api from '../../http/api/posDevices.js'
import sp from '../../http/api/provider.js'
export default {
  data() {
    return {
      loading: false,
      loadingBox: false,
      showProvider: false,
      form: {
        deviceSerialNo: '',
        sitePk: '',
        providerPk: '',
        chargeBoxPk: [],
        deviceStatus: 'A'
      },
      rule: {
        deviceSerialNo: {
          required: true,
          trigger: 'blur',
          message: 'Please input device serial no'
        },
        sitePk: {
          required: true,
          trigger: 'change',
          message: 'Please select a site'
        },
        chargeBoxPk: {
          required: true,
          trigger: 'change',
          message: 'Please select at least one station'
        },
        providerPk: {
          required: true,
          trigger: 'change',
          message: 'Please select service provider'
        },
        deviceStatus: {
          required: true,
          trigger: 'change',
          message: 'Please select a status'
        }
      },
      siteList: [],
      stationList: [],
      providerList: [],
      statusOptions: [{
        name: 'Active',
        value: 'A'
      },{
        name: 'Inactive',
        value: 'I'
      }],
      isEdit: false
    }
  },
  async created() {
    this.loading = true;
    if (this.$route.params.deviceId) {
      this.isEdit = true;
      this.getSiteOptions()
      this.getProviderOptions()
      await this.getDetails(this.$route.params.deviceId)
    } else {
      this.getProviderOptions()
      await this.getSiteOptions()
    }
  },
  methods: {
    getDetails(deviceId) {
      this.loadingBox = true
      api.getPosDevice({
        deviceId: deviceId
      }).then(res => {
        if (res.data) {
          this.form = res.data
          if (this.form.sitePk) {
            this.getStationOptions(true)
          }
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    async getProviderOptions() {
      try {
        const res = await sp.getAllServiceProvider();
        if (res.data && res.data.length > 0) {
          this.providerList = res.data
        }
      } catch(e) {
        this.providerList = []
      }
    },
    getSiteOptions() {
      api.getSiteList().then(res => {
        if (res.data) {
          this.siteList = res.data
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.loading = false;
      });
    },
    getStationOptions(keep) {
      this.loadingBox = true
      if (!keep) {
        this.form.chargeBoxPk = ''
        setTimeout(() => {
          this.$refs['addForm'].clearValidate('chargeBoxPk')
        }, 10)
      }
      api.getStationBySite({
        sitePk: this.form.sitePk
      }).then(res => {
        this.loadingBox = false
        if (res.data) {
          this.stationList = res.data
        } else {
          this.stationList = []
        }
      }).catch(err => {
        this.loadingBox = false
        this.$message({
          message: err,
          type: 'error'
        })
        this.stationList = []
      });
    },
    addDevice() {
      this.loading = true;
      api.addPosDevice(this.form).then(res => {
        this.loading = false;
        this.$message({
          message: 'Add device successfully!',
          type: 'success'
        });
        setTimeout(() => {
          this.handleClickCancleButton()
        }, 500);
      }).catch(err => {
        this.loading = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    editDevice() {
      this.loading = true;
      api.editPosDevice(this.form).then(res => {
        this.loading = false;
        this.$message({
          message: 'Update device successfully!',
          type: 'success'
        });
        setTimeout(() => {
          this.handleClickCancleButton()
        }, 500);
      }).catch(err => {
        this.loading = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    handleClickCancleButton() {
      this.$nextTick(() => {
        this.$router.replace({
          path: '/pos-device-management'
        });
      })
    },
    handleClickSaveButton() {
      this.$refs['addForm'].validate(result => {
        if (result) {
          if (this.isEdit) {
            this.editDevice()
          } else {
            this.addDevice()
          }
        }
      })
    }
  }
}
</script>

<style scoped="scoped" lang='scss'>
  @import '../../styles/variables.scss';
  
  .card-container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  .card-content {
    padding: 15px 80px;
    border-radius: 6px;
    background-color: white;
  }
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 16px;
    user-select: none;
    line-height: 24px;
    font-weight: 500;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100%;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .hr-full {
    height: 2px;
    margin: 80px -80px 30px;
    background-color: #F0F5FC;
  }
  .rate-list-view {
    display: flex;
    align-items: center;
  }
  .rate-text {
    max-width: 150px;
    padding-right: 14px;
  }
  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0 10px 22px;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 30px;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 30px;
    }
  }
  .item-unit {
    top: 12px;
    left: -40px;
    font-size: 12px;
    user-select: none;
    position: absolute;
  }
</style>
