<template>
  <el-dialog
    class="dialog-access"
    :visible="visible"
    :before-close="e => hideDialog(false)"
    :title="isEdit ? 'Update User' : 'Add User'">
    <el-form
      ref="acsForm"
      :model="form"
      :rules="rules"
      label-position="top"
      v-loading="initial">
      <div class="form-row">
        <el-form-item
          prop="userName"
          class="form-item"
          label="NAME:">
          <el-input
            v-model="form.userName"
            class="flex-item"
            maxlength="20"/>
        </el-form-item>
        <!--el-form-item
          prop="phone"
          class="form-item"
          label="CONTACT NO.:">
          <div class="flexc flex-item">
            <el-select
              style="min-width: 70px; max-width: 78px;margin-right: 10px;"
              v-model="form.callingCode">
              <el-option
                v-for="(item,index) in callingOptions"
                :key="index"
                :label="'+' + item.callingCode"
                :value="item.callingCode"
              />
            </el-select>
            <el-input
              v-model="form.phone"
              class="flex1"
              maxlength="12"
            />
          </div>
        </el-form-item-->
        <el-form-item
          prop="email"
          class="form-item"
          label="EMAIL:">
          <el-input
            v-model="form.email"
            class="flex-item"
            maxlength="50"/>
        </el-form-item>
      </div>
      <div class="form-row">
        <el-form-item
          class="form-item"
          label="SET PASSWORD:"
          v-if="isEdit">
          <el-input
            v-model="form.password"
            class="flex-item"
            type="password"
            maxlength="32"/>
        </el-form-item>
        <el-form-item
          class="form-item"
          label="SET PASSWORD:"
          prop="password"
          v-else>
          <el-input
            v-model="form.password"
            class="flex-item"
            type="password"
            maxlength="32"/>
        </el-form-item>
        <el-form-item
          class="form-item"
          label="ROLE:">
          <el-select
            v-model="form.roleName"
            class="flex-item">
            <el-option
              v-for="(item, index) in roleOptions"
              :key="index"
              :label="item.roleDesc"
              :value="item.roleName"/>
          </el-select>
        </el-form-item>
      </div>
      <div class="form-row">
        <el-form-item
          class="form-item"
          label="PROVIDER NAME:"
          prop="providerPk"
          v-if="form.roleName=='PROVIDER'">
          <el-select
            v-model="form.providerPk"
            class="flex-item2">
            <el-option
              v-for="(item, index) in providerOptions"
              :key="index"
              :label="item.providerName"
              :value="item.providerPk"/>
          </el-select>
        </el-form-item>
        <el-form-item
          class="form-item"
          label="GROUP NAME:"
          prop="groupPk"
          v-if="form.roleName=='GROUP'">
          <el-select
            v-model="form.groupPk"
            class="flex-item2">
            <el-option
              v-for="(item, index) in groupOptions"
              :key="index"
              :label="item.groupName"
              :value="item.groupPk"/>
          </el-select>
        </el-form-item>
        <el-form-item
          class="form-item"
          label="SITE ALLOCATION:"
          prop="sitePks"
          v-if="form.roleName=='SITE'">
          <el-select
            v-model="form.sitePks"
            class="flex-item2"
            filterable
            multiple
            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>
      </div>
      <div class="flexcc" style="margin-top: 10px;">
        <el-button
          class="button"
          type="primary"
          :loading="loading"
          @click="onFormSave">
          <span style="padding: 0 20px;">SAVE</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import api from '@/http/api/access'
