<template>
  <div class="container" v-loading="loading">
    <el-form
      :model="form"
      :rules="rule"
      ref="form"
      label-position="right"
      label-width="150px"
      style="width: 100%;">
      <div class="content">
        <div class="section-title">Service Provider</div>
        <el-form-item
          label="Provider Name:"
          prop="providerName">
          <el-input
            class="add-text"
            maxlength="30"
            v-model="form.providerName"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="Contact Person:">
          <el-input
            class="add-text"
            maxlength="50"
            v-model="form.providerAddress"
            placeholder="Add text"/>
        </el-form-item>
        <!--el-form-item
          label="Login ID:"
          prop="loginId">
          <el-input
            class="add-text"
            maxlength="50"
            v-model="form.loginId"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="Password Set:">
          <el-input
            class="add-text"
            maxlength="50"
            v-model="form.password"
            type="password"
            placeholder="Add text"/>
        </el-form-item-->
        <el-form-item
          label="Contact Number:">
          <el-input
            class="add-text"
            maxlength="15"
            v-model="form.providerContact"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="Country:">
          <el-select
            v-model="form.countryCode"
            class="add-text"
            placeholder="">
            <el-option
              v-for="item in countryOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="Provider Logo:">
          <el-upload
            class="logo-upload"
            action
            :limit="1"
            :show-file-list="false"
            :on-remove="file => removeLogo(file)"
            :http-request="file => uploadLogo(file)"
            accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
            v-loading="uploading">
            <el-image
              v-if="logos.length > 0"
              :src="logos[0].url"
              title="Click to update logo"/>
            <i v-else
              class="el-icon-plus avatar-uploader-icon"
              title="Click to select file"/>
          </el-upload>
        </el-form-item>
      </div>
      <div class="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="onSaveClick">
            Save
          </el-button>
        </div>
        <div
          class="update-by"
          v-if="isEdit">
          <span
            class="add-text"
            :title='"CREATED BY " + form.createdBy + " ON " + form.createdOn'>
            LAST UPDATED BY {{form.updatedBy}} TIMESTAMP: {{form.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import site from '@/http/api/site'
  import {baseURL} from '../../http/http'
  import provider from '../../http/api/provider'
  import setting from '../../settings.js'
  export default {
    data() {
      return {
        loading: false,
        uploading: false,
        rule: {
          providerName: {
            required: true,
            trigger: 'blur',
            message: 'Please type provider name'
          },
          loginId: {
            required: true,
            trigger: 'blur',
            message: 'Please type login id'
          }
        },
        form: {
          loginId: '',
          password: "",
          providerName: '',
          providerAddress: '',
          providerContact: '',
          providerLogo: '',
          countryCode: setting.defaultCountry
        },
        logos: [],
        imgAddress: baseURL,
        countryOptions: [],
        isEdit: false
      }
    },
    created() {
      this.loading = true;
      this.getCountryList()
      if (this.$route.params.id) {
        this.isEdit = true;
        this.getProviderInfo()
      }
    },
    methods: {
      getCountryList() {
        site.getCountryList().then(({ data }) => {
          this.countryOptions = data
        }).finally(() => {
          this.loading = false
        })
      },
      getProviderInfo() {
        provider.getServiceProviderInfo({
          providerPk: this.$route.params.id
        }).then(res => {
          if (res.data) {
            this.form = Object.assign(this.form, res.data);
            if (this.form.providerLogo) {
              this.logos.push({
                path: this.form.providerLogo,
                url: this.imgAddress + this.form.providerLogo
              });
            }
          }
        })
      },
      uploadLogo(file) {
        this.uploading = true;
        const formData = new FormData()
        formData.append('file', file.file)
        provider.uploadLogo(formData).then(res => {
          //console.log("upload", res);
          if (this.logos.length == 0) {
            this.logos.push({
              url: ""
            })
          }
          this.logos[0] = ({
            path: res.data.picturePath,
            url: this.imgAddress + res.data.picturePath
          })
        }).catch(err => {
          this.$message({
            message: err,
            type: 'error'
          })
        }).finally(() => {
          this.uploading = false;
        })
      },
      removeLogo(file) {
        this.logos = []
        this.form.providerLogo = ""
      },
      onSaveClick() {
        this.$refs['form'].validate(result => {
          if (result) {
            if (this.logos.length > 0) {
              this.form.providerLogo = this.logos[0].path
            } else {
              this.form.providerLogo = "";
            }
            if (this.isEdit){
              this.updateProvider()
            } else {
              this.addProvider();
            }
          }
        })
      },
      addProvider() {
        this.loading = true;
        provider.addServiceProvider(this.form).then(res => {
          this.$message({
            message: 'Add service provider successfully',
            type: 'success'
          })
          this.handleClickCancleButton()
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      updateProvider() {
        this.loading = true;
        provider.updateServiceProvider(this.form).then(res => {
          this.$message({
            message: 'Update service provider successfully',
            type: 'success'
          })
          this.handleClickCancleButton()
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      handleClickCancleButton() {
        this.loading = false;
        this.$nextTick(() => {
          this.$router.replace({
            path: "/partnership-management/service-provider-management"
          })
        });
      }
    }
  }
</script>

<style scoped="scoped" lang='scss'>
  @import '../../styles/variables.scss';

  .container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  
  .content {
    margin: 0 8px 16px;
    padding: 15px 80px;
    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: bold;
    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;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  @media screen and (max-width: 500px) {
    .container {
      padding: 0px;
    }
    .content {
      padding: 15px 30px;
    }
  }
  
  .logo-upload {
    width: 148px;
    height: 148px;
    position: relative;
    ::v-deep .el-image {
      width: 148px;
      height: 148px;
      border-radius: 6px;
    }
  }
  
  .avatar-uploader-icon {
    width: 148px;
    height: 148px;
    color: #8c939d;
    cursor: pointer;
    font-size: 28px;
    text-align: center;
    line-height: 148px;
    border-radius: 6px;
    border: 1px dashed #d9d9d9;
  }
</style>
