<template>
	<view class="pvfbox">
		<view class="pvform">

      <uni-forms ref="valiForm" :modelValue="formData">
        <uni-forms-item class="form-item" label="姓名" name="pernalName" required>
          <uni-easyinput v-model="formData.pernalName" type="text" placeholder="请输入姓名" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="身份证号" name="pernalCard" required>
          <uni-easyinput v-model="formData.pernalCard" type="text" placeholder="请输入身份证号" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="户籍所在地" name="domicileStr" required>
          <picker class="picker picker_select" mode="multiSelector" :range="domicileArr" range-key="name" :value="domicileIndex" @change="pickerChange"
                  @columnchange="pickerColumnchange">
            <view class="pbox" >
              <view>{{formData.domicileStr === '' ? '请点击选择户籍所在地' : formData.domicileStr}}</view>
              <text class="iconfont icon-you"></text>
            </view>
          </picker>
        </uni-forms-item>
        <uni-forms-item class="form-item" label="联系地址" name="pernalAddress" required>
          <uni-easyinput v-model="formData.pernalAddress" type="text" placeholder="请输入联系地址" />
        </uni-forms-item>
        <!-- 身份证扫描件（国徽面） -->
        <uni-forms-item class="form-item" :class="{ view_show_image: pernalJust1!=''}" label="身份证扫描件（国徽面）" name="pernalJust1" required>
          <view class="image-list" v-if="pernalJust1!=''">
            <view class="image-preview" v-for="(image, imageIndex) in pernalJust1[0]">
              <image class="image" mode="aspectFill" :src="image.path"></image>
            </view>
          </view>
          <button class="form-item--input" @click="chooseImage('pernalJust1')" v-else>身份证扫描件（国徽面）</button>
          <input type="text" class="image_url" v-model="formData.pernalJust1">
        </uni-forms-item>
        <!-- 身份证扫描件（人像面） -->
        <uni-forms-item class="form-item" :class="{ view_show_image: pernalJust2!=''}" label="身份证扫描件（国徽面）" name="pernalJust2" required>
          <view class="image-list" v-if="pernalJust2!=''">
            <view class="image-preview" v-for="(image, imageIndex) in pernalJust2[0]">
              <image class="image" mode="aspectFill" :src="image.path"></image>
            </view>
          </view>
          <button class="form-item--input" @click="chooseImage('pernalJust2')" v-else>身份证扫描件（人像面）</button>
          <input type="hidden" class="image_url" v-model="formData.pernalJust2">
        </uni-forms-item>

        <uni-forms-item class="form-item" label="联系电话" name="pernalPhone" required>
          <uni-easyinput v-model="formData.pernalPhone" type="text" placeholder="请输入联系电话" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="邮箱地址" name="pernalEmial" required>
          <uni-easyinput v-model="formData.pernalEmial" type="text" placeholder="请输入邮箱地址" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="银行账户账号" name="pernalBank" required>
          <uni-easyinput v-model="formData.pernalBank" type="text" placeholder="请输入银行账户账号" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="开户银行" name="pernalOpenBank" required>
          <uni-easyinput v-model="formData.pernalOpenBank" type="text" placeholder="请输入开户银行" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="开户所在地" name="bankStr" required>
          <picker class="picker picker_select" mode="multiSelector" :range="bankArr" range-key="name" :value="bankIndex" @change="pickerBankChange"
                  @columnchange="pickerBankColumnChange">
            <view class="pbox">
              <view>{{formData.bankStr === '' ? '请点击选择开户所在地' : formData.bankStr}}</view>
              <text class="iconfont icon-you"></text>
            </view>
          </picker>
        </uni-forms-item>
        <uni-forms-item class="form-item" label="开户银行预留手机号" name="peralBankPhone" required>
          <uni-easyinput v-model="formData.peralBankPhone" type="text" placeholder="请输入开户银行预留手机号" />
        </uni-forms-item>
        <uni-forms-item class="form-item" label="推荐中介服务机构" name="islicode" required>
          <picker mode="selector" :range="certiauditList" range-key="name" :value="idIndex2" @change="onChangeCertiaudit">
            <text v-if="idIndex2 > -1">{{ certiauditList[idIndex2].name }}</text>
            <text v-else class="col-80">推荐中介服务机构</text>
          </picker>
        </uni-forms-item>
        <uni-forms-item class="form-item" label="身份" name="saleType" required>
          <checkbox v-for="item in identityList" v-model="item.show" color="#4399ff" class="ckbox title_left_radio title_content" @click="onCalculateAmount(item.id)">{{item.saleType}}</checkbox>
        </uni-forms-item>

        <uni-forms-item class="form-item" label="认证费用" name="fee">
          <view class="title_content">￥{{formData.fee}}</view>
        </uni-forms-item>
      </uni-forms>
			
			<!-- 隐私政策等 -->
			<view class="privacy">
				<checkbox :checked="isTick" color="#4399ff" class="ckbox" @click="readpri"></checkbox>
				<view class="">
					我已阅读并同意网站的 《<text class="atxt" @click="gotopage('trading')">交易主体进场协议</text> 》和
					《<text class="atxt" @click="gotopage('commission')">文化数据交易委托协议</text>》和
					《<text class="atxt" @click="gotopage('business')">临时业务机构委托协议</text>》
				</view>
			</view>

      <!-- 协议弹框 -->
      <whpop v-model="showPopup" :maskCloseAble="true" :mkey="murl"></whpop>
			
			<!-- 提交按钮 -->
			<view class="vf-button" @click="handleSubmit">
			  <text>提交认证</text>
			</view>
		
		</view>
	</view>
