<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" v-if="current === 0">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="公司名称"
          required
        >
          <a-input placeholder="请输入公司名称..." v-model.trim="platform.company" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="成立时间"
          required
        >
          <!-- 时间选择器（时间点） -->
          <a-date-picker @change="changeBirthday" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="法人代码"
          required
        >
          <a-input placeholder="请输入法人代码..." v-model.trim="platform.legalPerson" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="现注册地址"
          required
        >
          <a-input placeholder="请输入现注册地址..." v-model.trim="platform.registerSite" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="注册资金(单位：万)"
        >
          <a-input placeholder="请输入注册资金..." type="number" v-model.trim="platform.registerMoney" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="员工人数"
        >
          <a-input placeholder="请输入员工人数..." type="number" v-model.trim="platform.staffCount" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="其中研发人数"
        >
          <a-input placeholder="请输入研发人数..." type="number" v-model.trim="platform.resarchStaff" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="大专以上人员"
        >
          <a-input placeholder="请输入员工人数..." type="number" v-model.trim="platform.juniorCollege" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="主营业务"
        >
          <a-input placeholder="请输入主营业务..." v-model.trim="platform.mainBusiness" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="营业收入(单位：万)"
        >
          <a-input placeholder="请输入营业收入..." type="number" v-model.trim="platform.businessIncome" />
        </a-form-item>
      </a-form>
      <a-form :form="form" v-if="current === 1">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="产品/技术阶段"
          required
        >
          <!-- 单选 -->
          <a-radio-group v-model="platform.productTech">
            <a-radio :value="0" style="margin-right: 20px">创意阶段</a-radio>
            <a-radio :value="1" style="margin-right: 20px">研发阶段</a-radio>
            <a-radio :value="2" style="margin-right: 20px">转化阶段</a-radio>
            <a-radio :value="3" style="margin-right: 20px">原型样品</a-radio>
            <a-radio :value="4">产业化开发</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="申请专利数"
        >
          <a-input placeholder="请输入申请专利数..." type="number" v-model.trim="platform.patentApply" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="授权专利数"
        >
          <a-input placeholder="请输入授权专利数..." type="number" v-model.trim="platform.patentGrented" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="发明专利数"
        >
          <a-input placeholder="请输入发明专利数..." type="number" v-model.trim="platform.patentInvent" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="软件著作权"
        >
          <a-input placeholder="请输入软件著作权..." v-model.trim="platform.softwareRegister" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="动植物新品种"
        >
          <a-input placeholder="请输入动植物新品种..." v-model.trim="platform.plantKind" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="集成电路布图设计"
        >
          <a-input placeholder="请输入集成电路布图设计..." v-model.trim="platform.electricDesign" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="合作单位"
        >
          <a-input placeholder="请输入合作单位..." v-model.trim="platform.friendCompany" />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="上传附件"
        >
          <a-upload
            :action="action"
            :before-upload="beforeUpload"
            :default-file-list="fileList"
            @change="fileChange"
            list-type="picture"
            name="files"
          >
            <p>1.营业执照复印件（尚无注册的无需梯控）</p>
            <p>2.法定代表或授权代表身份证复印件</p>
            <p>3.主导产品或技术简介</p>
            <a-button>
              <a-icon type="upload" />点击上传附件
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
      <a-form :form="form" v-if="current === 2">
        <!-- <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="公司名称">
          <a-input v-model.trim="platform.companyName" placeholder="请输入公司名称..." />
        </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-radio-group v-model="platform.sex">
            <a-radio :value="1" style="margin-right: 100px">男</a-radio>
            <a-radio :value="0">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="职务"
          required
        >
          <a-input placeholder="请输入申请人职务..." v-model.trim="platform.position" />
        </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-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="电子邮箱"
        >
          <!-- 电子邮箱 -->
          <a-input
            @change="changeEamil"
            placeholder="请输入电子邮箱..."
            type="email"
            v-decorator="['email', { rules: emailRules }]"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="身份证号"
          required
        >
          <!-- 身份证号 -->
          <a-input
            @change="changeIdCard"
            placeholder="请输入身份证号..."
            v-decorator="['idCard', { rules: idCardRules }]"
          />
        </a-form-item>
      </a-form>
      <a-steps :current="current">
        <a-step @click="current = 0" style="cursor: pointer">
          <template slot="title">
            <span v-if="current === 0">Waiting...</span>
            <span v-else>完成</span>
          </template>
          <span slot="description">企业基本信息</span>
        </a-step>
        <a-step
          :title="current > 1 ? '完成' : 'Waiting...'"
          @click="current = 1"
          description="企业详细信息"
          style="cursor: pointer"
        />
        <a-step
          :title="current > 2 ? '完成' : 'Waiting...'"
          @click="current = 2"
          description="申请人基本信息"
          style="cursor: pointer"
        />
      </a-steps>
    </a-modal>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import { Settled, 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: 'SettledModel',
  props: {
    typeNum: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'submit' }),
      visible: false,
      current: 0,
      action: upload,
      fileList: [],
      title: '入驻企业注册',
      str: '申请加入',
      formItemLayout,
      formTailLayout,
      confirmLoading: false,
      platform: {
        manName: '', // 姓名
        sex: 1, // 性别 0：女，1：男
        position: '', // 职务
        tel: '', // 联系电话
        isTel: false,
        email: '', // 电子邮箱
        isEmail: false,
        code: '', // 验证码
        idCard: '', // 身份证号
        isIdCard: false,
        company: '', // 公司名称
        buildTime: 0, // 成立时间（时间戳）
        legalPerson: '', // 法人代码
        registerMoney: 0, // 注册资金
        staffCount: 0, // 员工人数
        resarchStaff: 0, // 研发人数
        juniorCollege: 0, // 大专以上人员
        mainBusiness: '', // 主营业务
        businessIncome: 0, // 营业收入
        registerSite: '', // 现注册地址
        productTech: 0, // 产品阶段
        patentApply: 0, // 申请专利数
        patentGrented: 0, // 授权专利数
        patentInvent: 0, // 发明专利数
        softwareRegister: '', // 软件著作权
        plantKind: '', // 动植物新品种
        electricDesign: '', // 集成电路布图设计
        friendCompany: '', // 合作单位
        files: [], // 文件id
      },
      phoneRules: [
        { required: true, pattern: new RegExp(/^[1][3,4,5,6,7,8,9][0-9]{9}$/), whitespace: true, message: '请输入正确的手机号' },
      ],
      codeRules: [
        { required: true, message: '请输入验证码' },
        { min: 4, max: 4, message: '请输入4位短信验证码' },
      ],
      emailRules: [
        {
          pattern: new RegExp(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/),
          whitespace: true,
          message: '请输入正确的邮箱格式',
        },
      ],
      idCardRules: [
        {
          required: true,
          pattern: new RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/),
          whitespace: true,
          message: '请输入身份证号',
        },
      ],
      codeNum: '',
      showInterval: false,
      codeTimer: null,
      interval: 120, // 验证码有效时间倒计时
    };
  },
  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']),
    ...mapMutations('home', ['setPagePath']),
    // 显示表单输入框
    showModal() {
      const anyringToken = sessionStorage.getItem('anyringToken');
      if (!anyringToken) {
        this.setPagePath(this.$route.path);
        this.$router.push('/login');
        this.$message.warning('请先登录');
      } else {
        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);
    },
    // 验证电子邮箱
    changeEamil(e) {
      this.platform.email = e.target.value;
      this.platform.isEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(this.platform.email);
    },
    // 验证身份证号
    changeIdCard(e) {
      this.platform.idCard = e.target.value;
      this.platform.isIdCard = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(this.platform.idCard);
    },
    // 获取验证码
    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();
    },
    // 成立时间
    changeBirthday(date, dateString) {
      this.platform.buildTime = this.$moment(date).unix() * 1000;
      // console.log(this.$moment(date).unix(), dateString);
    },
    // 点击确定
    handleOk() {
      if (this.current !== 2) {
        this.current++;
      } else {
        if (this.platform.company === '') {
          this.$message.error('请输入公司名称');
        } else if (this.platform.buildTime === 0) {
          this.$message.error('请选择成立时间');
        } else if (this.platform.legalPerson === '') {
          this.$message.error('请输入法人代码');
        } else if (this.platform.registerSite === '') {
          this.$message.error('请输入现注册地址');
        } else if (this.platform.manName === '') {
          this.$message.error('请输入姓名');
        } else if (this.platform.position === '') {
          this.$message.error('请输入职务');
        } else if (this.platform.isTel === false) {
          this.$message.error('请输入联系电话');
        } else if (this.platform.idCard === '') {
          this.$message.error('请输入身份证号');
        } else {
          for (var i = 0; i < this.fileList.length; i++) {
            this.platform.files = this.platform.files.concat(this.fileList[i].response.data[0].id);
          }
          this.addSettled();
        }
      }
    },
    async addSettled() {
      this.confirmLoading = true;
      try {
        const params = {
          param: {
            buildTime: this.platform.buildTime,
            businessIncome: this.platform.businessIncome,
            company: this.platform.company,
            electricDesign: this.platform.electricDesign,
            email: this.platform.email,
            fileList: this.platform.files,
            friendCompany: this.platform.friendCompany,
            gender: this.platform.sex,
            idCard: this.platform.idCard,
            juniorCollege: this.platform.juniorCollege,
            legalPerson: this.platform.legalPerson,
            mainBusiness: this.platform.mainBusiness,
            name: this.platform.manName,
            patentApply: this.platform.patentApply,
            patentGrented: this.platform.patentGrented,
            patentInvent: this.platform.patentInvent,
            phone: this.platform.tel,
            placeType: this.typeNum, //     自己带过来 0:虚拟，1:实体
            plantKind: this.platform.plantKind,
            position: this.platform.position,
            productTech: this.platform.productTech,
            registerMoney: this.platform.registerMoney,
            registerSite: this.platform.registerSite,
            resarchStaff: this.platform.resarchStaff,
            softwareRegister: this.platform.softwareRegister,
            staffCount: this.platform.staffCount,
          },
        };
        // console.log(params);
        const res = await Settled(params);
        // console.log(res);
        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;
          this.platform.isEmail = false;
          this.platform.isIdCard = false;
        } else {
          throw msg;
          // console.log('失败1');
          this.confirmLoading = false;
        }
      } catch (error) {
        // console.log('失败2');
        this.$message.error(error);
        this.confirmLoading = false;
      }
    },
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.warning('上传附件大小不能超过5m！');
          return reject(false);
        }
        return resolve(true);
      });
    },
    fileChange(info) {
      this.fileList = info.fileList;
    },
  },
};
</script>

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

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