<template>
  <div class="autoBox container-box">
    <div class="bread-crumb">
      <el-breadcrumb separator="/" style="float: left; margin: 15px">
        <el-breadcrumb-item :to="{ path: 'home' }">{{
          $i18n.locale == "en" ? "Home" : "首页"
        }}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: 'ConferenceServices' }">{{
          $i18n.locale == "en" ? "Conferences" : "会议"
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{
          $i18n.locale == "en" ? "The information provided" : "信息填报"
        }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="content-box" v-if="$i18n.locale == 'en'">
      <div class="content-item">
        <div class="category-body">
          <el-form
            :model="meetingApply"
            :rules="rulesEn"
            ref="meetingApplyEn"
            label-width="260px"
            key="1"
          >
            <!-- 邀请码 -->
            <el-form-item label="Invitation Code" prop="invitationCode">
              <el-input
                v-model="meetingApply.invitationCode"
                placeholder="Please enter Invitation Code.If not, please enter 000000."
              ></el-input>
            </el-form-item>
            <!-- 名 -->
            <el-form-item label="Given Name" prop="givenName">
              <el-input
                v-model="meetingApply.givenName"
                placeholder=""
              ></el-input>
            </el-form-item>
            <!-- 中间名 -->
            <el-form-item label="Middle Name">
              <el-input
                v-model="meetingApply.middleName"
                placeholder=""
              ></el-input>
            </el-form-item>
            <!-- 姓 -->
            <el-form-item label="Surname" prop="sumame">
              <el-input v-model="meetingApply.sumame" placeholder=""></el-input>
            </el-form-item>
            <!-- 所在国家 -->
            <el-form-item label="Country/Region" prop="unitCountryDcit">
              <el-select
                v-model="meetingApply.unitCountryDcit"
                filterable
                placeholder=""
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in unitCountryDictEns"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 单位名称 -->
            <el-form-item label="Name of Company/Organization" prop="filmName">
              <el-input
                v-model="meetingApply.filmName"
                placeholder=""
              ></el-input>
            </el-form-item>
            <!-- 单位类型 -->
            <el-form-item label="Company/Organization Type" prop="filmTypeDict">
              <el-select
                v-model="meetingApply.filmTypeDict"
                placeholder=""
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, i) in meetingUnitTypeDictEns"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 职务 -->
            <el-form-item label="Title" prop="title">
              <el-input v-model="meetingApply.title" placeholder=""></el-input>
            </el-form-item>
            <!-- 邮箱 -->
            <el-form-item label="E-mail" prop="mail">
              <el-input v-model="meetingApply.mail" placeholder=""></el-input>
            </el-form-item>
            <el-form-item
              label-width="198px"
              v-if="
                gridData.length && intentions.isShowEnOnlineIntention == 'Yes'
              "
            >
              <p style="font-size: 16px">
                Among multiple events of our conference, please kindly choose
                your preferable events to attend to（Multiple choice）.
              </p>
              <el-table
                :data="gridData"
                :border="false"
                @selection-change="checkRow"
                @row-click="setSelectEn"
                size="small"
                ref="multipleTableEn"
                :empty-text="'Sorry no date.'"
                class="active-grid"
              >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column property="activityName" label="ALL">
                  <template slot-scope="scope">
                    <p style="font-weight: bold">
                      {{ momentDate(scope.row.activityStartTime) }} ~
                      {{ momentDate(scope.row.activityEndTime) }}
                    </p>
                    <p>{{ scope.row.activityNameEn }}</p>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item style="text-align: center" label-width="0">
              <el-button
                type="primary"
                @click="submitFormEn('meetingApplyEn')"
                :key="btnKey"
                >Submit</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="content-box" v-else>
      <div class="content-item">
        <div class="category-body">
          <el-form
            :model="meetingApply"
            :rules="rulesZh"
            ref="meetingApplyZh"
            label-width="100px"
            key="2"
          >
            <el-form-item label="邀请码" prop="invitationCode">
              <el-input
                v-model="meetingApply.invitationCode"
                placeholder="请输入邀请码，如果没有，请输入000000。"
              ></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="meetingApply.name" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="国家" prop="unitCountryDcit">
              <el-select
                v-model="meetingApply.unitCountryDcit"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in unitCountryDicts"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单位名称" prop="filmName">
              <el-input
                v-model="meetingApply.filmName"
                placeholder=""
              ></el-input>
            </el-form-item>
            <el-form-item label="单位类型" prop="filmTypeDict">
              <el-select
                v-model="meetingApply.filmTypeDict"
                placeholder=""
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, i) in meetingUnitTypeDicts"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职务" prop="title">
              <el-input v-model="meetingApply.title" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="mail">
              <el-input v-model="meetingApply.mail" placeholder=""></el-input>
            </el-form-item>
            <el-form-item
              label-width="36px"
              v-if="
                gridData.length && intentions.isShowZhOnlineIntention == 'Yes'
              "
            >
              <p style="font-size: 16px">
                此次大会包括多场会议活动，请勾选您希望参加的场次（可多选）。
              </p>
              <el-table
                :data="gridData"
                :border="false"
                @selection-change="checkRow"
                @row-click="setSelect"
                size="small"
                ref="multipleTable"
                class="active-grid"
              >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column property="activityName" label="全选">
                  <template slot-scope="scope">
                    <p style="font-weight: bold">
                      {{ momentDate(scope.row.activityStartTime) }} ~
                      {{ momentDate(scope.row.activityEndTime) }}
                    </p>
                    <p>{{ scope.row.activityName }}</p>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item style="text-align: center" label-width="0">
              <el-button type="primary" @click="submitForm('meetingApplyZh')"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog :show-close="false" :visible.sync="dialogVisible" width="600px">
      <div class="category-body submit-success">
        <p>
          <img
            src="@/assets/img/conference/submit-success.png"
            alt=""
            width="200"
          />
        </p>
        <p style="font-size: 24px; color: #666; margin-bottom: 20px">
          {{ $i18n.locale == "en" ? "Registered!" : "报名成功！" }}
        </p>
        <p>
          <el-button
            style="background: #2c558a; color: #fff"
            @click="toView('ConferenceDetail', $route.query.key)"
          >
            {{ $i18n.locale == "en" ? "Back" : "返回" }}（{{ num }}s）
          </el-button>
          <el-button @click="ContinueRegister">{{
            $i18n.locale == "en" ? "Continue" : "继续报名"
          }}</el-button>
        </p>
      </div>
    </el-dialog>
    <div class="apply-history" v-if="applyHistoryInfo.length">
      <span style="font-size: 14px; margin-right: 20px">{{
        $i18n.locale == "en" ? "Registration History" : "报名历史"
      }}</span>
      <el-select
        v-model="applyHistorySelected"
        @change="applyHistoryChanged"
        :placeholder="$i18n.locale == 'en' ? 'Please Select' : '请选择'"
      >
        <el-option
          v-for="(item, i) in applyHistoryInfo"
          :key="i"
          :label="item.name"
          :value="i"
        >
          <span style="float: left">{{ item.name }}</span>
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
import Base from "@/views/base/Base";
import {
  registerOnline,
  getMeetingApplyActivityInfos,
  getOlApplyHistoryInfosByLoginAccount,
} from "@/api/meeting/meetingApply";
import { getConfrenceDetail } from "@/api/meeting/meetingOutInfo";
import { getToken } from "@/utils/auth";
import { getDicts } from "@/api/dict";
import moment from "moment-timezone";
import { addIntegral, addGrowth } from "@/utils/toCompleteTask";
export default {
  extends: Base,
  data() {
    var checkInvitationCode = (rule, value, callback) => {
      if (!value) {
        let errorTxt =
          this.$i18n.locale == "en"
            ? "Please enter Invitation Code.If not, please enter 000000."
            : "请输入邀请码";
        callback(new Error(errorTxt));
      } else if (!this.invitationCodeArr.includes(value)) {
        let errorTxt =
          this.$i18n.locale == "en"
            ? "Please enter the correct Invitation Code. If not, please enter 000000."
            : "请输入正确的邀请码。如果没有，请输入000000";
        callback(new Error(errorTxt));
      } else {
        callback();
      }
    };
    var checkEmail = (rule, value, callback) => {
      let reg = /^\w+.*\w+@[a-zA-Z0-9]+.*[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/gm;
      if (!value) {
        let errorTxt =
          this.$i18n.locale == "en" ? "Please enter E-mail." : "请输入邮箱";
        return callback(new Error(errorTxt));
      } else if (!reg.test(value)) {
        let errorTxt =
          this.$i18n.locale == "en"
            ? "Please enter the correct E-mail address."
            : "邮箱格式不正确";
        callback(new Error(errorTxt));
      } else {
        callback();
      }
    };
    return {
      newChecked:[],
      applyHistorySelected: "", //被选择的报名历史
      applyHistoryInfo: [], //报名历史信息
      btnKey: 1,
      dialogVisible: false,
      num: 5,
      timer: "",
      meetingUnitTypeDictEns: [],
      meetingUnitTypeDicts: [],
      invitationCodePrefix: [],
      invitationCodeArr: ["000000"],
      unitCountryDicts: [],
      unitCountryDictEns: [],
      gridData: [],
      checkedIds: [],
      baseInfo: {},
      intentions: {},
      meetingApply: {
        // meetingId: window.localStorage.getItem('conferenceId'),
        meetingId: this.$route.query.key,
        invitationCode: "",
        name: "",
        middleName: "",
        givenName: "",
        sumame: "",
        filmName: "",
        filmType: "",
        filmTypeDict: "",
        title: "",
        mail: "",
        unitCountryDcit: "",
        applyWay: "",
        isSendNotice: "No",
      },
      rulesEn: {
        invitationCode: [
          { required: true, validator: checkInvitationCode, trigger: "blur" },
        ],
        givenName: [
          {
            required: true,
            message: "Please enter Given Name.",
            trigger: "blur",
          },
        ],
        sumame: [
          { required: true, message: "Please enter Surname.", trigger: "blur" },
        ],
        mail: [{ required: true, validator: checkEmail, trigger: "blur" }],
        unitCountryDcit: [
          {
            required: true,
            message: "Please select Country/Region.",
            trigger: "change",
          },
        ],
        filmName: [
          {
            required: true,
            message: "Please enter Name of Company/Organization.",
            trigger: "blur",
          },
        ],
        filmTypeDict: [
          {
            required: true,
            message: "Company/Organization Type.",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "Please enter Title.", trigger: "blur" },
        ],
      },
      rulesZh: {
        invitationCode: [
          { required: true, validator: checkInvitationCode, trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        unitCountryDcit: [
          { required: true, message: "请选择国家", trigger: "change" },
        ],
        mail: [{ required: true, validator: checkEmail, trigger: "blur" }],
        filmName: [
          { required: true, message: "请输入单位名称", trigger: "blur" },
        ],
        filmTypeDict: [
          { required: true, message: "请选择单位类型", trigger: "change" },
        ],
        title: [{ required: true, message: "请输入职务", trigger: "blur" }],
      },
      user: {
        umsUser: {},
      },
    };
  },
  watch: {
    "$i18n.locale"(val) {
      this.meetingApply.unitCountryDcit =
        this.$i18n.locale == "en" ? "" : "china";
      this.getApplyHistoryInfos();
    },
    dialogVisible() {
      if (this.dialogVisible == true) {
        this.loginTipsChange();
      }
    },
  },
  mounted() {
    this.initData();
    if (this.$route.query) {
      localStorage.setItem("conferenceId", this.$route.query.key);
    }
    this.getIntentions();
    this.meetingApply.unitCountryDcit =
      this.$i18n.locale == "en" ? "" : "china";
    getDicts(
      "meeting_unit_type_dict_en, meeting_unit_type_dict, geidco_dept_dict, unit_country_dict, unit_country_dict_en"
    )
      .then((result) => {
        var data = result.data;
        if (data) {
          this.meetingUnitTypeDictEns = result.data[0] || [];
          this.meetingUnitTypeDicts = result.data[1] || [];
          this.invitationCodePrefix = result.data[2] || [];
          this.unitCountryDicts = result.data[3] || [];
          this.unitCountryDictEns = result.data[4] || [];
          if (this.unitCountryDictEns.length) {
            this.unitCountryDictEns.sort(function (a, b) {
              return a.value.charCodeAt() - b.value.charCodeAt();
            });
          }
        }
      })
      .then((res) => {
        getConfrenceDetail(localStorage.getItem("conferenceId")).then((res) => {
          this.baseInfo = res.data.basicInfo;
          // console.log('会议数据', res)
          // 邀请码集合
          this.invitationCodePrefix.forEach((item) => {
            this.invitationCodeArr.push(
              `${item.value}${res.data.basicInfo.meetingRand}`
            );
          });
          // console.log('邀请码集合', this.invitationCodeArr)
        });
        getMeetingApplyActivityInfos(localStorage.getItem("conferenceId"))
          .then((_res) => {
            console.log("_res", _res);
            this.gridData = _res.data.allMeetingActivitys || [];
          })
          .catch((err) => {
            this.gridData = [];
          });
      });
    this.getApplyHistoryInfos();
  },
  methods: {
    initData() {
      this.user = JSON.parse(window.localStorage.getItem("user"));
    },
    applyHistoryChanged(i) {
      Object.keys(this.applyHistoryInfo[i]).forEach((key) => {
        this.meetingApply[key] = this.applyHistoryInfo[i][key];
      });
    },
    //获取报名历史信息
    getApplyHistoryInfos() {
      this.applyHistorySelected = "";
      getOlApplyHistoryInfosByLoginAccount(this.$i18n.locale).then((res) => {
        this.applyHistoryInfo = res.data.olApplyHistoryInfos;
        console.log("ApplyHistoryInfos", res);
      });
    },
    getIntentions() {
      this.intentions = JSON.parse(
        sessionStorage.getItem("pathReminder")
      ).query.intentions;
    },
    momentDate(date) {
      if (this.$i18n.locale == "zh") {
        moment.locale("zh-cn");
        return moment(date).format("YYYY MM DD, H:mm");
      } else {
        moment.locale("en");
        return moment(date).format("lll");
      }
    },
    checkRow(checkedData) {
      this.checkedIds = [];
      this.newChecked = [];
      const date = []
      checkedData.forEach((item) => {
        date.find(i=>{
          if(i===this.momentDate(item.activityStartTime)){
            let msgTxt = this.$i18n.locale=='en'? 'Kind Reminder: participants can only register for one parallel session. Hope you enjoy the conference.': '温馨提示：同一时段平行召开的会议仅限选择一场参加，祝您参会愉快！';
            this.$message({
                message: msgTxt,
                type:'error'
              })
            }
          })
          date.push(this.momentDate(item.activityStartTime))
          this.checkedIds.push(item.id)
          this.newChecked.push(item.activityStartTime)
      });
    },
    setSelect(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    setSelectEn(row) {
      this.$refs.multipleTableEn.toggleRowSelection(row);
    },
    ContinueRegister() {
      clearInterval(this.timer);
      this.dialogVisible = false;
      this.btnKey = Math.random();
      // this.$refs.meetingApplyEn.resetFields();
    },
    loginTipsChange() {
      const that = this;
      this.num = 5;

      this.timer = setInterval(function () {
        if (that.num > 0) {
          that.num--;
        } else {
          clearInterval(that.timer);
          that.dialogVisible = false;
          that.toView("ConferenceDetail", that.$route.query.key);
        }
      }, 1000);
    },
    toView(router, json) {
      this.$router.push({ path: router, query: { key: json } });
    },
    formatDate(t) {
      if (!t) {
        return "";
      } else {
        var original = new Date(t);
        var year = original.getFullYear();
        var month = original.getMonth() + 1;
        var date = original.getDate();
        return year + "-" + month + "-" + date;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error("请填写完整信息");
          return false;
        }
        this.save();
      });
    },
    submitFormEn(formName) {
      // alert(this.$route.params.key)
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$message.error("Please fill in the complete information");
          return false;
        }
        this.meetingApply.name = `${this.meetingApply.givenName} ${this.meetingApply.middleName}  ${this.meetingApply.sumame}`;
        this.save();
      });
    },
    save: function () {
      var arr1=this.newChecked
        var arr2=arr1.sort()
        for(var i=0;i<arr2.length-1;i++){
          if(arr2[i]==arr2[i+1]){
            let msgTxt = this.$i18n.locale=='en'? 'Kind Reminder: participants can only register for one parallel session. Hope you enjoy the conference.': '温馨提示：同一时段平行召开的会议仅限选择一场参加，祝您参会愉快！';
            this.$message.error(msgTxt)
            return false
          }else{
            console.log('hello');
        }
      }

      // console.log("filmName:", this.meetingApply.filmName)
      this.meetingApply.applyWay = this.$i18n.locale;
      // console.log('this.meetingApply', this.meetingApply);
      // return
      this.submitHandler((token) => {
        registerOnline(
          JSON.stringify(this.meetingApply),
          token,
          this.checkedIds.join(",")
        )
          .then((result) => {
            console.log("result", result);
            if (result.status == "200") {
              if (this.user.umsUser.userUsertypeDict !== "2") {
                addIntegral("meeting_registration_successful", "10");
                addGrowth("meeting_registration_successful");
              }
              if (result.data.isRepeat) {
                let errorMsg =
                  this.$i18n.locale == "en"
                    ? "The guest has registered, please do not fill in again."
                    : "该嘉宾已报名，请勿重复填写!";
                this.$message.error(errorMsg);
                this.resetToken();
              } else {
                this.dialogVisible = true;
                this.resetToken();
              }
            }
            console.log("result", result);
          })
          .catch((error) => {
            this.resetToken();
          });
      });
    },
  },
};
</script>