</template>

<script>

  import * as VerifyApi from '@/api/verify'
  import whpop from '../../login/components/WhPopup'
  import region from "../../../utils/json/pca.json";
  import { returnAccountId } from '@/core/app'
  import uniForms from '../../../uni_modules/uni-forms/components/uni-forms/uni-forms';
  import uniFormsItem from '../../../uni_modules/uni-forms/components/uni-forms-item/uni-forms-item'
  import uniEasyinput from '../../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput'
  import uniDataCheckbox from '../../../uni_modules/uni-data-checkbox/components/uni-data-checkbox/uni-data-checkbox'

	export default {
    components: {whpop,uniForms,uniFormsItem,uniEasyinput,uniDataCheckbox},
		data() {
			return {
        // 提交数据
        formData: {
          // 姓名
          pernalName: '',
          // 身份证号
          pernalCard: '',
          // 户籍地址
          domicileStr: '',
          // 联系地址
          pernalAddress: '',
          // 联系电话
          pernalPhone: '',
          // 邮箱地址
          pernalEmial: '',
          // 银行账户账号
          pernalBank: '',
          // 开户银行
          pernalOpenBank: '',
          // 开户银行预留手机号
          peralBankPhone: '',
          // 开户所在地
          bankStr: '',
          // 推荐中介服务
          islicode: '',
          // 认证费用
          fee: '0.00',
          // 身份
          saleType: '',
          // 身份证正面
          pernalJust1: '',
          // 身份证反面
          pernalJust2: '',
        },
        rules: {
          pernalName: {
            rules: [{
              required: true,
              errorMessage: '姓名不能为空'
            }]
          },
          pernalCard: {
            rules: [
              {
                required: true,
                errorMessage: '身份证号不能为空'
              },
              {
                validateFunction: function (rule, value, data, callback) {
                  let pattern = /^\d{17}[\dXx]$/;
                  if (!pattern.test(value)) {
                    callback('请输入正确的身份证号')
                  }
                }
              }
            ]
          },
          domicileStr: {
            rules: [{
              required: true,
              errorMessage: '请点击选择户籍所在地'
            }]
          },
          pernalAddress: {
            rules: [{
              required: true,
              errorMessage: '联系地址不能为空'
            }]
          },
          pernalJust1: {
            rules: [{
              required: true,
              errorMessage: '请点击上传身份证扫描件正面'
            }]
          },
          pernalJust2: {
            rules: [{
              required: true,
              errorMessage: '请点击上传身份证扫描件反面'
            }]
          },
          pernalPhone: {
            rules: [
              {
                required: true,
                errorMessage: '联系电话不能为空'
              },
              {
                validateFunction: function (rule, value, data, callback) {
                  let pattern = /^1[3-9]\d{9}$/;
                  if (!pattern.test(value)) {
                    callback('请输入正确的联系电话')
                  }
                }
              }
            ]
          },
          pernalEmial: {
            rules: [{
              required: true,
              errorMessage: '邮箱地址不能为空'
            }]
          },
          pernalBank: {
            rules: [{
              required: true,
              errorMessage: '银行账号不能为空'
            }]
          },
          pernalOpenBank: {
            rules: [{
              required: true,
              errorMessage: '开户行不能为空'
            }]
          },
          bankStr: {
            rules: [{
              required: true,
              errorMessage: '开户行所在地不能为空'
            }]
          },
          peralBankPhone: {
            rules: [
              {
                required: true,
                errorMessage: '开户银行预留手机号不能为空'
              },
              {
                validateFunction: function (rule, value, data, callback) {
                  let pattern = /^1[3-9]\d{9}$/;
                  if (!pattern.test(value)) {
                    callback('请输入正确的开户银行预留手机号')
                  }
                }
              }
            ]
          },
          islicode: {
            rules: [{
              required: true,
              errorMessage: '请点击选择推荐中介服务'
            }]
          },
          saleType: {
            rules: [{
              required: true,
              errorMessage: '请至少选择一种身份'
            }]
          },
        },
        // 身份证扫描件正反
        pernalJust1: [],
        pernalJust2: [],
        // 省市区数据
        oldRegion: region,
        // 户籍地址
        domicileIndex: [0, 0, 0],
        domicileArr: [[],[],[]],
        // 开户所在地
        bankIndex: [0, 0, 0],
        bankArr: [[],[],[]],
        // 中介服务机构列表
        certiauditList: [],
        idIndex2: -1,
        // 身份列表
        identityList: [],
        // 隐私政策标识
        murl: '',
        // 显示隐私政策内容
        showPopup: false,
        // 隐私政策
        isTick: false,
        // 弹窗
        isRevise: false,
			}
		},
    onReady() {
      // 需要在onReady中设置规则
      this.$refs.valiForm.setRules(this.rules)
    },
    mounted() {
      // 页面初始化
      this.getCertiauditList()
      this.getSelectCertificationFee()
    },
    created() {
      // 省市区选择
      let provinceArr = [];
      let cityArr = [];

      this.oldRegion.map((item, index) => {
        this.domicileArr[0].push({
          name: item.name,
          code: item.code
        });
        this.bankArr[0].push({
          name: item.name,
          code: item.code
        });
        if (this.domicileArr[0][0].code == item.code) {
          provinceArr = item.children;
          this.domicileIndex[0] = index;
        }
      })
      provinceArr.map((item, index) => {
        this.domicileArr[1].push({
          name: item.name,
          code: item.code
        });
        this.bankArr[1].push({
          name: item.name,
          code: item.code
        });
        if (this.domicileArr[1][0].code == item.code) {
          cityArr = item.children;
          this.domicileIndex[1] = index;
        }
      })
      cityArr.map((item, index) => {
        this.domicileArr[2].push({
          name: item.name,
          code: item.code
        });
        this.bankArr[2].push({
          name: item.name,
          code: item.code
        });
        if (this.domicileArr[2][0].code == item.code) {
          this.domicileIndex[2] = index;
        }
      })
      if (this.isRevise) {
        this.formData.domicileStr = this.domicileArr[0][this.domicileIndex[0]].name + ' ' + this.domicileArr[1][this.domicileIndex[1]].name + ' ' +
            this.domicileArr[2][this.domicileIndex[2]].name;
      } else {
        // this.formData.domicileStr = '请选择户籍所在地省/市/区';
        // this.formData.bankStr = '请选择开户所在地省/市/区';
      }
    },
		methods: {
      // 切换城市户籍
      pickerChange(e) {
        this.domicileIndex = e.detail.value;
        this.formData.domicileStr = this.domicileArr[0][this.domicileIndex[0]].name + ' ' + this.domicileArr[1][this.domicileIndex[1]].name + ' ' +
            this.domicileArr[2][this.domicileIndex[2]].name;

        // 组件传值
        this.$emit('domicileArr', [this.domicileArr[0][this.domicileIndex[0]].name , this.domicileArr[1][this.domicileIndex[1]].name,
          this.domicileArr[2][this.domicileIndex[2]].name]);
      },
      // 选择城市信息 户籍
      pickerColumnchange(e) {

        if (e.detail.column === 0) {
          // 声明城市数组
          let cityArr = [];
          let countyArr = [];
          // 设置下标
          this.domicileIndex = [e.detail.value, 0, 0];
          // 改变城市列表
          this.domicileArr[1] = this.oldRegion[e.detail.value].children.map(item => {
            cityArr.push({
              name: item.name,
              code: item.code
            });
          })
          this.$set(this.domicileArr, 1, cityArr);
          // 改变县区列表
          this.oldRegion[e.detail.value].children[0].children.map(item => {
            countyArr.push({
              name: item.name,
              code: item.code
            });
          })
          this.$set(this.domicileArr, 2, countyArr);
        }
        if (e.detail.column === 1) {
          this.domicileIndex[1] = e.detail.value;
          this.domicileIndex[2] = 0;
          let countyArr = [];
          this.oldRegion[this.domicileIndex[0]].children[this.domicileIndex[1]].children.map(item => {
            countyArr.push({
              name: item.name,
              code: item.code
            });
          })
          this.$set(this.domicileArr, 2, countyArr);
        }
        if (e.detail.column === 2) {
          this.domicileIndex[2] = e.detail.value;
        }
      },
      // 切换城市 开户
      pickerBankChange(e) {
        this.bankIndex = e.detail.value;
        this.formData.bankStr = this.bankArr[0][this.bankIndex[0]].name + ' ' + this.bankArr[1][this.bankIndex[1]].name + ' ' +
            this.bankArr[2][this.bankIndex[2]].name;

        // 组件传值
        this.$emit('bankArr', [this.bankArr[0][this.bankIndex[0]].name , this.bankArr[1][this.bankIndex[1]].name,
          this.bankArr[2][this.bankIndex[2]].name]);
      },
      // 选择城市信息 开户
      pickerBankColumnChange(e) {
        if (e.detail.column === 0) {
          // 声明城市数组
          let cityArr = [];
          let countyArr = [];
          // 设置下标
          this.bankIndex = [e.detail.value, 0, 0];
          // 改变城市列表
          this.bankArr[1] = this.oldRegion[e.detail.value].children.map(item => {
            cityArr.push({
              name: item.name,
              code: item.code
            });
          })
          this.$set(this.bankArr, 1, cityArr);
          // 改变县区列表
          this.oldRegion[e.detail.value].children[0].children.map(item => {
            countyArr.push({
              name: item.name,
              code: item.code
            });
          })
          this.$set(this.bankArr, 2, countyArr);
        }
        if (e.detail.column === 1) {
          this.bankIndex[1] = e.detail.value;
          this.bankIndex[2] = 0;
          let countyArr = [];
          this.oldRegion[this.bankIndex[0]].children[this.bankIndex[1]].children.map(item => {
            countyArr.push({
              name: item.name,
              code: item.code
            });
          })
          this.$set(this.bank, 2, countyArr);
        }
        if (e.detail.column === 2) {
          this.bankIndex[2] = e.detail.value;
        }
      },
      // 选择图片
      chooseImage( item) {
        const app = this
        const oldImageList = app.$data[item]
        // 选择图片
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success({ tempFiles }) {
            oldImageList.push(tempFiles)
            uni.uploadFile({
              url: VerifyApi.getUploadUrl(), //仅为示例，非真实的接口地址
              filePath: tempFiles[0].path,
              name: 'file',
              success: (uploadFileRes) => {
                let res = JSON.parse(uploadFileRes.data)
                if (res.resultCode != '00000000' ) {
                  app.$error('上传失败')
                }
                app.formData[item] = res.data
              }
            })
          }
        })
      },
      // 机构列表
      getCertiauditList(){
        const app = this
        return new Promise((resolve, reject) => {
          VerifyApi.getCertiaudit()
              .then(result => {
                app.certiauditList = result.data
                resolve()
              })
              .catch(reject)
        })
      },
      // 选择中介服务机构
      onChangeCertiaudit(e) {
        const curIndex = e.detail.value
        this.idIndex2 = curIndex
        this.formData.islicode = this.certiauditList[curIndex].islicode
      },
      // 获取身份，认证费用
      getSelectCertificationFee(){
        const app = this
        return new Promise((resolve, reject) => {
          VerifyApi.getIdentity()
              .then(result => {
                let data = result.data
                for (let attr in data) {
                  let value = data[attr]
                  if (value.userType == '个人') {
                    value.checked = 0
                    app.identityList.push(value)
                  }
                }
                resolve()
              })
              .catch(reject)
        })
      },
      // 点击计算金额
      onCalculateAmount(id){
        const app = this;
        app.formData.fee = 0;
        let saleTypeTemp = []

        for (let attr in app.identityList) {

          let value = app.identityList[attr]

          if (id === value.id) {
            if (value.checked === 1) {
              app.identityList[attr].checked = 0
              value.checked = 0
            } else {
              app.identityList[attr].checked = 1
              value.checked = 1
            }
          }

          if (value.checked === 1) {
            app.formData.fee += value.fee * 1
            saleTypeTemp.push(value.saleType)
          }

        }

        app.formData.saleType = saleTypeTemp.join(',')
      },
      /**
       * 阅读注册协议和隐私
       */
      gotopage(str){
        this.murl = str
        this.showPopup = ! this.showPopup
      },
      readpri() {
        this.isTick = true;
      },
      // 提交认证
      handleSubmit() {
        const app = this;
        uni.showLoading()
        this.$refs.valiForm.validate().then(res => {
          uni.hideLoading()

          if (!app.isTick) {
            app.$error('请勾选《交易主体进场协议》和《文化数据交易委托协议》和《临时业务机构委托协议》')
            return false
          }

          let accountId = returnAccountId()
          if (accountId === '') {
            app.$error('登录已失效，请前往登录')
            uni.navigateTo({
              url:"/pages/login/index"
            })
            return false
          }

          let agreement = {
            agreementIds: "4,5,6",
            userId: accountId
          }

          // 户籍所在地
          let domicileStr = app.formData.domicileStr
          let domicileArr = domicileStr.split(" ")
          // 身份证正反面
          let pernalJust1 = app.formData.pernalJust1;
          let pernalJust2 = app.formData.pernalJust2;
          // 开户所在地
          let bankStr = app.formData.bankStr
          let bankArr = bankStr.split(" ")
          // 买卖方类型
          let saleType = app.formData.saleType

          let peopledata = {
            name: app.formData.pernalName, // 姓名
            uscc: app.formData.pernalCard, // 身份证号
            regionprovince: domicileArr[0], // 户籍所在地-省
            regioncity: domicileArr[1], // 户籍所在地-市
            regiondistrict: domicileArr[2], // 户籍所在地-区
            address: app.formData.pernalAddress, // 详细地址
            cerscanpath1: pernalJust1, // 个人身份证扫正面描件url
            cerscanpath2: pernalJust2, // 个人身份证扫反面描件url
            contactscellphone: app.formData.pernalPhone, // 联系电话
            contactsemail: app.formData.pernalEmial, // 邮箱地址
            publicaccount: app.formData.pernalBank, // 对公账户号
            bankname: app.formData.pernalOpenBank, // 开户银行名称
            bankprovince: bankArr[0], // 开户银行所在地-省
            bankcity: bankArr[1], // 开户银行所在地-市
            bankdistrict: bankArr[2], // 开户银行所在地-区/县
            bankcellphone: app.formData.peralBankPhone, // 开户银行预留手机号
            parentislicode: app.formData.islicode, // 推荐中介服务机构 中介机构is
            isposttion: 0, // 是否后置名单(0、否 1、是 )
            saleType: saleType, //买卖方类型
            fees: app.formData.fee, //总费用
            updateat: "",
            userid: accountId,
            usertype: "个人"
          }


          VerifyApi.preservation(agreement)
          return new Promise((resolve, reject) => {
            VerifyApi.verifySubmit(peopledata)
                .then(result => {
                  if (result.resultCode != '00000000') {
                    app.$error('提交认证失败')
                  } else {
                    app.$success('认证提交成功')
                    uni.navigateTo({
                      url:"/pages/user/index"
                    })
                  }
                  resolve()
                })
                .catch(reject)
          })
        }).catch(err => {
          uni.hideLoading()
          return false
        })
      },
		}
	}
