<template>
  <div class="container" v-loading="loading.page">
    <el-form
      :model="form"
      :rules="rule"
      ref="form"
      label-position="right"
      label-width="150px"
      style="width: 100%;">
      <div class="flexr">
        <div class="content flex1">
          <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"/>
          </el-form-item>
          <el-form-item
            label="Country:"
            prop="countryCode">
            <el-select
              v-model="form.countryCode"
              class="add-text">
              <el-option
                v-for="item in options.country"
                :key="item.countryCode"
                :label="item.countryName"
                :value="item.countryCode"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="Party ID:"
            prop="partyId">
            <el-input
              class="add-text"
              maxlength="3"
              v-model="form.partyId"
              @blur="changePartyId"/>
          </el-form-item>
          <el-form-item
            label="Contact Person:"
            prop="providerContactPerson">
            <el-input
              class="add-text"
              maxlength="50"
              v-model="form.providerContactPerson"/>
          </el-form-item>
          <el-form-item
            label="Contact Number:"
            prop="providerContactPhoneNumber">
            <div class="add-text flexc">
              <el-select
                style="min-width: 75px; max-width: 80px;"
                v-model="form.providerContactCallingCode">
                <el-option
                  v-for="item in options.country"
                  :key="item.callingCode"
                  :label="'+' + item.callingCode"
                  :value="item.callingCode"/>
              </el-select>
              <el-input
                v-model="form.providerContactPhoneNumber"
                style="margin-left: 10px;"
                maxlength="15"/>
            </div>
          </el-form-item>
          <el-form-item
            label="Payment Gateway:"
            prop="paymentGateway">
            <el-select
              v-model="form.paymentGateway"
              class="add-text">
              <el-option
                v-for="item in options.payment"
                :key="item.key"
                :label="item.value"
                :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="Provider Logo:"
            class="is-required">
            <el-upload
              class="logo-upload"
              action
              :limit="1"
              :show-file-list="false"
              :file-list="[]"
              :on-remove="file => removeLogo(file)"
              :http-request="file => uploadLogo(file)"
              accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
              v-loading="loading.upload">
              <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 flex1">
          <div class="section-title">Company Details</div>
          <el-form-item
            label="Company Name:"
            prop="company.companyName">
            <el-input
              class="add-text"
              maxlength="50"
              v-model="form.company.companyName"/>
          </el-form-item>
          <el-form-item
            label="Company UEN:"
            prop="company.companyUen">
            <el-input
              class="add-text"
              maxlength="15"
              v-model="form.company.companyUen"/>
          </el-form-item>
          <el-form-item
            label="Company Email:"
            prop="company.companyEmail">
            <el-input
              class="add-text"
              maxlength="50"
              v-model="form.company.companyEmail"/>
          </el-form-item>
          <el-form-item
            label="Company Website:"
            prop="company.companyWebsit">
            <el-input
              class="add-text"
              maxlength="50"
              v-model="form.company.companyWebsit"/>
          </el-form-item>
          <el-form-item
            label="Company Address:"
            prop="company.companyAddress">
            <el-input
              class="add-text"
              maxlength="100"
              v-model="form.company.companyAddress"
              type="textarea"
              :autosize="autoSize"/>
          </el-form-item>
        </div>
      </div>
      <div class="content flexcr">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="onBack">
            Cancel
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            :loading="loading.saving"
            @click="onClickSave">
            &nbsp;Save&nbsp;
          </el-button>
        </div>
        <audit-view :audit="form.audit"/>
      </div>
    </el-form>
  </div>
</template>

