<template>
	<view class="pvfbox">
		<view class="pvform">
			
			<view class="form-item">
				<input class="form-item--input" placeholder="姓名" v-model="formData.pernalName"/>
			</view>
			
			<view class="form-item">
				<input class="form-item--input" placeholder="身份证号" v-model="formData.pernalCard"/>
			</view>
			
			<view class="form-item">
        <picker class="picker" mode="multiSelector" :range="domicileArr" range-key="name" :value="domicileIndex" @change="pickerChange"
                @columnchange="pickerColumnchange">
          <view class="pbox" :class="{'pbox_hover':domicileStr != '请选择户籍所在地省/市/区'}">
            <view>{{domicileStr}}</view>
            <text class="iconfont icon-you"></text>
          </view>
        </picker>
			</view>
			
			<view class="form-item">
				<input  class="form-item--input" placeholder="联系地址" v-model="formData.pernalAddress"/>
			</view>
			<!-- 身份证扫描件（国徽面） -->
			<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>
			<view class="form-item" v-else>
				<button class="form-item--input" @click="chooseImage('pernalJust1')">身份证扫描件（国徽面）</button>
			</view>
      <input type="hidden" id="pernalJust1" value="">
      <!-- 身份证扫描件（人像面） -->
			<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>
			<view class="form-item" v-else>
				<button class="form-item--input" @click="chooseImage('pernalJust2')">身份证扫描件（人像面）</button>
			</view>
      <input type="hidden" id="pernalJust2" value="">
			
			<view class="form-item">
				<input class="form-item--input" placeholder="联系电话" v-model="formData.pernalPhone"/>
			</view>
			
			<view class="form-item">
				<input class="form-item--input" placeholder="邮箱地址" v-model="formData.pernalEmial"/>
			</view>
			
			<view class="form-item">
				<input class="form-item--input" placeholder="银行账户账号" v-model="formData.pernalBank"/>
			</view>
			
			<view class="form-item">
				<input class="form-item--input" placeholder="开户银行" v-model="formData.pernalOpenBank"/>
			</view>
			
			<view class="form-item">
        <picker class="picker" mode="multiSelector" :range="bankArr" range-key="name" :value="bankIndex" @change="pickerBankChange"
                @columnchange="pickerBankColumnChange">
          <view class="pbox" :class="{'pbox_hover':bankStr != '请选择开户所在地省/市/区'}">
            <view>{{bankStr}}</view>
            <text class="iconfont icon-you"></text>
          </view>
        </picker>
			</view>
			
			<view class="form-item">
				<input class="form-item--input" placeholder="开户银行预留手机号" v-model="formData.peralBankPhone"/>
			</view>
			
			<view class="form-item">
        <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>
			</view>
			
			<view class="form-item">
        <view >身份</view>
        <checkbox v-for="item in identityList" style="margin-left: 20px" v-model="item.show" color="#4399ff" class="ckbox" @click="onCalculateAmount(item.id)">{{item.saleType}}</checkbox>
			</view>
			
			<view class="form-item">
				<view>认证费用</view>
        <view>￥ {{formData.amount}}</view>
			</view>
			
			<!-- 隐私政策等 -->
			<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'

	export default {
    components: {whpop},
		data() {
			return {
        // 提交数据
        formData: {
          // 姓名
          pernalName: '',
          // 身份证号
          pernalCard: '',
          // 联系地址
          pernalAddress: '',
          // 联系电话
          pernalPhone: '',
          // 邮箱地址
          pernalEmial: '',
          // 银行账户账号
          pernalBank: '',
          // 开户银行
          pernalOpenBank: '',
          // 开户银行预留手机号
          peralBankPhone: '',
          // 推荐中介服务
          islicode: '',
          // 认证费用
          amount: '0.00',
        },
        // 身份证扫描件正反
        pernalJust1: [],
        pernalJust2: [],
        // 省市区数据
        oldRegion: region,
        // 户籍地址
        domicileStr: "请选择户籍所在地省/市/区",
        domicileIndex: [0, 0, 0],
        domicileArr: [[],[],[]],
        // 开户所在地
        bankStr: "请选择开户行所在地省/市/区",
        bankIndex: [0, 0, 0],
        bankArr: [[],[],[]],
        // 中介服务机构列表
        certiauditList: [],
        idIndex2: -1,
        // 身份列表
        identityList: [],
        // 隐私政策标识
        murl: '',
        // 显示隐私政策内容
        showPopup: false,
        // 隐私政策
        isTick: false,
        // 弹窗
        isRevise: false,
			}
		},
    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.domicileStr = this.domicileArr[0][this.domicileIndex[0]].name + ' ' + this.domicileArr[1][this.domicileIndex[1]].name + ' ' +
            this.domicileArr[2][this.domicileIndex[2]].name;
      } else {
        this.domicileStr = '请选择户籍所在地省/市/区';
        this.bankStr = '请选择开户所在地省/市/区';
      }
    },
		methods: {
      // 切换城市户籍
      pickerChange(e) {
        this.domicileIndex = e.detail.value;
        this.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.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: 'kk/'+VerifyApi.getUploadUrl(), //仅为示例，非真实的接口地址
              filePath: tempFiles[0].path,
              name: 'file',
              success: (uploadFileRes) => {
                let res = JSON.parse(uploadFileRes.data)
                if (res.resultCode != '00000000' ) {
                  alert('上传失败')
                }
                document.getElementById(item).value = 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.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.is_show = 0
                    app.identityList.push(value)
                  }
                }
                resolve()
              })
              .catch(reject)
        })
      },
      // 点击计算金额
      onCalculateAmount(id){
        const app = this;
        app.formData.amount = 0;

        for (let attr in app.identityList) {

          let value = app.identityList[attr]

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

          if (value.is_show === 1) {
            app.formData.amount += value.fee * 1
          }

        }
      },
      /**
       * 阅读注册协议和隐私
       */
      gotopage(str){
        this.murl = str
        this.showPopup = ! this.showPopup
      },
      readpri() {
        this.isTick = true;
      },
      // 提交认证
      handleSubmit() {
        const app = this;

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

        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.domicileStr
        let domicileArr = domicileStr.split(" ")
        // 身份证正反面
        let pernalJust1 = document.getElementById('pernalJust1').value;
        let pernalJust2 = document.getElementById('pernalJust2').value;
        // 开户所在地
        let bankStr = app.bankStr
        let bankArr = bankStr.split(" ")
        // 买卖方类型
        let saleTypeTemp = []
        let identityList = app.identityList
        for (let attr in identityList) {
          let saleTypeData = identityList[attr]
          if (saleTypeData.is_show === 1) {
            saleTypeTemp.push(saleTypeData.saleType)
          }
        }
        let saleType = saleTypeTemp.join(',')

        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.islicode, // 推荐中介服务机构 中介机构is
          isposttion: 0, // 是否后置名单(0、否 1、是 )
          saleType: saleType, //买卖方类型
          fees: app.formData.amount, //总费用
          updateat: "",
          userid: accountId,
          usertype: "个人"
        }
        let validateRes = app.submitDataValidate(peopledata)
        if (validateRes < 1) {
          return false
        }

        VerifyApi.preservation(agreement)
        let res = VerifyApi.verifySubmit(peopledata)
        uni.navigateTo({
          url:"/pages/user/index"
        })
      },
      // 验证必填
      submitDataValidate(data) {
        const app = this
        let validateData = [
          {key: 'name', title: '姓名'},
          {key: 'uscc', title: '身份证号'},
          {key: 'regionprovince', title: '户籍所在地'},
          {key: 'address', title: '详细地址'},
          {key: 'establishdate', title: '机构成立日期'},
          {key: 'desc', title: '机构简介'},
          {key: 'cerscanpath1', title: '个人身份证扫正面描件'},
          {key: 'cerscanpath2', title: '个人身份证扫反面描件'},
          {key: 'contactscellphone', title: '联系电话'},
          {key: 'contactsemail', title: '邮箱地址'},
          {key: 'publicaccount', title: '对公账户号'},
          {key: 'bankname', title: '开户银行名称'},
          {key: 'bankprovince', title: '开户银行所在地'},
          {key: 'bankcellphone', title: '开户银行预留手机号'},
          {key: 'parentislicode', title: '推荐中介服务机构'}
        ]

        for (let i in validateData) {
          let dateVal = validateData[i]
          let val = data[dateVal.key]
          if (val === '' || val === null || val === undefined) {
            app.$error(dateVal.title + '不能为空')
            return 0
          }
        }

        return 1;
      }
		}
	}
</script>

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

	}
	
	// 登录按钮
	.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;
		}
	}
	
	.image-list {
	  display: flex;
	  padding: 0 20rpx;
	  margin-top: 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
	}
	
}
</style>
