<template>
  <div class="edit-team-drawer">
    <el-drawer
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <!-- Title -->
      <div slot="title" class="flex-l">
        <sys-origin-icon :icon="profile.sysOrigin" size="18px" />&nbsp;{{ $t('pages.teamList.edit.title') }}
      </div>
      <div class="edit-team">
        <div class="drawer-form">
          <el-alert
            v-if="tmpRegion !== form.region && form.id !== ''"
            :title="$t('pages.teamList.edit.regionChangeWarning')"
            type="warning"
            effect="dark"
            :closable="false"
            style="margin-bottom: 10px;"
          />
          <el-form
            ref="form"
            :model="form"
            :rules="formRules"
            label-width="80px"
          >
            <!-- Region -->
            <el-form-item prop="region" :label="$t('pages.teamList.edit.region')">
              <select-system-region
                ref="regionSelectPolicy"
                v-model="form.region"
                :sys-origin="profile.sysOrigin"
                clearable
                :placeholder="$t('pages.teamList.edit.region')"
                @change="changeRegionSelectPolicy"
              />
            </el-form-item>

            <!-- Nickname -->
            <!-- <el-form-item prop="nickname" label="Nickname">
              <el-input v-model="form.nickname" placeholder="Enter team nickname" maxlength="24" show-word-limit />
            </el-form-item> -->

            <!-- Cover -->
            <!-- <el-form-item label="Cover">
              <el-form-item prop="cover">
                <upload-image
                  v-model="form.avatar"
                  :file-dir="$application.fileBucket.avatar"
                />
              </el-form-item>
            </el-form-item> -->

            <!-- Country -->
            <el-form-item :label="$t('pages.teamList.edit.country')" prop="country.countryId">
              <contry-select
                v-model="form.country.countryId"
                @change="contrySelectChange"
              />
            </el-form-item>

            <div style="padding: 10px 0px;">
              <!-- Section title -->
              <el-divider content-position="left">{{ $t('pages.teamList.edit.settingInfo') }}</el-divider>

              <!-- Member quantity -->
              <el-form-item prop="setting.maxMember" :label="$t('pages.teamList.edit.memberQuantity')">
                <el-input
                  v-model="form.setting.maxMember"
                  :placeholder="$t('pages.teamList.edit.maxMember')"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>

              <!-- Switch: agent receives host salary -->
              <el-form-item
                prop="setting.hostSalaryToAgent"
                :label="$t('pages.teamList.edit.hostSalaryToAgent')"
              >
                <el-switch
                  v-model="form.setting.hostSalaryToAgent"
                  :active-value="true"
                  :inactive-value="false"
                />
              </el-form-item>

              <!-- Switch: withdrawal enabled -->
              <el-form-item prop="withdrawalEnabled" :label="$t('pages.teamList.edit.withdrawalEnabled')">
                <el-switch
                  v-model="form.withdrawalEnabled"
                  :active-value="true"
                  :inactive-value="false"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button :disabled="submitLoading" @click="handleClose()"
            >{{ $t('pages.teamList.action.cancel') }}</el-button
          >
          <el-button
            type="primary"
            :disabled="submitLoading"
            :loading="submitLoading"
            @click="submitForm()"
            >{{ $t('pages.teamList.action.save') }}</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import ContrySelect from "@/components/data/ContrySelect";
import { contactTypes, billCyclePolicyTypes } from "@/constant/team-type";
import { updateTeamProfile } from "@/api/team";
import { deepClone } from "@/utils";

export default {
  name: "TeamEdit",
  components: { ContrySelect },
  props: {
    profile: {
      type: Object,
      require: true,
      default: () => {}
    }
  },
  data() {
    const commonRules = [
      { required: true, message: this.$t("pages.teamList.validation.requiredField"), trigger: "blur" }
    ];
    return {
      billCyclePolicyTypes,
      contactTypes,
      submitLoading: false,
      formSettingDefault: false,
      formContactAdd: false,
      tmpRegion: "",
      form: {
        sysOrigin: "",
        region: "",
        nickname: "",
        avatar: "",
        setting: {
          maxMember: "1000"
        },
        country: {
          countryId: "",
          countryCode: "",
          countryName: ""
        }
      },
      formRules: {
        sysOrigin: commonRules,
        region: commonRules,
        nickname: commonRules,
        "country.countryId": commonRules,
        "setting.maxMember": commonRules
      },
      selecteRegion: {}
    };
  },
  computed: {},
  watch: {
    profile: {
      handler(newVal) {
        this.tmpRegion = "";
        const form = deepClone(newVal);
        this.tmpRegion = form.region;
        if (!form.country) {
          form.country = this.form.country;
        }
        if (form.country && !form.country.countryId) {
          form.country = this.form.country;
        }
        this.form = form;
      },
      immediate: true
    }
  },
  methods: {
    handleClose() {
      if (this.submitLoading) {
        this.$opsMessage.warn(this.$t("pages.teamList.message.submitting"));
        return;
      }
      this.$emit("close");
    },
    contrySelectChange(id, row) {
      this.form.country.countryId = row.id;
      this.form.country.countryCode = row.code;
      this.form.country.countryName = row.name;
    },
    changeRegionSelectPolicy(val, item) {
      this.selecteRegion = item;
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }

        if (!that.form.id || this.tmpRegion === that.form.region) {
          that.submitLoading = true;
          updateTeamProfile(that.form)
            .then(res => {
              that.submitLoading = false;
              that.$emit(
                "success",
                Object.assign({}, that.form),
                that.selecteRegion
              );
              that.handleClose();
            })
            .catch(err => {
              that.submitLoading = false;
              that.$emit("fial", err);
            });
          return;
        }

        that
          .$confirm(
            this.$t("pages.teamList.confirm.changeRegionMessage"),
            this.$t("pages.teamList.confirm.deleteTitle"),
            {
              confirmButtonText: this.$t("pages.teamList.action.confirm"),
              cancelButtonText: this.$t("pages.teamList.action.cancel"),
              type: "warning"
            }
          )
          .then(() => {
            that.submitLoading = true;
            updateTeamProfile(that.form)
              .then(res => {
                that.submitLoading = false;
                that.$emit(
                  "success",
                  Object.assign({}, that.form),
                  that.selecteRegion
                );
                that.handleClose();
              })
              .catch(err => {
                that.submitLoading = false;
                that.$emit("fial", err);
              });
          })
          .catch(() => {});
        // <el-alert
        //         :v-if="tmpRegion !== form.region"
        //         title="Changing the agent region will clear all host targets. Continue?"
        //         type="warning"
        //         effect="dark"
        //         :closable="false"
        //       />
      });
    }
  }
};
</script>
