<template>
  <div class="container">
    <div class="content">
      <el-form
        class="form"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :xs="24" :md="10" :offset="0">
            <el-form-item label="Display Name:" prop="nickName">
              <el-input
                :disabled="isDispatch"
                v-model="form.nickName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="10" >
            <el-form-item label="PDVL:" prop="pdvLicence">
              <el-input
                :disabled="isDispatch"
                v-model="form.pdvLicence"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="10" :offset="0">
            <el-form-item label="Email Address:" prop="email">
              <el-input
                :disabled="isDispatch"
                v-model="form.email"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="10">
            <el-form-item label="Group:" prop="groupPk">
              <el-select
                :disabled="isDispatch"
                v-model="form.groupPk">
                <el-option
                  v-for="(item, index) in options.fleetCompany"
                  :key="index"
                  :label="item.groupName"
                  :value="item.groupPk"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="10">
            <el-form-item label="Country:" prop="phone">
              <el-select
                :disabled="isDispatch"
                v-model="form.countryCode">
                <el-option
                  v-for="item in options.countryList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="10" :offset="0">
            <el-form-item label="Phone Number:" prop="phone">
              <div class="flexc">
                <el-select
                  style="min-width: 75px; max-width: 80px;"
                  :disabled="isDispatch"
                  v-model="form.callingCode">
                  <el-option
                    v-for="item in options.callingCode"
                    :key="item.callingCode"
                    :label="'+' + item.callingCode"
                    :value="item.callingCode"
                  />
                </el-select>
                <el-input
                  style="margin-left: 10px;"
                  :disabled="isDispatch"
                  v-model="form.phone"
                />
              </div>
              <!--el-input
                v-else
                :disabled="isDispatch"
                v-model="form.phone"
              ></el-input-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="PDVL:" class="pdvl" prop="pdvLicencePictures">
              <template v-slot:label>
                PDVL Photos: <br> (Front & Back)
              </template>
              <div class="flexcr">
                <el-upload
                  :disabled="isDispatch"
                  class="avatar-uploader"
                  accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
                  :action="action"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccessFirst"
                  :before-upload="beforeAvatarUpload">
                  <el-image
                    style="width: 150px; height: 100px"
                    v-if="form.pdvLicencePictures.front"
                    :src="form.pdvLicencePictures.front | imageSrc"
                    :preview-src-list="isDispatch ? previewSrcList : []"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-upload
                  :disabled="isDispatch"
                  class="avatar-uploader"
                  accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
                  :action="action"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccessSecond"
                  :before-upload="beforeAvatarUpload">
                  <el-image
                    style="width: 150px; height: 100px"
                    v-if="form.pdvLicencePictures.back"
                    :src="form.pdvLicencePictures.back | imageSrc"
                    :preview-src-list="isDispatch ? previewSrcList : []"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="!isFulfilled"></el-divider>
      <div class="buttons" v-if="isDispatch">
        <el-button
          v-if="!isFulfilled"
          @click="onClickRejectButton"
          type="primary"
          class="cancel-button"
          :loading="rejectButtonLoading"
        >
          Reject
        </el-button>
        <el-button
          v-if="!isFulfilled"
          @click="onClickApproveButton"
          type="primary"
          :loading="approveButtonLoading"
        >
          Approve
        </el-button>
      </div>
      <div class="buttons" v-else>
        <el-button
          @click="onClickCancelButton"
          type="primary"
          class="cancel-button"
        >
          Cancel
        </el-button>
        <el-button
          @click="onClickConfirmButton"
          type="primary"
          :loading="confirmButtonLoading"
        >
          Save
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/http/api/driver'
import group from '@/http/api/group'
import { baseURL } from '@/http/http'
import site from '../../http/api/site'
import { getToken } from '@/utils/auth'
import {getCountryList} from '../../utils/index.js'
import settings from '../../settings.js'
export default {
  name: "DriverDetail",
  data() {
    const picturesValidator = (rule, value, callback) => {
      if (!value.back || !value.front) {
        callback(new Error('must two picture...'))
      } else {
        callback()
      }
    }
    return {
      form: {
        userPk: "",
        nickName: "",
        groupStatus: "",
        email: "",
        phone: "",
        countryCode: settings.defaultCountry,
        callingCode: settings.defaultCalling,
        groupPk: "",
        pdvLicence: "",
        pdvLicencePictures: {
          front: "",
          back: "",
        },
      },
      options: {
        countryList: [],
        callingCode: [],
        fleetCompany: [],
      },
      rules: {
        nickName: [{
          message: "Nickname is required",
          trigger: "blur",
          required: true,
        }],
        email: [{
          message: "Email is required",
          trigger: "blur",
          required: true,
        }],
        phone: [{
          message: "Phone number is required",
          trigger: "blur",
          required: true,
        }],
        groupPk: [{
          message: "Please select group",
          trigger: "blur",
          required: true,
        }],
        pdvLicence: [{
          message: "required",
          trigger: "blur",
          required: false,
        }],
        pdvLicencePictures: [{
          trigger: "blur",
          required: false,
          //validator: picturesValidator,
        }],
      },
      confirmButtonLoading: false,
      approveButtonLoading: false,
      rejectButtonLoading: false,
    }
  },
  computed: {
    isFulfilled() {
      return this.form.groupStatus !== 'Pending Review'
    },
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/picture/upload'
    },
    isEdit() {
      return !!this.$route.query.id
    },
    isDispatch() {
      return !!this.$route.query.dispatch && !!this.$route.query.id
    },
    headers() {
      return {
        accessToken: getToken(),
        photoSubDir: "PDVL",
      }
    },
    previewSrcList() {
      const imageSrc = []
      const { front, back } = this.form.pdvLicencePictures
      if (front) {
        imageSrc.push(this.getImageSrc(front))
      }
      if (back) {
        imageSrc.push(this.getImageSrc(back))
      }
      return imageSrc
    },
  },
  filters: {
    imageSrc(path) {
      return baseURL + path
    }
  },
  methods: {
    getImageSrc(path) {
      return baseURL + path
    },
    getDriverId() {
      return this.$route.query.id
    },
    async getDriverDetail() {
      if (this.isEdit) {
        const { success, data } = await api.fetchDriverDetail({
          userPk: this.getDriverId()
        })
        if (success) {
          this.form.groupStatus = data.groupStatus
          this.form.email = data.email
          this.form.groupPk = data.groupPk
          this.form.nickName = data.nickName
          this.form.pdvLicence = data.pdvLicence
          this.form.countryCode = data.countryCode || 'SG'
          this.form.callingCode = "" + data.callingCode
          this.form.phone = data.phone
          this.form.userPk = data.userPk
          if (data.pdvLicencePictures) {
            const [front = '', back = ''] = data.pdvLicencePictures
            this.form.pdvLicencePictures.front = front
            this.form.pdvLicencePictures.back = back
          }
        }
      }
    },

    handleAvatarSuccessFirst(response) {
      this.form.pdvLicencePictures.front = response.data.picturePath
    },
    handleAvatarSuccessSecond(response) {
      this.form.pdvLicencePictures.back = response.data.picturePath
    },
    beforeAvatarUpload(file) {
      const IMAGE_TYPE_ARRAY = ['jpg', 'png', 'jpeg', 'gif']
      const fileExt = file.name.replace(/.+\./, '').toLowerCase()
      if (IMAGE_TYPE_ARRAY.indexOf(fileExt) === -1) {
        const msg = `请选择类型为${IMAGE_TYPE_ARRAY.join('、')}的文件`
        this.$message.warning(msg)
        return false
      }
      if (file.size / 1024 / 1024 > 2) {
        this.$message.warning('上传文件不能超过2m')
        return false
      }
    },
    async getFleetCompanyOptions() {
      const {
        success,
        data
      } = await group.getAllUserGroups()
      if (success) {
        this.options.fleetCompany = data
      }
    },
    async onClickApproveButton() {
      const params = { userPk: this.getDriverId() }
      this.approveButtonLoading = true
      try {
        const { success, msg } = await api.approveDriver(params)
        if (success) {
          this.$notify.success(msg)
          this.$router.back()
        }
      } catch (error) {
        this.$notify.error(msg)
      }
      this.approveButtonLoading = false
    },
    async onClickRejectButton() {
      const params = { userPk: this.getDriverId() }
      this.rejectButtonLoading = true
      try {
        const { success, msg } = await api.rejectDriver(params)
        if (success) {
          this.$notify.success(msg)
          this.$router.back()
        }
      } catch (error) {
        this.$notify.error(msg)
      }
      this.rejectButtonLoading = false
    },
    onClickCancelButton() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/user-management/group"
        })
      })
    },
    onClickConfirmButton() {
      this.confirmButtonLoading = true
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const {
              pdvLicencePictures: {
                front,
                back,
              },
              countryCode,
              callingCode,
              phone,
              ...others
            } = this.form
            const pdvLicencePictures = []
            front && pdvLicencePictures.push(front)
            back && pdvLicencePictures.push(back)

            let result
            if (this.isEdit) {
              result = await api.updateDriver({
                pdvLicencePictures,
                phone,
                countryCode,
                callingCode,
                ...others,
              })
            } else {
              result = await api.addDriver({
                pdvLicencePictures,
                countryCode,
                callingCode,
                phone,
                ...others,
              })
            }
            if (result.success) {
              this.$notify.success(result.msg)
              this.onClickCancelButton();
            }
          } catch (error) {
            if (error) {
              this.$notify.error(error)
            }
          }
        }
      })
      this.confirmButtonLoading = false
    },
    getCountryOptions() {
      site.getCountryList().then(({ data }) => {
        this.options.countryList = data
      })
    }
  },
  async created() {
    this.getFleetCompanyOptions()
    if (this.isEdit) {
      this.getDriverDetail()
    }
    this.getCountryOptions()
    getCountryList(list => {
      this.options.callingCode = list
    })
  },
}
</script>

<style lang='scss' scoped>
@import '../../styles/variables.scss';
  .container {
    width: 100%;
    padding: 20px 50px;
    background-color: #F0F5FC;
    .content {
      border-radius: 6px;
      min-height: calc(#{$mainAppMinHeight} - (2 * 20px));
      background-color: white;
      .form {
        padding: 45px 100px;
        .pdvl {
          ::v-deep .el-form-item__label {
            padding: 12px;
            line-height: 16px;
          }
        }
        .avatar-uploader {
          margin-right: 10px;
          .avatar-uploader-icon {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            font-size: 28px;
            color: #8c939d;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
          }
        }
      }

      .el-select {
        width: 100%;
      }

      .buttons {
        padding: 0 45px;
      }
    }
  }
</style>