</script>

<style scoped lang="scss">
.pvfbox{
	width: 100%;
	background: #fff;
	
	.pvform{
		padding: 10rpx;
		
	}
	
	// 输入框元素
	.form-item {
	  display: flex;
	  padding: 18rpx;
	  margin-bottom: 30rpx;
	  height: 96rpx;
	
	  &--input {
		font-size: 28rpx;
		letter-spacing: 1rpx;
		flex: 1;
		height: 100%;
	  }
	
	  &--parts {
		min-width: 100rpx;
		height: 100%;
	  }

    .picker_select {
      margin-top: 18rpx;
    }

    .title_content {
      margin-top: 12rpx!important;
    }

    .image_url {
      display: none;
    }
	}
	
	// 登录按钮
	.vf-button {
	  width: 100%;
	  height: 86rpx;
	  margin-top: 80rpx;
	  background: linear-gradient(to right, #242e4b, #242e4b);
	  color: #fff;
	  // border-radius: 80rpx;
	  box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.1);
	  letter-spacing: 5rpx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	}
	// 协议
	.privacy{
		display: flex;
		margin-top: 10rpx;
		
		.ckbox{
			border-radius: 50%;
		}
		
		.atxt{
			color: #4399ff;
		}
	}

  .view_show_image {
    margin-bottom: 110rpx;
  }
	
	.image-list {
	  display: flex;
	  padding: 0 20rpx;
	  margin-bottom: -20rpx;
	
	  &:after {
	    clear: both;
	    content: " ";
	    display: table;
	  }
	
	  .image {
	    display: block;
	    width: 100%;
	    height: 100%;
	  }
	
	  .image-picker,.image-preview {
	    width: 196rpx;
	    height: 196rpx;
	    margin-right: 30rpx;
	    margin-bottom: 30rpx;
	    float: left;
	
	    &:nth-child(3n+0) {
	      margin-right: 0;
	    }
	  }
	
	  .image-picker {
	    display: flex;
	    flex-direction: column;
	    justify-content: center;
	    align-items: center;
	    border: 1rpx dashed #ccc;
	    color: #ccc;
	
	    .choose-icon {
	      font-size: 48rpx;
	      margin-bottom: 6rpx;
	    }
	
	    .choose-text {
	      font-size: 24rpx;
	    }
	  }
	
	  .image-preview {
	    position: relative;
	
	    .image-delete {
	      position: absolute;
	      top: -15rpx;
	      right: -15rpx;
	      height: 42rpx;
	      width: 42rpx;
	      line-height: 42rpx;
	      background: rgba(0, 0, 0, 0.64);
	      border-radius: 50%;
	      color: #fff;
	      font-weight: bolder;
	      font-size: 22rpx;
	      z-index: 10;
	      text-align: center;
	    }
	  }
	  // endl
	}

  .title_left_radio {
    margin-right: 20rpx;
  }
	
}
</style>