import site from '@/http/api/site'
import group from '@/http/api/group'
import provider from '@/http/api/provider'
import settings from '../../settings.js'
import {getCountryList} from '../../utils/index.js'
export default {
  name: "DialogDetail",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    id: {
      type: String|Number,
      default: ''
    },
    roleOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      initial: false,
      loading: false,
      form: {
        userPk: undefined,
        userName: "",
        email: "",
        roleName: "",
        lastLogin: "",
        password: "",
        callingCode: settings.defaultCalling,
        providerPk: "",
        groupPk: "",
        sitePks: []
      },
      rules: {
        userName: {
          required: true,
          message: "Username is required",
          trigger: "blur"
        },
        phone: [{
          required: true,
          message: "Contact No. is required",
          trigger: "blur"
        }, {
          pattern: /^\d{6,}$/,
          trigger: 'blur',
          message: 'Please type a correct phone'
        }],
        email: [{
          message: "Email is required",
          trigger: "blur",
          required: true,
        },{
          pattern: /^[a-zA-Z0-9]+[\S]+@[a-zA-Z0-9_-]+[\.][\Sa-zA-Z]+$/,
          trigger: 'blur',
          message: 'Please type a correct email'
        }],
        password: [{
          required: true,
          message: "Passwrod is required",
          trigger: "blur"
        }],
        providerPk: {
          required: true,
          message: "Provider is required",
          trigger: "change"
        },
        groupPk: {
          required: true,
          message: "Group is required",
          trigger: "change"
        },
        sitePks: {
          required: true,
          message: "Please select at least one site",
          trigger: "change"
        }
      },
      siteOptions: [],
      groupOptions: [],
      callingOptions: [],
      providerOptions: []
    };
  },
  watch: {
    id(n, o) {
      if (this.visible && n) {
        this.$nextTick(() => {
          this.getUserInfo();
        })
      }
    }
  },
  mounted() {
    this.getOptions();
  },
  methods: {
    hideDialog(success) {
      this.init();
      this.$emit("hide", success || false);
    },
    init() {
      this.form = {
        userPk: undefined,
        userName: "",
        email: "",
        phone: "",
        roleName: this.roleOptions[0].roleName,
        lastLogin: "",
        password: "",
        callingCode: settings.defaultCalling,
        providerPk: "",
        groupPk: "",
        sitePks: []
      }
      this.loading = false;
      this.$nextTick(() => {
        if (this.$refs['acsForm']) {
          this.$refs['acsForm'].clearValidate();
        }
      })
    },
    getOptions() {
      getCountryList(list => {
        this.callingOptions = list
      });
      provider.getAllServiceProvider().then(res => {
        if (res.data) {
          this.providerOptions = res.data
        }
      });
      group.getAllUserGroups().then(res => {
        if (res.data) {
          this.groupOptions = res.data
        }
      });
      this.getAllSite()
    },
    getAllSite(siteKeyword) {
      site.getAllSiteList({siteName: siteKeyword || ""}).then(res => {
        if (res.data && res.data.length > 0) {
          this.siteOptions = res.data
        } else {
          this.siteOptions = []
        }
        this.init();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
        this.siteOptions = []
      });
    },
    getUserInfo() {
      this.initial = true;
      api.infoAccessUser(this.id).then(res => {
        if (res.data) {
          this.form = res.data
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.initial = false;
      })
    },
    onFormSave() {
      this.$refs['acsForm'].validate((valid) => {
        if (valid) {
          this.isEdit ?this.updateUser() : this.addUser();
        }
      })
    },
    addUser() {
      this.loading = true;
      api.addAccessUser(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Add successfully"
        });
        this.hideDialog(true);
      }).catch(err => {
        this.loading = false;
        this.$message({
          type: 'error',
          message: err
        })
      });
    },
    updateUser() {
      this.loading = true;
      api.updateAccessUser(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Update successfully"
        });
        this.hideDialog(true);
      }).catch(err => {
        this.loading = false;
        this.$message({
          type: 'error',
          message: err
        })
      });
    }
  }
}
</script>

<style scoped>
.dialog-access >>> .el-dialog {
  width: 100%;
  max-width: 600px;
}
.dialog-access >>> .el-form {
  padding-right: 10px;
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  padding: 0 0 10px;
}
.form-item {
  flex: 1;
  margin-left: 10px;
  margin-bottom: 10px;
}
.form-item >>> label {
  padding: 0;
}
.flex-item {
  min-width: 200px;
  max-width: 270px;
}
.flex-item2 {
  width: 100%;
  min-width: 200px;
}
@media screen and (max-width: 500px) {
  .flex-item {
    width: 100%;
    max-width: none;
  }
}
</style>