<template>
  <div class="card-container">
    <el-form
      :model="addForm"
      :rules="rule"
      v-loading="loading"
      ref="addForm"
      label-width="160px"
      label-position="left">
      <div class="flexr">
        <div class="card-content flex1">
          <div class="section-title">Charge Station Information</div>
          <el-row :gutter="20">
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Charge Station ID:"
                prop="chargeBoxId"
                label-width="160px">
                <el-input
                  class="add-text"
                  v-model="addForm.chargeBoxId"
                  placeholder=""
                  maxlength="30"
                  readonly
                  v-if="isEdit"/>
                <el-input
                  class="add-text"
                  v-model="addForm.chargeBoxId"
                  placeholder=""
                  maxlength="30"
                  @blur="formatStationId"
                  v-else/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="enableEVCPID">
            <el-col :xs="24" :md="24">
              <el-form-item
                label="EVCPID:"
                prop="evcpId"
                label-width="160px">
                <el-input
                  class="add-text"
                  v-model="addForm.evcpId"
                  placeholder=""
                  maxlength="20"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="false">
            <el-col :span="24">
              <el-form-item
                label="Insert connector status after start/stop transaction">
                <el-switch v-model="addForm.insertConnectorStatusAfterTransactionMsg"/>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="section-title">Service Provider</div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item
                label="Service Provider:"
                prop="providerPk"
                label-width="160px">
                <el-select
                  class="add-text"
                  v-model="addForm.providerPk"
                  placeholder="Select">
                  <el-option
                    v-for="(item, index) in providerOptions"
                    :key="index"
                    :label="item.providerName"
                    :value="item.providerPk"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="section-title">Location of Station</div>
          <el-row :gutter="20">
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Site of Station:"
                prop="sitePk"
                label-width="160px">
                <el-select
                  class="add-text"
                  filterable
                  remote
                  v-model="addForm.sitePk"
                  :remote-method="filterSite"
                  placeholder="Select with search">
                  <el-option
                    v-for="(item, index) in siteOptions"
                    :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="24">
              <el-form-item
                label="Additional Notes:"
                label-width="160px">
                <el-input
                  class="add-text"
                  type="textarea"
                  maxlength="300"
                  :autosize="autosize"
                  v-model="addForm.note"
                  placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Lot Number:"
                label-width="160px"
                prop="lotNumber">
                <el-input
                  class="add-text"
                  maxlength="300"
                  v-model="addForm.lotNumber"
                  placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Level:"
                label-width="160px">
                <el-input
                  class="add-text"
                  maxlength="300"
                  v-model="addForm.level"
                  placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Registration Status:"
                label-width="160px"
                prop="registrationStatus">
                <el-select
                  class="add-text"
                  v-model="addForm.registrationStatus"
                  placeholder="">
                  <el-option
                    v-for="(item, index) in registerOptions"
                    :key="index"
                    :label="item"
                    :value="item"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="card-content flex1">
          <div class="section-title">Charge Station Specifications</div>
          <el-row :gutter="20">
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Endpoint Address:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.endpointAddress}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Charge Point Vendor:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.chargePointVendor}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Charge Point Serial Number:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.chargePointSerialNumber}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Charge Box Serial Number:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.chargeBoxSerialNumber}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Firmware Version:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.fwVersion}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Firmware Update Timestamp:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.fwUpdateTimestamp}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="IMSI:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.imsi}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Last Heartbeat Timestamp:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.lastHeartbeatTimestamp}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="OCPP Protocol:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.ocppProtocol}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Charge Point Model:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.chargePointModel}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="ICCID:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.iccid}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Meter Type:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.meterType}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Meter Serial Number:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.meterSerialNumber}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Diagnostics Status:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.diagnosticsStatus}}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24">
              <el-form-item
                label="Diagnostics Timestamp:"
                label-width="210px"
                class="info-item">
                <span class="info-text">{{addForm.diagnosticsTimestamp}}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="card-content flex1">
        <div class="section-title">Websocket urls</div>
        <div class="urls-group">
          <div class="urls-item" v-for="(item, index) in socketUrls" :key="index">
            <span class="urls-title">{{item.urlName + " URL:"}}</span>
            <span class="copy-url" @click="e => copyUrls(e, item.urlValue)">
              <i class="el-icon-document-copy"></i>
              {{item.urlValue}}
            </span>
          </div>
        </div>
      </div>
      <div class="card-content flex1" v-if="addForm.connectorInfo.length">
        <div class="section-title">Connector Settings</div>
        <div class="rate-list-view" v-for="(item, index) in addForm.connectorInfo" :key="index">
          <el-form-item
            label="Connector ID:"
            label-width="120px"
            :prop="'connectorInfo.' + index + '.connectorId'"
            :rules="rule.connectorInfo.connectorId">
            <el-input
              class="rate-text center"
              v-model.number="item.connectorId"
              maxlength="5"
              readonly
              placeholder=""/>
          </el-form-item>
          <el-form-item
            label="Charge Type:"
            label-width="120px"
            :prop="'connectorInfo.' + index + '.chargeTypePk'"
            :rules="rule.connectorInfo.chargeTypePk">
            <el-select
              class="rate-text"
              v-model="item.chargeTypePk"
              placeholder="">
              <el-option 
                v-for="(item, index) in chargeTypeOptions"
                :key="index"
                :label="item.chargeType"
                :value="item.chargeTypePk"/>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="card-content flexcr">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="handleClickCancleButton">
            Cancel
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            @click="handleClickConfigUpateButton">
            Save
          </el-button>
        </div>
        <div
          class="update-by"
          v-if="isEdit">
          <span
            class="add-text"
            :title='"CREATED BY " + addForm.createdBy + " ON " + addForm.createdOn'>
            LAST UPDATED BY {{addForm.updatedBy}} TIMESTAMP: {{addForm.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  //import { mapState } from 'vuex'
  import site from '../../http/api/site'
  import station from '../../http/api/charge'
  import provider from '../../http/api/provider'
  import handleClipboard from '@/utils/clipboard'
  import settings from '../../settings'
  export default {
    data() {
      return {
        loading: true,
        autosize: {
          minRows: 3,
          maxRows: 6
        },
        rule: {
          // "address": {
          //   "zipCode": {
          //     required: true,
          //     trigger: 'blur',
          //     message: 'Please type postal code'
          //   },
          //   "country": {
          //     required: true,
          //     trigger: 'change',
          //     message: 'Please select country'
          //   },
          //   "city": {
          //     required: true,
          //     trigger: 'blur',
          //     message: 'Please type city'
          //   },
          //   "street": {
          //     required: true,
          //     trigger: 'blur',
          //     message: 'Please type street'
          //   },
          //   "houseNumber": {
          //     required: true,
          //     trigger: 'blur',
          //     message: 'Please type unit number'
          //   }
          // },
          "sitePk": {
            required: true,
            trigger: 'change',
            message: 'Please select a site'
          },
          "providerPk": {
            required: true,
            trigger: 'change',
            message: 'Please select a provider'
          },
          "chargeBoxId": {
            required: true,
            trigger: 'blur',
            message: 'Please type charge station id'
          },
          "evcpId": {
            required: false,
            trigger: 'blur',
            message: 'Please type EVCPID'
          },
          "registrationStatus": {
            required: true,
            trigger: 'change',
            message: 'Please select a status'
          },
          'ocpp': [{
            required: true,
            trigger: 'blur',
            message: 'Please type ocpp',
          }, {
            pattern: /^\d{1,}(.{0,1}\d{1,})$/,
            trigger: 'blur',
            message: 'Please type a correct ocpp'
          }],
          'lotNumber': {
            pattern: /^\d+$/,
            trigger: 'blur',
            message: 'Please type a correct number'
          },
          'timeLimit': [{
            required: true,
            trigger: 'change',
          }],
          'connectorInfo': {
            'connectorPk': [{
              required: true,
              trigger: 'blur',
              message: 'Please type Connector ID',
            }],
            'chargeTypePk': [{
              required: true,
              trigger: 'blur',
              message: 'Please type Charge Type',
            }]
          }
        },
        addForm: {
          sitePk: '',
          providerPk: '',
          /*address: {
            country: '',
            city: '',
            street: '',
            zipCode: ''
          },*/
          chargeBoxId: '',
          registrationStatus: '',
          //description: '',
          //adminAddress: '',
          note: '',
          insertConnectorStatusAfterTransactionMsg: false,
          connectorInfo: [],
          //timeLimit: ''
          level: '',
          lotNumber: '',
          evcpId: ''
        },
        socketUrls: [],
        chargeTypeOptions: [],
        registerOptions: [],
        providerOptions: [],
        siteOptions: [],
        siteKeyword: '',
        defConnectorInfo: {
          connectorPk: '',
          chargeTypePk: ''
        },
        isEdit: false,
        enableEVCPID: settings.enableEVCPID
      }
    },
    created() {
      this.getRegisterOptions()
      if (this.$route.params.id) {
        this.isEdit = true;
        this.getChargeTypes();
        this.getStationInfo();
      }
    },
    methods: {
      async getChargeTypes() {
        const res = await site.getChargeTypeList()
        if (res.data && res.data.length > 0) {
          this.chargeTypeOptions = res.data
          //this.defConnectorInfo.chargeTypePk = res.data[0].chargeTypePk;
        }
      },
      async getRegisterOptions() {
        const res = await station.getRegistrationStatusList();
        if (res.data && res.data.length > 0) {
          this.registerOptions = res.data;
          if (!this.isEdit) {
            this.addForm.registrationStatus = res.data[0];
          }
        }
        this.getAllSite();
      },
      getAllSite() {
        site.getAllSiteList({siteName: this.siteKeyword}).then(res => {
          if (res.data && res.data.length > 0) {
            this.siteOptions = res.data
          }
        }).finally(() => {
          this.getAllProvider();
          this.getStationUrls();
        });
      },
      getStationInfo() {
        station.getStationInfo({chargeBoxPk: this.$route.params.id}).then(res => {
          if (res.data) {
            this.addForm = res.data
            delete this.addForm.address
          }
        }).catch(err => {
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      getStationUrls() {
        station.getStationUrls().then(res => {
          if (res.data) {
            this.socketUrls = res.data
          }
        }).catch(err => {
          this.$message({
            message: err,
            type: 'error'
          })
        })
      },
      getAllProvider() {
        provider.getAllServiceProvider().then(res => {
          if (res.data && res.data.length > 0) {
            this.providerOptions = res.data
            if (!this.isEdit) {
              this.addForm.providerPk = res.data[0].providerPk
            }
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      filterSite(word) {
        this.siteKeyword = word
        this.getAllSite();
      },
      addConnector() {
        this.addForm.connectorInfo.push(Object.assign({}, this.defConnectorInfo));
      },
      delConnector(index) {
        this.addForm.connectorInfo.splice(index, 1);
      },
      formatStationId() {
        let id = "" + this.addForm.chargeBoxId;
        id = id.toUpperCase().replace(/\s/g, "");
        this.addForm.chargeBoxId = id;
      },
      handleClickCancleButton() {
        this.loading = false;
        this.$nextTick(() => {
          this.$router.replace({
            path: "/charge-station-management/registered-charge-stations"
          })
        })
      },
      handleClickConfigUpateButton() {
        this.$refs['addForm'].validate(result => {
          if (result) {
            this.isEdit ? this.updateStation() : this.addStation();
          }
        })
      },
      addStation() {
        this.loading = true;
        station.addStation(this.addForm).then(res => {
          this.$message({
            message: 'Add station successfully',
            type: 'success'
          })
          this.handleClickCancleButton();
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      updateStation() {
        this.loading = true;
        station.updateStation(this.addForm).then(res => {
          this.$message({
            message: 'Edit station successfully',
            type: 'success'
          });
          this.handleClickCancleButton();
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        })
      },
      copyUrls(e, url) {
        handleClipboard(url, e)
      }
    }
  }
</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 {
    margin: 0 8px 16px;
    padding: 15px 50px;
    border-radius: 6px;
    background-color: white;
  }
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 15px;
    user-select: none;
    line-height: 24px;
    font-weight: 700;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100%;
    font-size: 14px;
    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: 20px -80px;
    background-color: #F0F5FC;
  }
  .rate-list-view {
    display: flex;
    flex-wrap: wrap;
    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: 15px;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 30px;
    }
  }
  .info-item {
    margin-bottom: 0;
  }
  .info-text {
    color: #888;
  }
  .urls-item {
    display: flex;
    padding: 5px 0;
    font-size: 14px;
    align-items: center;
  }
  .urls-title {
    width: 85px;
    margin-right: 10px;
    text-align: right;
    white-space: nowrap;
  }
  .copy-url {
    color: #888;
    display: flex;
    cursor: pointer;
    font-size: 14px;
    align-items: center;
    transition: all .4s;
    word-break: break-all;
  }
  .copy-url i {
    padding: 5px;
    font-size: 16px;
  }
  .copy-url:hover,
  .copy-url:active {
    color: #000;
  }
</style>
