<template>
  <div>
    <a-button @click="showModal" type="primary">{{ str }}</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 placeholder="请输入单位名称..." v-model.trim="platform.companyName" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="单位性质"
        >
          <a-input placeholder="请输入单位性质..." v-model.trim="platform.companyType	" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          class="fill-width"
        >
          <span class="title-color" style="margin-left:5%;">社会信用代码或组织机构代码：</span>
          <a-input
            placeholder="请输入社会信用代码或组织机构代码..."
            style="margin-left:27.5%;"
            v-model.trim="platform.code	"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="所属领域"
        >
          <a-select
            @change="handlePosition"
            placeholder="请选择所属领域"
            v-model.trim="platform.position	"
          >
            <a-select-option value="1">功能食品协同创新中心</a-select-option>
            <a-select-option value="2">现代医药</a-select-option>
            <a-select-option value="3">生物医学工程</a-select-option>
            <a-select-option value="4">数字健康开发</a-select-option>
            <a-select-option value="5">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="单位负责人"
        >
          <a-input placeholder="请输入单位负责人..." v-model.trim="platform.ower" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="单位邮箱"
        >
          <a-input
            :initial-value="platform.email"
            placeholder="请输入单位邮箱..."
            v-decorator="['email', { rules: emailRules }]"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="单位联系人"
          required
        >
          <a-input placeholder="请输入单位联系人..." v-model.trim="platform.contact" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="联系电话"
          required
        >
          <a-input
            @change="changePhone"
            placeholder="请输入联系电话.."
            type="phone"
            v-decorator="['phone', {initialValue: platform.phone, 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.message" />
            <a-button
              class="code_img ml-2"
              disabled
              type="primary"
              v-if="showInterval"
            >重新发送 {{ interval }}</a-button>
            <a-button
              :disabled="isTel === false"
              @click="getCode"
              class="code_img ml-2"
              type="primary"
              v-else
            >获取验证码</a-button>
          </div>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="上传附件"
        >
          <a-upload
            :action="action"
            :default-file-list="fileList"
            @change="fileChange"
            list-type="picture"
            name="files"
          >
            <a-button>
              <a-icon type="upload" />点击上传附件
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { CreatingPlatformAdd, upload } from 'config/api';

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
const formTailLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18, offset: 6 },
};
export default {
  name: 'NewModel',

  data() {
    return {
      form: this.$form.createForm(this, { name: 'submit' }),
      visible: false,
      title: '协同创新中心加入申请',
      str: '申请加入',
      formItemLayout,
      formTailLayout,
      confirmLoading: false,
      platform: {
        companyName: '', // 单位名称
        companyType: '', // 单位性质
        code: '', // 社会信用代码或组织机构代码
        position: '', // 所属领域
        ower: '', // 单位负责人
        email: '', // 单位邮箱
        contact: '', // 单位联系人
        phone: '', // 联系电话
        message: '', // 短信验证码
        // 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: '请输入正确的手机号' },
      ],
      action: upload,
      fileList: [],
      emailRules: [
        {
          pattern: new RegExp(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/),
          whitespace: true,
          message: '请输入正确的邮箱格式',
        },
      ],
    };
  },

  computed: {
    ...mapState('user', ['picCode']),
    ...mapState('home', ['userSer']),

    isTel() {
      return /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.platform.phone);
    },
  },

  async created() {
    this.sendPicCode();
    await this.getUserSer();
    if (this.userSer) {
      if (this.userSer.name) {
        this.platform.contact = this.userSer.name;
      }
      if (this.userSer.phone) {
        this.platform.phone = this.userSer.phone;
      }
      if (this.userSer.companyName) {
        this.platform.companyName = this.userSer.companyName;
      }
    }
  },
  methods: {
    ...mapActions('user', ['sendCode', 'sendPicCode']),
    ...mapActions('home', ['getUserSer']),
    // 显示表单输入框
    showModal() {
      this.visible = true;
    },
    // 取消显示
    handleCancel(e) {
      this.visible = false;
    },
    // 选择领域
    handlePosition(value) {
      this.platform.position = value;
    },
    // 验证电话
    changePhone(e) {
      this.platform.phone = e.target.value;
    },
    fileChange(info) {
      this.fileList = info.fileList;
    },
    // 点击确定
    handleOk() {
      if (!this.platform.contact) {
        this.$message.error('请输入联系人');
      } else if (!this.platform.phone) {
        this.$message.error('请输入联系电话');
      } else if (!this.platform.message) {
        this.$message.error('请输入验证码');
      } else {
        if (this.isTel) {
          this.subMitAdd();
        } else {
          this.$message.error('请输入正确的联系电话');
        }
      }
    },
    // 加入接口
    async subMitAdd() {
      this.confirmLoading = true;
      try {
        const params = {
          param: {
            companyName: this.platform.companyName,
            companyType: this.platform.companyType,
            code: this.platform.code,
            position: this.platform.position,
            ower: this.platform.ower,
            email: this.platform.email,
            contact: this.platform.contact,
            phone: this.platform.phone,
            message: this.platform.message,
            // pic: this.codeNum,
            fileList: this.fileList,
          },
        };
        console.log('params: ', params);
        const res = await CreatingPlatformAdd(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.isTel = false;
        } else {
          throw msg;
          this.confirmLoading = false;
        }
      } catch (error) {
        this.$message.error(error);
        this.confirmLoading = false;
      }
    },
    // 获取验证码
    async getCode() {
      try {
        const params = {
          phone: this.platform.phone,
          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>
