<template>
  <el-dialog
    :title="$t('pages.accountHandle.dialog.title')"
    :visible="true"
    width="30%"
    :before-close="handleClose"
  >
    <el-form
      ref="form"
      v-loading="loading"
      :model="form"
      :rules="localizedFormRules"
      label-width="80px"
    >
      <el-form-item v-loading="loadingAccountStatus" :label="$t('pages.accountHandle.form.currentStatus')">
        {{ thisAccountStatus.value }}
      </el-form-item>
      <el-form-item :label="$t('pages.accountHandle.form.handleStatus')" prop="accountStatusEnum">
        <el-select
          v-model="form.accountStatusEnum"
          :disabled="accountStatusTypes.length <= 0"
          style="width: 100%;"
          @change="selectChanged"
        >
          <el-option-group
            v-for="(item, index) in accountStatus"
            :key="index"
            :label="item.name"
          >
            <el-option
              v-for="oItem in item.options"
              :key="oItem.value"
              :label="oItem.name"
              :value="oItem.value"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.accountStatusEnum === 'FREEZE'"
        :label="$t('pages.accountHandle.form.freezeDays')"
        prop="days"
      >
        <el-select v-model="form.days">
          <el-option
            v-for="item in dayOptions"
            :key="`freeze-${item.value}`"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.accountStatusEnum === 'ARCHIVE'"
        :label="$t('pages.accountHandle.form.days')"
        prop="days"
      >
        <el-select v-model="form.days">
          <el-option
            v-for="item in dayOptions"
            :key="`archive-${item.value}`"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('pages.accountHandle.form.remarks')" prop="description">
        <el-input
          v-model.trim="form.description"
          type="textarea"
          @keyup.native="descriptionKeyup"
        />
        <el-button
          v-if="form.accountStatusEnum === 'WARNING'"
          :loading="loadingTranslate"
          type="text"
          :disabled="disabledTranslate"
          @click="clickTranslate"
          >{{ $t('pages.accountHandle.action.translate') }}</el-button
        >
      </el-form-item>
      <el-form-item v-if="form.descriptionTranslate" :label="$t('pages.accountHandle.form.translation')">
        <el-input v-model="form.descriptionTranslate" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit()">{{ $t('pages.accountHandle.action.submit') }}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { accountHandle } from "@/api/approval";
import { getAccountStatus } from "@/api/app-user";
import { translateUserLangContent } from "@/api/translate";
import { mapGetters } from "vuex";
import { deepClone } from "@/utils";
export default {
  name: "AccountHandle",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loadingTranslate: false,
      loadingAccountStatus: true,
      disabledTranslate: false,
      thisAccountStatus: {},
      loading: false,
      accountStatusGroup: [
        {
          nameKey: "executePunishment",
          options: [
            { value: "WARNING", nameKey: "warning" },
            { value: "FREEZE", nameKey: "freeze" },
            { value: "ARCHIVE", nameKey: "archive" },
            { value: "ARCHIVE1DAY", nameKey: "archive1Day" },
            { value: "ARCHIVE_DEVICE", nameKey: "archiveDevice" }
          ]
        },
        {
          nameKey: "releasePunishment",
          options: [
            { value: "UNTIE_ACOOUNT", nameKey: "untieAccount" },
            { value: "UNTIE_DEVICE", nameKey: "untieDevice" },
            { value: "UNTIE_DEVICE_AND_ACCOUNT", nameKey: "untieDeviceAndAccount" }
          ]
        }
      ],
      form: {
        accountStatusEnum: "",
        days: 3,
        description: "",
        descriptionTranslate: "",
        beApprovalUserId: ""
      },
      accountStatusTypes: []
    };
  },
  computed: {
    ...mapGetters(["buttonPermissions"]),
    localizedFormRules() {
      const commonRules = [this.getRequiredRule()];
      return {
        description: commonRules,
        days: commonRules,
        accountStatusEnum: commonRules
      };
    },
    dayOptions() {
      return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "15", "30"].map(
        value => ({
          value,
          label: this.getDayLabel(value)
        })
      );
    },
    accountStatus() {
      const that = this;
      const result = [];
      that.accountStatusTypes = [];
      that.accountStatusGroup.forEach(row => {
        const newRow = deepClone(row);
        newRow.name = that.$t(`pages.accountHandle.group.${row.nameKey}`);
        result.push(newRow);
        newRow.options = [];
        row.options.forEach(item => {
          if (that.buttonPermissions.includes(`user:account:${item.value}`)) {
            newRow.options.push({
              ...item,
              name: that.$t(`pages.accountHandle.status.${item.nameKey}`)
            });
            that.accountStatusTypes.push(item);
          }
        });
      });
      return result;
    }
  },
  watch: {
    userId: {
      handler(newVal) {
        if (newVal) {
          this.loadAccountStatus(newVal);
        }
      },
      immediate: true
    }
  },
  methods: {
    getRequiredRule() {
      return {
        required: true,
        message: this.$t("pages.accountHandle.validation.requiredField"),
        trigger: "blur"
      };
    },
    getDayLabel(day) {
      return this.$t(
        Number(day) === 1
          ? "pages.accountHandle.word.daySingle"
          : "pages.accountHandle.word.dayPlural",
        { days: day }
      );
    },
    loadAccountStatus(userId) {
      const that = this;
      that.loadingAccountStatus = true;
      getAccountStatus(userId)
        .then(res => {
          that.loadingAccountStatus = false;
          that.thisAccountStatus = res.body;
        })
        .catch(() => {
          that.loadingAccountStatus = false;
        });
    },
    handleClose() {
      this.$emit("close");
    },
    selectChanged(value) {
      this.disabledTranslate = false;
      this.form.descriptionTranslate = "";
      if (value === "WARNING") {
        this.form.description =
          "由于您被其他用户多次合理举报，且经平台审查属实。现对您发出警告，请下次务必注意言行，避免账号被冻结或者封禁。";
      } else {
        this.form.description = "";
      }
      if (value === "ARCHIVE1DAY") {
        this.form.days = 1;
      } else {
        this.form.days = 3;
      }
    },
    submit() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return false;
        }
        that.form.beApprovalUserId = that.userId;
        if (that.form.accountStatusEnum === "ARCHIVE1DAY") {
          that.form.accountStatusEnum = "ARCHIVE";
        }
        that.loading = true;
        accountHandle(that.form)
          .then(res => {
            that.loading = false;
            that.$emit("success", Object.assign({}, that.form));
            that.handleClose();
          })
          .catch(err => {
            that.loading = false;
            that.$emit("fial", err);
            that.handleClose();
          });
      });
    },
    clickTranslate() {
      const that = this;
      if (!that.form.description) {
        return;
      }
      that.loadingTranslate = true;
      translateUserLangContent({
        targetUserId: that.userId,
        content: that.form.description
      })
        .then(res => {
          that.loadingTranslate = false;
          that.form.descriptionTranslate = res.body;
          if (res.status === 3001) {
            that.$opsMessage.fail(this.$t("pages.accountHandle.message.sameLanguage"));
            return;
          }
          if (res.status === 3003) {
            that.$opsMessage.fail(this.$t("pages.accountHandle.message.noSuitableLanguage"));
            return;
          }
          that.disabledTranslate = true;
        })
        .catch(() => {
          that.loadingTranslate = false;
        });
    },
    descriptionKeyup() {
      this.disabledTranslate = false;
      this.form.descriptionTranslate = "";
    }
  }
};
</script>