<script>
import setting from '../../settings.js';
import apiBase from '../../api/apiBase.js';
import provider from '../../api/provider.js';
import AuditView from "@/components/AuditView"
export default {
  data() {
    return {
      isEdit: false,
      loading: {
        page: true,
        upload: false,
        saving: false
      },
      options: {
        country: [],
        payment: []
      },
      form: {
        partyId: "",
        providerPk: "",
        providerName: "",
        countryCode: setting.defaultCountry,
        providerLogo: "",
        paymentGateway: "",
        providerContactPerson: "",
        providerContactCallingCode: Number(setting.defaultCalling),
        providerContactPhoneNumber: "",
        company: {
          companyUen: "",
          companyName: "",
          companyEmail: "",
          companyWebsit: "",
          companyAddress: "",
          providerCompanyPk: ""
        }
      },
      rule: {
        providerName: {
          required: true,
          trigger: 'blur',
          message: 'Please type provider name'
        },
        countryCode: {
          required: true,
          trigger: 'change',
          message: 'Please select country'
        },
        paymentGateway: {
          required: true,
          trigger: 'change',
          message: 'Please select payment gateway'
        },
        providerContactPerson: {
          required: true,
          trigger: 'blur',
          message: 'Please type contact person'
        },
        providerContactPhoneNumber: {
          required: true,
          trigger: 'blur',
          message: 'Please type contact number'
        },
        partyId: {
          required: true,
          trigger: 'blur',
          message: 'Please type party Id'
        },
        "company.companyName": {
          required: true,
          trigger: 'blur',
          message: 'Please type company name'
        },
        "company.companyUen": {
          required: true,
          trigger: 'blur',
          message: 'Please type company UEN'
        },
        "company.companyAddress": {
          required: true,
          trigger: 'blur',
          message: 'Please type company address'
        }
      },
      logos: [],
      autoSize: {
        minRows: 3,
        maxRows: 8
      }
    };
  },
  components: {AuditView},
  created() {
    if (this.$route.params.id) {
      this.isEdit = true;
      this.getProviderInfo();
    }
    this.getCountryOptions();
  },
  methods: {
    onBack() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/partnership-management/service-provider-mgmt"
        })
      })
    },
    getCountryOptions() {
      apiBase.getCountryList().then(res => {
        if (res.data) {
          this.options.country = res.data
        }
      }).finally(() => {
        this.getPaymentOptions();
      })
    },
    getPaymentOptions() {
      apiBase.getPaymentGatewayList().then(res => {
        if (res.data) {
          this.options.payment = res.data
        }
      }).finally(() => {
        this.loading.page = false
      })
    },
    getProviderInfo() {
      provider.viewServiceProvider(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.$imageSrc(this.form.providerLogo)
            });
          }
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    uploadLogo(file) {
      this.loading.upload = true;
      const formData = new FormData()
      formData.append('file', file.file)
      apiBase.uploadImage(formData).then(res => {
        if (this.logos.length == 0) {
          this.logos.push({
            url: ""
          })
        }
        this.logos[0] = ({
          path: res.data.picturePath,
          url: this.$imageSrc(res.data.picturePath)
        })
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.loading.upload = false;
      })
    },
    removeLogo(file) {
      this.logos = []
      this.form.providerLogo = ""
    },
    onClickSave() {
      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.form.providerLogo) {
            this.$message({
              message: "Please upload provider logo",
              type: 'error'
            });
            return
          }
          this.loading.saving = true;
          if (this.isEdit) {
            this.updateProvider()
          } else {
            this.addProvider();
          }
        }
      });
    },
    addProvider() {
      provider.addServiceProvider(this.form).then(res => {
        this.$message({
          message: 'Add service provider successfully',
          type: 'success'
        })
        this.onBack();
      }).catch(err => {
        this.loading.saving = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    updateProvider() {
      provider.updateServiceProvider(this.form).then(res => {
        this.$message({
          message: 'Update service provider successfully',
          type: 'success'
        })
        this.onBack();
      }).catch(err => {
        this.loading.saving = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    changePartyId() {
      if (this.form.partyId) {
        this.form.partyId = this.form.partyId.toUpperCase();
      }
    }
  }
}
</script>

<style 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;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  @media screen and (max-width: 500px) {
    .container {
      padding: 0px;
    }
    .content {
      padding: 15px 30px;
    }
  }
  .logo-upload {
    width: 300px;
    height: 100px;
    position: relative;
    border-radius: 6px;
    background-color: #F8F8F8;
    ::v-deep .el-image {
      width: 300px;
      height: 100px;
      border-radius: 6px;
      img {
        object-fit: contain;
      }
    }
  }
  .avatar-uploader-icon {
    width: 300px;
    height: 100px;
    color: #8c939d;
    cursor: pointer;
    font-size: 28px;
    text-align: center;
    line-height: 100px;
    border-radius: 6px;
    border: 1px dashed #d9d9d9;
  }
</style>