<template>
  <div>
    <a-button @click="showModal" type="primary">立即报名</a-button>

    <a-modal
      :confirm-loading="confirmLoading"
      :title="title"
      :visible="visible"
      @cancel="handleCancel"
      @ok="handleOk"
      width="50%"
    >
      <a-form :form="form">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="活动名称"
        >
          <a-input :value="actName" disabled />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="申请单位"
          required
        >
          <a-input placeholder="请输入申请单位..." v-model.trim="platform.companyName" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          class="mb-3"
          label="参加人员"
          required
        >
          <div :key="index" class="d-flex flex-nowrap mb-3" v-for="(item,index) in people">
            <a-input class="flex-1 mr-3" placeholder="姓名" v-model.trim="item.name" />
            <a-input class="flex-1 mr-3" placeholder="职称" v-model.trim="item.duties" />
            <a-input class="flex-1 mr-3" placeholder="职务" v-model.trim="item.positional" />
            <a-button
              @click="changePerson(index)"
              icon="plus"
              type="link"
              v-if="index === people.length -1"
            />
          </div>
        </a-form-item>

        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="联系人"
          required
        >
          <a-input placeholder="请输入联系人..." v-model.trim="platform.manName" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="联系电话"
          required
        >
          <a-input
            @change="changePhone"
            placeholder="请输入联系电话.."
            type="tel"
            v-decorator="['tel', { rules: phoneRules }]"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="图片验证码"
          required
        >
          <div class="d-flex flex-nowrap">
            <a-input placeholder="图片验证码" type="number" v-model="codeNum" />
            <img
              :src="picCode.imageBase64"
              @click="changePicCode"
              class="code_img ml-2"
              v-if="picCode && picCode.imageBase64"
            />
            <a-button @click="changePicCode" class="code_img ml-2" size="small" v-else>获取验证码</a-button>
            <!-- <a-input v-decorator="['account', { rules: rules.account }]" /> -->
          </div>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="短信验证码"
          required
        >
          <div class="d-flex flex-nowrap">
            <a-input placeholder="请输入验证码" type="number" v-model="platform.code" />
            <a-button
              class="code_img ml-2"
              disabled
              type="primary"
              v-if="showInterval"
            >重新发送 {{ interval }}</a-button>
            <a-button
              :disabled="platform.isTel === false"
              @click="getCode"
              class="code_img ml-2"
              type="primary"
              v-else
            >获取验证码</a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { apply } from 'config/api';
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
const formTailLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18, offset: 6 },
};
export default {
  name: 'Enroll',
  props: {
    activityId: {
      type: Number,
      default: 0,
    },
    actName: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'submit' }),
      visible: false,
      title: '活动报名',
      formItemLayout,
      formTailLayout,
      confirmLoading: false,
      // 参加人员
      people: [
        {
          name: '',
          duties: '',
          positional: '',
        },
      ],
      platform: {
        companyName: '', // 申请单位
        manName: '', // 联系人
        tel: '', // 联系电话
        code: '', // 验证码
        isTel: false,
      },
      codeRules: [
        { required: true, message: '请输入验证码' },
        { min: 4, max: 4, message: '请输入4位短信验证码' },
      ],
      codeNum: '',
      showInterval: false,
      codeTimer: null,
      interval: 120, // 验证码有效时间倒计时
      phoneRules: [
        { required: true, pattern: new RegExp(/^[1][3,4,5,6,7,8,9][0-9]{9}$/), whitespace: true, message: '请输入正确的手机号' },
      ],
    };
  },

  computed: mapState('user', ['picCode']),

  async created() {
    this.sendPicCode();
    await this.getUserSer();
    if (this.userSer) {
      if (this.userSer.name) {
        this.platform.manName = this.userSer.name;
      }
      if (this.userSer.phone) {
        this.platform.tel = this.userSer.phone;
      }
      if (this.userSer.companyName) {
        this.platform.companyName = this.userSer.companyName;
      }
    }
  },

  methods: {
    ...mapActions('user', ['sendCode', 'sendPicCode']),
    ...mapActions('home', ['getUserSer']),

    changePerson(index) {
      // if (this.people[index].name && this.people[index].positional && this.people[index].duties) {
      const a = { name: '', positional: '', duties: '' };
      this.people.push(a);
      // }
    },
    // 显示表单输入框
    showModal() {
      this.visible = true;
    },
    // 取消显示
    handleCancel(e) {
      this.visible = false;
    },
    // 验证电话
    changePhone(e) {
      this.platform.tel = e.target.value;
      this.platform.isTel = /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.platform.tel);
    },
    // 点击确定
    handleOk() {
      if (!this.platform.companyName) {
        this.$message.error('请输入申请单位');
      } else if (!this.people[0].name || !this.people[0].positional || !this.people[0].duties) {
        this.$message.error('请至少输入一名参加人员');
      } else if (!this.platform.tel) {
        this.$message.error('请输入联系电话');
      } else if (!this.platform.code) {
        this.$message.error('请输入验证码');
      } else {
        if (this.platform.isTel) {
          this.subMitAdd();
        } else {
          this.$message.error('请输入正确的联系电话');
        }
      }
    },
    // 加入接口
    async subMitAdd() {
      this.confirmLoading = true;
      try {
        const { activityId, platform, people } = this;
        people.forEach(item => {
          item.activityId = activityId;
        });
        const params = {
          param: {
            activityId,
            code: platform.code,
            companyName: platform.companyName,
            contactName: platform.manName,
            contactPhone: platform.tel,
            peoples: people,
          },
        };
        console.log('params: ', params);
        const res = await apply(params);
        const { code, msg, data } = res.data;
        if (code === 200) {
          this.$message.success('申请成功');
          this.visible = false;
          this.confirmLoading = false;
          for (let key in this.platform) {
            this.platform[key] = '';
          }
          this.platform.isTel = false;
        } else {
          throw msg;
          this.confirmLoading = false;
        }
      } catch (error) {
        this.$message.error(error);
        this.confirmLoading = false;
      }
    },
    // 获取验证码
    async getCode() {
      console.log(111);
      try {
        const params = {
          phone: this.platform.tel,
          verificationCodeId: this.picCode.verificationCodeId,
          verificationCodeValue: this.codeNum,
        };
        await this.sendCode(params);
        this.getCodeInterval();
      } catch (error) {
        // throw new Error(`SignIn.vue method getCode: ${error}`);
        console.log(error);
      }
    },

    // 验证码倒计时
    getCodeInterval() {
      this.showInterval = true;
      this.codeTimer = setInterval(() => {
        if (this.interval === 0) {
          clearInterval(this.codeTimer);
          this.codeTimer = null;
          this.showInterval = false;
          this.interval = 120;
          return;
        }
        this.interval = this.interval - 1;
      }, 1000);
    },

    // 刷新验证码
    changePicCode() {
      this.sendPicCode();
    },
  },
};
</script>

<style lang="stylus" scoped>
.must-color {
  color: red;
}

.code_img {
  height: 32px;
  width: 120px;
}
</style>
