<script lang="ts">
import { MobileOutlined, MailOutlined, LockOutlined, PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
export default defineComponent({
  name: 'register',
  components: {
    MobileOutlined,
    MailOutlined,
    LockOutlined,
    PlusOutlined,
    LoadingOutlined
  },
})
</script>
<script setup lang='ts'>
import { FormProps, message, UploadFile } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { defineComponent, onMounted, reactive, ref, UnwrapRef, watch } from 'vue'
import { sendSms, verification, applyDevelop } from '@/api/index'
import AMapLoader from '@amap/amap-jsapi-loader';
import util from '@/util/index'
import router from '@/router';

const current = ref<number>(0);
const steps = ref<Array<any>>([
  '账号信息', '资料提交', '完成注册',
])
let verifyText = ref<string>('点击获取')
let firstDisabled = ref<Boolean>(true)
let submitDisabled = ref<Boolean>(true)
let loading = ref<boolean>(false);
let fileList = ref([]);
let time = ref<number>(60)
let timer = ref<number>()
let canSendSms = ref<boolean>(true)
let labelCol = ref<object>({ style: { width: '200px' } })
let action = ref<string>('http://153.37.175.42:8070/app/common/upload')
interface FormState {
  provinceName: string,
  cityName: string,
  cityCode: string,
  districtName: string,
  userAccount: string;
  password: string;
  passwordAgain: string;
  code?: number
  licenseType: number,
  merchantType: number,
  categoryId: number,
  address: string,
  street: string,
  merchantName: string,
  bizLicenseNo: string,
  bizLicense: string
  legalPerson: string,
  idcardType: number,
  idcardNo: string,
  idcardFront: string,
  idcardBack: string,
  bizLicenseIdcard: string,
  contactName: string,
  mobile: string
}
const formState: UnwrapRef<FormState> = reactive({
  provinceName: '',
  cityName: '',
  cityCode: '',
  districtName: '',
  userAccount: '',
  password: '',
  passwordAgain: '',
  licenseType: 3,
  merchantType: 2,
  categoryId: 2,
  address: '',
  street: '',
  merchantName: '',
  bizLicenseNo: '',
  bizLicense: '',
  legalPerson: '',
  idcardType: 1,
  idcardNo: '',
  idcardFront: '',
  idcardBack: '',
  bizLicenseIdcard: '',
  contactName: '',
  mobile: ''
});
window._AMapSecurityConfig = {
  securityJsCode: '23cf1bca0e52bbf8cb129047cdb46f10'
}
onMounted(() => {

})
watch(formState, (newValue) => {
  console.log('数据：', newValue);
  if (newValue.userAccount && newValue.password && newValue.passwordAgain && newValue.code) {
    firstDisabled.value = false
    if (newValue.address && newValue.street && newValue.merchantName && newValue.bizLicenseNo && newValue.bizLicense && newValue.legalPerson && newValue.idcardNo && newValue.idcardFront && newValue.idcardBack && newValue.bizLicenseIdcard && newValue.contactName && newValue.mobile) {
      submitDisabled.value = false
    } else {
      submitDisabled.value = true
    }
  } else {
    firstDisabled.value = true
  }
}, { deep: true })
const next = async () => {
  if (formState.password !== formState.passwordAgain) {
    return message.error('俩次输入的密码不一致，请修改为相同密码！')
  }
  let res: any = await verification({ mobile: formState.userAccount, code: formState.code })
  if (res.code !== 200) {
    return message.error(res.message)
  }
  if (!util.mobile(formState.userAccount)) {
    return message.error('请填写正确格式的注册手机号！')
  }
  current.value++;
};
const prev = () => {
  current.value--;
};
function getAddressInfo() {
  return new Promise((resolve, reject) => {
    AMapLoader.load({
      "key": "21132ea36aed6ab1884085a836f12ca9",              // 申请好的Web端开发者Key，首次调用 load 时必填
      "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      "plugins": ['AMap.Geocoder'],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap: { Geocoder: new () => any; }) => {
      let geocoder = new AMap.Geocoder()
      geocoder.getLocation(formState.address, function (status: string, result: { info: string; }) {
        console.log('result:', status, result);
        if (status === 'complete' && result.info === 'OK') {
          // result中对应详细地理坐标信息
          resolve(result)
        } else {
          return message.error('请正确填写企业地址的省市区')
          reject(result)
        }
      })
    })
  })

}
const submit = async () => {
  let result: any = await getAddressInfo()
  console.log('result:', result);
  let addressComponent = result?.geocodes[0]?.addressComponent
  if (result.info === 'OK' && addressComponent.province && addressComponent.city && addressComponent.district) {
    formState.provinceName = addressComponent.province
    formState.cityName = addressComponent.city
    formState.cityCode = addressComponent.citycode
    formState.districtName = addressComponent.district
  } else {
    message.error('请正确填写企业地址的省市区')
  }
  if (!util.mobile(formState.mobile)) {
    return message.error('请填写正确格式的联系电话！')
  }
  applyDevelop(formState).then((res: any) => {
    if (res.code === 0) {
      current.value++;
    } else {
      message.error(res.message)
    }
  })
}
const doSendSms = () => {
  if (!util.mobile(formState.userAccount)) {
    return message.error('请填写正确格式的注册手机号！')
  }
  sendSms({ mobile: formState.userAccount, type: 1 }).then((res: any) => {
    console.log(res);
    if (res.code === 200) {
      message.success('发送成功，请查收短信验证码！')
      timer.value = setInterval(() => {
        canSendSms.value = false
        time.value--
        verifyText.value = `重新获取 (${time.value})`
        if (!time.value) {
          verifyText.value = `重新获取`
          canSendSms.value = true
          clearInterval(timer.value)
          time.value = 60
        }
      }, 1000)
    } else {
      message.error(res.msg)
    }
  })
}
const handleChanges = (info: any, type: number) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    loading.value = false;
    console.log('info.file:', info.file);
    let url = info.file.response.data.url
    switch (type) {
      case 1:
        formState.bizLicense = url
        break;
      case 2:
        formState.idcardFront = url
        break;
      case 3:
        formState.idcardBack = url
        break;
      case 4:
        formState.bizLicenseIdcard = url
        break;
      default:
        break;
    }
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
}
const handleChange = (info: UploadChangeParam) => {
  handleChanges(info, 1)
};
const handleChange2 = (info: UploadChangeParam) => {
  handleChanges(info, 2)
};
const handleChange3 = (info: UploadChangeParam) => {
  handleChanges(info, 3)
};
const handleChange4 = (info: UploadChangeParam) => {
  handleChanges(info, 4)
};
</script>
<template>
  <div class=" pt-120px flex flex-col items-center">
    <a-steps :current="current" labelPlacement="vertical" class="w-700px">
      <a-step v-for="item in steps" :key="item" :title="item" />
    </a-steps>
    <div class="mt-60px">
      <!-- 账号信息 -->
      <a-form v-if="current === 0" :model="formState" class="w-600px">
        <a-form-item>
          <a-input v-model:value="formState.userAccount" :maxlength="11" allowClear placeholder="输入注册手机号">
            <template #prefix>
              <MobileOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input-password v-model:value="formState.password" allowClear placeholder="输入登录密码">
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-input-password v-model:value="formState.passwordAgain" allowClear placeholder="再次输入登录密码">
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-input v-model:value="formState.code" :maxlength="4" placeholder="输入短信验证码" allowClear
            style="width: calc(100% - 130px)">
            <template #prefix>
              <MailOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
          <a-button @click="doSendSms" :disabled="!canSendSms" class="ml-20px w-110px" type="primary">{{ verifyText }}
          </a-button>
        </a-form-item>
      </a-form>
      <!-- 资料提交 -->
      <a-form v-if="current === 1" :model="formState" :label-col="labelCol">
        <a-form-item label="企业地址" :rules="[{ required: true }]">
          <a-input v-model:value="formState.address" allowClear placeholder="输入企业地址省市区" />
          <a-textarea class="mt-24px" v-model:value="formState.street" placeholder="输入企业详细地址" />
        </a-form-item>
        <a-form-item label="企业名称" :rules="[{ required: true }]">
          <a-input v-model:value="formState.merchantName" allowClear placeholder="输入企业名称" />
        </a-form-item>
        <a-form-item label="统一社会信用代码" :rules="[{ required: true }]">
          <a-input v-model:value="formState.bizLicenseNo" allowClear placeholder="输入企业统一社会信用代码" />
        </a-form-item>
        <a-form-item label="营业执照" :rules="[{ required: true }]">
          <template class="flex justify-between">
            <a-upload class="avatar-uploader" v-model:file-list="fileList" name="file" list-type="picture-card"
              :show-upload-list="false" :action="action" @change="handleChange">
              <img class="w-150px h-100px" v-if="formState.bizLicense" :src="formState.bizLicense" alt="avatar" />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </a-upload>
            <div class="flex items-start flex-shrink-0">
              <div class="text-14px font-500 text-dark-200 flex-shrink-0 mt-10px mr-20px">示例</div>
              <img class="w-150px h-100px" src="@/assets/images/14.png" alt="" srcset="">
            </div>
          </template>
        </a-form-item>
        <a-form-item label="法人／实际控制人姓名" :rules="[{ required: true }]">
          <a-input v-model:value="formState.legalPerson" allowClear placeholder="输入企业法人／实际控制人姓名" />
        </a-form-item>
        <a-form-item label="法人／实际控制人证件类型" :rules="[{ required: true }]">
          <a-select v-model:value="formState.idcardType">
            <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>
        </a-form-item>
        <a-form-item label="法人／实际控制人证件号码" :rules="[{ required: true }]">
          <a-input v-model:value="formState.idcardNo" allowClear placeholder="输入法人／实际控制人证件号码" />
        </a-form-item>
        <a-form-item label="证件照正面" :rules="[{ required: true }]">
          <template class="flex justify-between">
            <a-upload class="avatar-uploader" v-model:file-list="fileList" name="file" list-type="picture-card"
              :show-upload-list="false" :action="action" @change="handleChange2">
              <img v-if="formState.idcardFront" :src="formState.idcardFront" class="w-150px h-100px" alt="avatar" />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </a-upload>
            <div class="flex items-start flex-shrink-0">
              <div class="text-14px font-500 text-dark-200 flex-shrink-0 mt-10px mr-20px">示例</div>
              <img class="w-150px h-100px" src="@/assets/images/14-1.png" alt="" srcset="">
            </div>
          </template>
        </a-form-item>
        <a-form-item label="证件照反面" :rules="[{ required: true }]">
          <template class="flex justify-between">
            <a-upload class="avatar-uploader" v-model:file-list="fileList" name="file" list-type="picture-card"
              :show-upload-list="false" :action="action" @change="handleChange3">
              <img v-if="formState.idcardBack" :src="formState.idcardBack" class="w-150px h-100px" alt="avatar" />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </a-upload>
            <div class="flex items-start flex-shrink-0">
              <div class="text-14px font-500 text-dark-200 flex-shrink-0 mt-10px mr-20px">示例</div>
              <img class="w-150px h-100px" src="@/assets/images/14-2.png" alt="" srcset="">
            </div>
          </template>
        </a-form-item>
        <a-form-item label="手持证件照" :rules="[{ required: true }]">
          <template class="flex justify-between">
            <a-upload class="avatar-uploader" v-model:file-list="fileList" name="file" list-type="picture-card"
              :show-upload-list="false" :action="action" @change="handleChange4">
              <img v-if="formState.bizLicenseIdcard" :src="formState.bizLicenseIdcard" class="w-150px h-100px"
                alt="avatar" />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </a-upload>
            <div class="flex items-start flex-shrink-0">
              <div class="text-14px font-500 text-dark-200 flex-shrink-0 mt-10px mr-20px">示例</div>
              <img class="w-150px h-100px" src="@/assets/images/14-3.png" alt="" srcset="">
            </div>
          </template>
        </a-form-item>
        <a-form-item label="公司联系人" :rules="[{ required: true }]">
          <a-input v-model:value="formState.contactName" allowClear placeholder="输入公司联系人" />
        </a-form-item>
        <a-form-item label="联系电话" :rules="[{ required: true }]">
          <a-input v-model:value="formState.mobile" allowClear placeholder="输入联系电话" :maxlength="11" />
        </a-form-item>
      </a-form>
      <!-- 提交成功 -->
      <div v-if="current === 2" class="flex flex-col items-center">
        <img class="w-88px h-88px" src="@/assets/images/15.png" alt="" srcset="">
        <div class="text-24px font-500 text-dark-500 leading-33px mt-30px mb-10px">提交成功</div>
        <div class="flex text-16px text-gray-400">
          <div>恭喜您，资料提交成功，去</div>
          <div @click="router.push('/login')" class="text-blue-500 cursor-pointer">登录</div>
        </div>
      </div>
    </div>
    <div class="w-600px flex items-center justify-between mb-100px">
      <a-button v-if="current === 1" @click="prev">上一步</a-button>
      <a-button class="w-600px mt-50px" v-if="!current" :disabled="firstDisabled" type="primary" @click="next">下一步
      </a-button>
      <a-button class="w-400px" v-if="current === 1" :disabled="submitDisabled" type="primary" @click="submit">
        提交资料
      </a-button>
    </div>
  </div>
</template>
<style lang='scss' scoped>
.avatar-uploader :deep(.ant-upload) {
  width: 150px !important;
  height: 100px !important;
}
</style>