<style scoped>
/deep/ .el-table thead{
  display: none;
}
* {
  box-sizing: border-box;
}

.container-box {
  width: 1200px;
  margin: 10px auto;
  position: relative;
}

.bread-crumb {
  height: 40px;
  background: #fff;
  margin: 10px 0;
}

.content-box {
  width: 100%;
  box-sizing: border-box;
  padding: 60px 150px 20px 150px;
  background: #fff;
}

.content-item {
  padding-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

/deep/ .content-box .el-input__inner {
  border-top: none;
  border-left: none;
  border-right: none;
  border-radius: 0;
}

.submit-success {
  text-align: center;
  font-size: 20px;
  color: #999;
}

.submit-success p {
  margin: 0;
}

.submit-success .el-button {
  width: 150px;
  font-size: 20px;
  margin: 10px;
}

.down-load a {
  font-size: 28px;
  color: #49a2f2;
  text-decoration: none;
}

.down-load a:hover {
  color: #de551a;
}

/deep/ .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

/deep/ .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}

.active-grid p {
  margin: 0;
}

/deep/ .el-table th > .cell {
  padding-left: 14px;
}

.apply-history {
  position: absolute;
  top: 60px;
  right: 20px;
}

.apply-history .el-select {
  width: 300px;
}
</style>
