<template>
  <el-container>
    <el-main class="el-main-padding">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        :inline-message="true"
      >
        <el-form-item label="系统名称" prop="OE_STUDENT_SYS_NAME">
          <el-input
            v-model="ruleForm.OE_STUDENT_SYS_NAME"
            placeholder="请输入系统名称"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item label="学校logo" prop="LOGO_FILE_URL">
          <el-upload
            class="upload-width"
            ref="upload"
            accept=".png"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :before-upload="beforeUpload"
            :on-progress="uploadProgress"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="false"
            :multiple="false"
            :limit="1"
            :on-exceed="handleExceed"
            list-type="picture"
          >
            <el-button size="small" slot="trigger" type="primary"
              >选择文件</el-button
            >&nbsp;
            <el-button size="small" type="success" @click="submitUpload"
              >确认上传</el-button
            >
            <el-button size="small" type="danger" @click="removeFile"
              >清空文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              图片大小(长*宽)为400*100的png文件
            </div>
          </el-upload>
          <el-input v-show="false" v-model="ruleForm.LOGO_FILE_URL"></el-input>
        </el-form-item>

        <el-form-item label="登录方式选择" prop="loginType">
          <el-checkbox-group v-model="ruleForm.loginType">
            <el-checkbox
              v-for="lt in loginTypes"
              name="loginType"
              :label="lt.code"
              v-model="lt.code"
              :key="lt.code"
              >{{ lt.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="防作弊配置" prop="preventCheatingConfig">
          <el-checkbox-group v-model="ruleForm.preventCheatingConfig">
            <el-checkbox
              v-for="pcc in preventCheatingConfigs"
              name="preventCheatingConfig"
              :label="pcc.code"
              v-model="pcc.code"
              :key="pcc.code"
              >{{ pcc.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-show="false"
          label="窗口默认大小"
          prop="STUDENT_CLIENT_DEFAULT_SIZE"
        >
          <el-input
            v-model="ruleForm.STUDENT_CLIENT_DEFAULT_SIZE"
            placeholder="窗口大小格式为：宽度*高度"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item label="控制台配置" prop="STUDENT_CLIENT_CONSOLE_CONFIG">
          <el-input
            v-model="ruleForm.STUDENT_CLIENT_CONSOLE_CONFIG"
            placeholder="系统预留，无需配置"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >保 存</el-button
          >
          <!-- <el-button class="btn-margin-left" @click="resetForm('ruleForm')">取 消</el-button> -->
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>
<script>
import { mapState } from "vuex";
import {
  LOGIN_TYPE,
  PREVENT_CHEATING_CONFIG,
  CORE_API
} from "@/constants/constants.js";
export default {
  data() {
    return {
      rootOrgId: null,
      loginTypes: LOGIN_TYPE,
      propertyGroupId: "",
      preventCheatingConfigs: PREVENT_CHEATING_CONFIG,
      ruleForm: {
        relatedPropertyGroupIdList: [],
        orgId: null,
        OE_STUDENT_SYS_NAME: "",
        LOGO_FILE_URL: "",
        LOGIN_TYPE: "",
        PREVENT_CHEATING_CONFIG: "",
        STUDENT_CLIENT_DEFAULT_SIZE: "",
        STUDENT_CLIENT_CONSOLE_CONFIG: "",
        properties: {
          OE_STUDENT_SYS_NAME: "",
          LOGO_FILE_URL: "",
          LOGIN_TYPE: "",
          PREVENT_CHEATING_CONFIG: "",
          STUDENT_CLIENT_DEFAULT_SIZE: "",
          STUDENT_CLIENT_CONSOLE_CONFIG: ""
        },
        loginType: [],
        preventCheatingConfig: []
      },
      logoDialog: false,
      uploadAction: "",
      uploadHeaders: {},
      uploadData: {},
      fileList: [],
      rules: {
        OE_STUDENT_SYS_NAME: [
          { required: true, message: "请输入系统名称", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
        ],
        LOGO_FILE_URL: [
          { required: true, message: "请上传学校logo", trigger: "change" }
        ],
        loginType: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个登录方式",
            trigger: "change"
          }
        ],
        STUDENT_CLIENT_DEFAULT_SIZE: [
          { required: true, message: "请输入客户端默认大小", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.ruleForm.properties.OE_STUDENT_SYS_NAME = this.ruleForm.OE_STUDENT_SYS_NAME;
          this.ruleForm.properties.LOGO_FILE_URL = this.ruleForm.LOGO_FILE_URL;
          this.ruleForm.properties.STUDENT_CLIENT_DEFAULT_SIZE = this.ruleForm.STUDENT_CLIENT_DEFAULT_SIZE;
          this.ruleForm.properties.STUDENT_CLIENT_CONSOLE_CONFIG = this.ruleForm.STUDENT_CLIENT_CONSOLE_CONFIG;
          this.ruleForm.properties.LOGIN_TYPE = this.ruleForm.LOGIN_TYPE = this.ruleForm.loginType.join(
            ","
          );
          if (
            this.ruleForm.preventCheatingConfig == null ||
            this.ruleForm.preventCheatingConfig.length == 0
          ) {
            this.ruleForm.properties.PREVENT_CHEATING_CONFIG = this.ruleForm.PREVENT_CHEATING_CONFIG =
              "NONE";
          } else {
            this.ruleForm.properties.PREVENT_CHEATING_CONFIG = this.ruleForm.PREVENT_CHEATING_CONFIG = this.ruleForm.preventCheatingConfig.join(
              ","
            );
          }

          this.$httpWithMsg
            .put(CORE_API + "/org/saveOrgProperties", this.ruleForm)
            .then(
              () => {
                this.$notify({
                  message: "保存成功",
                  type: "success"
                });
              },
              () => {}
            );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    initForm() {
      this.ruleForm.orgId = this.user.rootOrgId;
      this.ruleForm.STUDENT_CLIENT_DEFAULT_SIZE = "1400*900";
      this.ruleForm.relatedPropertyGroupIdList = ["studentClientConfig"];
      var url =
        CORE_API +
        "/org/getOrgPropertiesByGroupWithoutCache/" +
        this.rootOrgId +
        "/" +
        this.propertyGroupId;
      this.$httpWithMsg.get(url).then(response => {
        console.log(response);

        if (response) {
          this.ruleForm.properties = response.data;
          // if (this.ruleForm.properties.OE_STUDENT_SYS_NAME) {
          this.ruleForm.OE_STUDENT_SYS_NAME =
            this.ruleForm.properties.OE_STUDENT_SYS_NAME ||
            this.ruleForm.OE_STUDENT_SYS_NAME;
          // }

          this.ruleForm.LOGO_FILE_URL =
            this.ruleForm.properties.LOGO_FILE_URL ||
            this.ruleForm.LOGO_FILE_URL;
          this.ruleForm.LOGIN_TYPE =
            this.ruleForm.properties.LOGIN_TYPE || this.ruleForm.LOGIN_TYPE;
          this.ruleForm.PREVENT_CHEATING_CONFIG =
            this.ruleForm.properties.PREVENT_CHEATING_CONFIG ||
            this.ruleForm.PREVENT_CHEATING_CONFIG;
          this.ruleForm.STUDENT_CLIENT_DEFAULT_SIZE =
            this.ruleForm.properties.STUDENT_CLIENT_DEFAULT_SIZE ||
            this.ruleForm.STUDENT_CLIENT_DEFAULT_SIZE;
          this.ruleForm.STUDENT_CLIENT_CONSOLE_CONFIG =
            this.ruleForm.properties.STUDENT_CLIENT_CONSOLE_CONFIG ||
            this.ruleForm.STUDENT_CLIENT_CONSOLE_CONFIG;

          if (this.ruleForm.properties.LOGIN_TYPE) {
            this.ruleForm.loginType = this.ruleForm.properties.LOGIN_TYPE.split(
              ","
            );
          } else {
            let defaultValue = [];
            for (let lt of LOGIN_TYPE) {
              defaultValue.push(lt.code);
            }
            this.ruleForm.loginType = defaultValue;
            console.log(defaultValue);
          }

          if (this.ruleForm.properties.PREVENT_CHEATING_CONFIG) {
            this.ruleForm.preventCheatingConfig = this.ruleForm.properties.PREVENT_CHEATING_CONFIG.split(
              ","
            );
          } else {
            let defaultValue = [];
            for (let lt of PREVENT_CHEATING_CONFIG) {
              defaultValue.push(lt.code);
            }
            this.ruleForm.preventCheatingConfig = defaultValue;
            console.log(defaultValue);
          }
          let fileUrl = response.data.LOGO_FILE_URL;
          let fname = "";
          if (fileUrl) {
            let lastIndex = fileUrl.lastIndexOf("/");
            let len = fileUrl.length;
            fname = fileUrl.substr(lastIndex + 1, len - lastIndex);
            this.fileList = [{ name: fname, url: this.ruleForm.LOGO_FILE_URL }];
          } else {
            this.fileList = [];
          }
        } else {
          this.$notify({
            message: "学生客户端信息暂未初始化，请立即初始化",
            type: "warning"
          });
        }
      });
    },
    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    // },
    initUpload() {
      this.fileList = [];
    },
    beforeUpload(file) {
      if (!this.checkUpload()) {
        return false;
      }
      console.log(file);
    },
    uploadProgress() {
      console.log("uploadProgress");
    },
    uploadSuccess(response) {
      console.log("uploadSuccess");
      console.log(response);
      if (response && response.length > 0) {
        this.$notify({
          message: "上传成功",
          type: "success"
        });
        let fileUrl = response;

        this.ruleForm.LOGO_FILE_URL = this.ruleForm.properties.LOGO_FILE_URL = fileUrl;
      } else {
        this.errDialog = true;
      }
      this.fileLoading = false;
      this.logoDialog = false;
      // this.removeFile();
    },
    uploadError(response) {
      let json = JSON.parse(response.message);
      if (response.status == 500) {
        this.$notify({
          message: json.desc,
          type: "error"
        });
      }
      this.fileLoading = false;
    },
    //确定上传
    submitUpload() {
      if (!this.checkUpload()) {
        return false;
      }
      this.$refs.upload.submit();
      this.fileLoading = true;
    },
    checkUpload() {
      var fileList = this.$refs.upload.uploadFiles;
      if (fileList.length == 0) {
        this.$notify({
          message: "上传文件不能为空",
          type: "error"
        });
        return false;
      }
      if (fileList.length > 1) {
        this.$notify({
          message: "每次只能上传一个文件",
          type: "error"
        });
        return false;
      }
      for (let file of fileList) {
        var fileName = file.name;
        if (
          // !fileName.endsWith(".jpg") &&
          // !fileName.endsWith(".gif") &&
          !fileName.endsWith(".png")
        ) {
          this.$notify({
            message: "上传文件格式必须为[png]",
            type: "error"
          });
          this.initUpload();
          return false;
        }
      }
      return true;
    },
    //清空文件
    removeFile() {
      this.fileList = [];
      this.ruleForm.LOGO_FILE_URL = this.ruleForm.properties.LOGO_FILE_URL = "";
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.removeFile();
    },
    handleExceed() {
      this.$notify({
        message: "当前限制选择 1 个文件,请先清空文件再试",
        type: "error"
      });
    }
  },
  created() {
    this.rootOrgId = this.user.rootOrgId;
    this.propertyGroupId = "studentClientConfig4Edit";
    this.uploadAction = CORE_API + "/org/importLogo/" + this.rootOrgId;
    this.uploadHeaders = {
      key: this.user.key,
      token: this.user.token
    };
    console.log(this.propertyGroupId);
    this.initForm();
  },
  computed: {
    ...mapState({ user: state => state.user })
  }
};
</script>
<style scoped>
.input-width {
  width: 638px;
}
.upload-width {
  width: 638px;
}
/* .btn-margin-left {
  margin-left: 20px;
} */
</style>
