<template>
  <div class="autoBox box">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: 'home' }">{{
          $t("common.Home")
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ $t("common.Feedback") }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="suggess">
      <el-form ref="form" :model="form" :rules="formrules">
        <!--                建议类型-->
        <el-form-item
          :label="$t('common.SuggestedType') + ':'"
          prop="suggestion"
        >
          <el-radio-group v-model="form.suggestion" style="width: 100%">
            <el-radio-button
              v-for="(item, index) in suggestype"
              :key="index"
              :label="item.value"
              border
              >{{ item.label }}</el-radio-button
            >
          </el-radio-group>
        </el-form-item>
        <!--                反馈内容-->
        <el-form-item
          :label="$t('common.ContentFeedback') + ':'"
          prop="report"
          style="margin-top: 45px"
        >
          <el-input
            type="textarea"
            v-model="form.report"
            :autosize="{ minRows: 5, maxRows: 10 }"
            :placeholder="$t('common.PleaseInputFeedback')"
            maxlength="300"
            minlength="15"
            show-word-limit
            class="feedtext"
          ></el-input>
        </el-form-item>
        <!--                上传图片-->
        <el-form-item style="margin-top: 50px">
          <div class="uploadText">{{ $t("common.ToUploadPictures") }}：</div>
          <div style="display: inline-block">
            <el-upload
              action="/api/file/upload/img?module=feedback"
              :headers="myHeaders"
              list-type="picture-card"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :limit="5"
              ref="upImage"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
          <span class="maxupload">{{ $t("common.UploadUupMaxPhotos") }}</span>
        </el-form-item>
        <!--                联系方式-->
        <el-form-item
          :label="$t('common.ContactWay') + ':'"
          prop="phone"
          style="margin-top: 50px"
        >
          <el-input
            type="text"
            v-model="form.phone"
            style="width: 240px"
          ></el-input>
        </el-form-item>
        <!--                提交反馈-->
        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit"
            style="margin-left: 155px"
            >{{ $t("common.SubmitFeedback") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import Base from "@/views/base/Base";
import { getToken, resetToken } from "@/utils/auth";
import { saveOrUpdate } from "@/api/feedback";
import { getDicts } from "@/api/dict";
import { addGrowth } from "@/utils/toCompleteTask";
import { getUserPointPage } from "@/api/user";
export default {
  name: "Feedback",
  extends: Base,
  data() {
    return {
      suggestype: [],
      dialogImageUrl: "",
      dialogVisible: false,
      form: {
        suggestion: "",
        report: "",
        picture: [],
        phone: "",
      },
      feedback: {
        suggestion: "",
        report: "",
        picture: [],
        phone: "",
        account_name: "",
        user_id: "",
      },
      myHeaders: { Authorization: "Bearer " + getToken() },
      user: {
        umsUser: {},
      },
      pointStatus: null,
    };
  },
  mounted() {
    this.getType();
    this.getUser();
    this.clearForm();
    this.initData();
  },
  computed: {
    formrules() {
      return {
        suggestion: [
          {
            required: true,
            message:
              this.$i18n.locale == "zh"
                ? "请选择建议类型"
                : "Please select the type of suggestion",
            trigger: "change",
          },
        ],
        report: [
          {
            required: true,
            message:
              this.$i18n.locale == "zh"
                ? "请输入反馈内容"
                : "Please enter feedback",
            trigger: "change",
          },
          {
            min: 15,
            message:
              this.$i18n.locale == "zh"
                ? "不得少于15字"
                : "No less than 15 words",
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            message:
              this.$i18n.locale == "zh"
                ? "请输入联系方式"
                : "Please enter your mobile phone number",
            trigger: "change",
          },
          {
            pattern: /^([0-9]*)$/,
            message:
              this.$i18n.locale == "zh"
                ? "请输入合法的手机号"
                : "Please enter a valid mobile phone number",
          },
        ],
      };
    },
  },
  watch: {
    "$i18n.locale"() {
      this.getType();
      this.getUser();
    },
  },
  methods: {
    initData() {
      getUserPointPage().then((res) => {
        this.pointStatus = res.data.umsUserPoints[0].pointStatus;
      });
    },
    //图片上传成功
    handleAvatarSuccess(res, file) {
      // console.log(this.form.picture)
      this.form.picture.push(res.data);
      // this.photoLength =  this.form.picture.length;
    },
    //图片格式验证
    beforeAvatarUpload(file) {
      let photoStr = [];
      let photorules = ["jpg", "jpeg", "png", "webp"];
      let isJPG = false;
      photoStr = file.name.split(".")[1];
      if (photorules.indexOf(photoStr) == -1) {
        this.$message.error(this.$t("common.CorrectPictureFormat"));
      } else {
        isJPG = true;
      }
      return isJPG;
    },

    //清空对象集合
    clearForm() {
      this.$refs["form"].resetFields();
      this.$refs["upImage"].clearFiles();
      this.form = {
        suggestion: "",
        report: "",
        picture: [],
        phone: "",
      };
    },
    //获取建议类型
    getType() {
      if (this.$i18n.locale == "zh") {
        getDicts("SUGGESTION_DICT").then((res) => {
          this.suggestype = res.data[0];
        });
      } else if (this.$i18n.locale == "en") {
        getDicts("SUGGESTION_DICT_EN").then((res) => {
          this.suggestype = res.data[0];
        });
      }
    },
    //表单提交
    onSubmit(form) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.feedback.suggestion = this.form.suggestion;
          this.feedback.report = this.form.report;
          this.feedback.picture = this.form.picture;
          this.feedback.phone = this.form.phone;
          this.submitHandler((token) => {
            saveOrUpdate(JSON.stringify(this.feedback), token)
              .then((res) => {
                if (
                  this.user.umsUser.userUsertypeDict !== "2" &&
                  this.pointStatus == "y"
                ) {
                  addGrowth("platform_problem_feedback");
                }
                this.$message({
                  message:
                    this.$i18n.locale.toUpperCase() == "ZH"
                      ? "提交成功"
                      : "Submitted successfully",
                  type: "success",
                });
                this.resetToken();
                this.clearForm();
              })
              .catch((error) => {
                this.$notify.error({
                  title: "common.Error",
                  message: error.msg,
                });
                this.resetToken();
                this.clearForm();
              });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //获取用户信息
    getUser() {
      let user = JSON.parse(window.localStorage.getItem("user"));
      this.feedback.account_name = user.username;
      this.feedback.user_id = user.userId;
    },
    //跳转链接
    toView(router, json) {
      this.$router.push({
        name: router,
        query: { key: json },
      });
    },
  },
};
</script>
<style scoped>
body {
  margin: 0;
}
.box {
  margin-top: 10px;
  background: #fff;
  /* height: 500px; */
  padding: 20px 0;
}
.crumbs {
  margin-left: 20px;
}
.suggess {
  padding: 10px 30px;
  margin-top: 20px;
}
.feedtext {
  width: 555px;
  display: block;
}
.el-form-item .el-form-item__label {
  font-size: 18px;
  color: black;
  font-weight: 600;
}

.el-radio-button {
  margin: 20px 40px 0 0;
  border: 1px solid rgba(204, 204, 204, 0.36);
}
.el-textarea__inner {
  height: 250px;
}

>>> .el-upload-list__item-actions {
  display: none;
}
.avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.uploadText {
  display: inline-block;
}
.maxupload {
  position: absolute;
  bottom: 0;
  margin-left: 10px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: inline-block;
}
</style>
