<template>
	<view class="container">
		<view class="head">
			<view>
				<uni-group mode="card">
				<uni-icons custom-prefix="iconfont" type="icon-dengpao" :color="primaryColor" size="20"></uni-icons><text class="textstyle text-white">小贴士：</text><br/>
					<text class="textstyle">1. 为了您的资金安全及合规，体现将通过第三方支付提供安全通道实现。</text><br/>
					<text class="textstyle">2. 应银行监管要求，每人每月限额10万元，最多绑定4个收款账户。</text><br/>
					<text class="textstyle">3. 一旦提现成功,设置的收款账户不可更改。</text>
				</uni-group>
			</view>
			<view>
				<uni-group mode="card">
				<uni-forms validate-trigger='blur' :modelValue="accountInfo" label-position="top" labelWidth="80" ref="form">
					<uni-forms-item label="真实姓名" required name="name">
						<uni-easyinput v-model="accountInfo.name" placeholder="请输入真实姓名"
                           :clearable="false"
                           :inputBorder="false"/>
					</uni-forms-item>
					<uni-forms-item label="身份证号" required name="idNo">
						<uni-easyinput v-model="accountInfo.idNo" placeholder="请输入身份证号"
                           :clearable="false"
                           :inputBorder="false" />
					</uni-forms-item>
          <uni-forms-item label="请选择" required>
            <uni-data-checkbox v-model="type"
                               :localdata="typeList"
                               :selectedColor="primaryColor"
                               :selectedTextColor="'#FFFFFF'">
            </uni-data-checkbox>
          </uni-forms-item>
					<uni-forms-item :label="(type === 0 ? '微信' : type === 2 ? '支付宝' : '') + '账号'" required name="accountNo">
						<uni-easyinput v-model="accountInfo.accountNo" placeholder="请输入收款账号"
                           :clearable="false"
                           :inputBorder="false" />
					</uni-forms-item>
          <uni-forms-item v-if="type === 0" label="微信收款码" required name="imgUrl">
            <uni-file-picker limit="1" file-mediatype="image" title="请上传微信收款码!" file-extname="png,jpg,jpeg"
                             @select="selectImage" @delete="deleteImg">
            </uni-file-picker>
          </uni-forms-item>
					<uni-forms-item label="预留电话" required name="phone">
						<uni-easyinput v-model="accountInfo.phone" placeholder="请输入预留电话"
                           :clearable="false"
                           :inputBorder="false" />
					</uni-forms-item>
				</uni-forms>
				</uni-group>
			</view>
		</view>
		<view class="foot">
			<view>
				<button class="confirmBtn" size="default" @click="$noMultipleClicks(submitAccount)">确定添加</button>
			</view>
			<view class="textstyle">
        本人确认已同意并遵守<navigator url="/pages-userInfo/setting/compoSign" :style="{color: primaryColor, display: 'contents'}">《艺术家合作协议》</navigator> 及
          <navigator url="/pages-userInfo/setting/secretSign" :style="{color: primaryColor, display: 'contents'}">《艺术家隐私协议》</navigator>的基础上，承诺已阅读并同意遵守
          <navigator url="/pages-userInfo/setting/secretSign" :style="{color: primaryColor, display: 'contents'}">《共享经济合作合办协议》</navigator>，按照协议内容提供合法合规服务。
			</view>
		</view>
	</view>
</template>

<script>
	import {
		addCreatorAccount,
		checkAccountExist,checkAccountUpToFour
	} from '@/api/userInfo.js'
	export default {
		data() {
			return {
        primaryColor: '#0b6375',
				userInfo: {},
				existFlag: false,
				upToFourFlag: false,
				noClick:true, //防止重复提交
        fileList: [],
				accountInfo:{
					name:'',
					idNo:'',
					accountNo:'',
					phone:'',
          imgUrl: ''
				},
        type: 0,
        typeList: [{
          text: '微信',
          value: 0
        }, {
          text: '支付宝',
          value: 2
        }],
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名'
						}, {
							minLength: 2,
							maxLength: 4,
							errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符'
						}]
					},
					idNo: {
						rules: [{
							required: true,
							errorMessage: '请输入身份证号'
						},{
							pattern: /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|30|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|X)$/,
							errorMessage: '请输入正确的身份证号'
						}]
					},
					accountNo: {
						rules: [
							{
								required: true,
								errorMessage: '请输入收款账号'
							},
							{
								validateFunction: this.checkAccount,
							}
						]
					},
          imgUrl: {
            rules: [{
              required: true,
              errorMessage: '请选择一张头像图片上传'
            }
            ]
          },
					phone: {
						rules: [{
								required: true,
								errorMessage: '请输入手机号'
							},
							{
								pattern: '^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$',
								errorMessage: '请输入正确的手机号'
							},
							{
								validateFunction: (data) => {
									// 异步需要返回 Promise 对象
									return new Promise((resolve, reject) => {
										if (data.length = 11) {
											resolve()
										} else {
											reject(new Error('手机号长度应为11个字符'))
										}
									})
								}
							}
						]
					}
				}
				
			}
		},
		mounted() {
			//设置校验规则
			this.$refs.form.setRules(this.rules);
		},
		created() {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.showModal({
					content: '艺术家账户过期,请重新登录！',
					showCancel: false,
					success() {
						//没有缓存则跳转登录页面
						uni.reLaunch({
							url: '/pages/login/login'
						});
					}
				});
			} else {
				this.userInfo = userInfo;
			}
			
			this.checkAccountUpToFour();
		},
		
		methods: {
			//检查收款账户是否超过4个
			async checkAccountUpToFour() {
			  const res = await checkAccountUpToFour(this.userInfo.id);
			  if (res.data.code === 200) {
          this.upToFourFlag = res.data.data == true;
			  } else {
          uni.showModal({
            content: '检查收款账户失败！',
            showCancel: false
          });
			  }
			},
			
			//检查艺术家收款账户是否存在
			checkAccount() {
				return new Promise((resolve, reject) => {
					let that = this;
					const param = {
						creatorId: that.userInfo.id,
						accountNo:that.accountInfo.accountNo
					}
          checkAccountExist(param).then(res => {
						if (res.data.code === 200) {
							if(res.data.data !== true){
								//不存在则放行，存在则提示
								that.existFlag = false;
								return resolve();
							}else{
								that.existFlag = true;
								return reject(new Error('该收款账户已存在'))
							}
						}else{
							uni.showModal({
								content: '检查收款账户失败！',
								showCancel: false
							});
						}
					});
				});
			},
      selectImage(e) {
        if (!e.tempFiles) {
          return;
        }
        let that = this;
        that.fileList = [...that.fileList, ...e.tempFilePaths];
        that.accountInfo.imgUrl = e.tempFilePaths[0];
      },//删除图片
      deleteImg(e) {
        let that = this
        that.fileList = [];
        that.accountInfo.imgUrl = ''
      },
      //图片上传
      uploadImg: async function (e) {
        let that = this;
        uni.showLoading({
          title: "上传中"
        });
        const tempFilePaths = e;
        for (let i = 0; i < tempFilePaths.length; i++) {
          const [error, res] = await uni.uploadFile({
            url: `${that.$baseURL}${that.$uploadURL}`,
            filePath: tempFilePaths[i],
            name: `${that.$uploadType}`,
            header:{
              "Content-Type": "multipart/form-data"
            },
          })
          const back = JSON.parse(res.data);
          if (back.code === 200) {
            that.accountInfo.imgUrl = back.data;
          }
        }
        uni.hideLoading()
        that.submitFormDataA(that);
      },
			//保存数据并跳转
			submitAccount() {
        let that = this;
        that.$refs.form.validate([], (err, formData) => {
          if (!err) {
            if(that.existFlag === true){
              uni.showModal({
                content: '收款账户已存在！',
                showCancel: false
              });
            }else{
              if(that.upToFourFlag === true){
                uni.showModal({
                  content: '绑定收款账户已达最大上限！',
                  showCancel: false,
                  success() {
                    uni.redirectTo({
                      url: '/pages-userInfo/creatorAccount/creatorAccount'
                    })
                  }
                });
              }else{
                if (that.type === 0) {
                  that.uploadImg(that.fileList)
                } else {
                  that.submitFormDataA(that);
                }
              }
            }
          } else  {
            uni.showToast({
              title: '表单验证未通过,请更正后提交!',
              icon: 'none',
              duration: 3000
            })
          }
        })
			},
			submitFormDataA: (e) => {
        let that = e;
        const param = {
          creatorId: that.userInfo.id,
          name: that.accountInfo.name,
          idNo: that.accountInfo.idNo,
          phone:that.accountInfo.phone,
          accountNo:that.accountInfo.accountNo,
          type: that.type //此处默认先添加为支付宝账户，后续微信支付了即可添加微信
        }
        if (param.type === 0) { //上传收款码
          param.imgUrl = that.accountInfo.imgUrl
        }
        //新增艺术家账户
        addCreatorAccount(param).then(res => {
          if (res.data.code === 200) {
            uni.hideLoading();
            uni.showToast({
              title:'添加成功!',
              duration: 1500,
              success() {
                setTimeout(function () {
                  uni.reLaunch({
                    url: '/pages-userInfo/creatorAccount/creatorAccount'
                  })
                }, 1500);
              }
            })
          }else{
            uni.showModal({
              content: '添加收款账户失败！',
              showCancel: false
            });
          }
        });
      },
			//跳转到置顶路径
			goto:function(url){
				uni.navigateTo({
					url: url
				})
			},
		},
    watch: {
		  type(newVal) {
		    if (newVal !== 0) {
          this.fileList = [];
          this.accountInfo.imgUrl = '';
        }
      }
    }
	}
</script>

<style lang="scss" scoped>
.container {
  width: 670rpx;
  height: 100vh;
  margin: 0 auto;
  position: relative;
}

.head {

  ::v-deep .uni-group--card {
    margin: 0 0 40rpx 0 !important;
    background: $uni-bg-base-color;
  }

  ::v-deep .uni-tag {
    border-width: 2rpx !important;
  }

  ::v-deep .uni-forms-item__label {
    color: $uni-white;
  }

  ::v-deep input {
    background: $uni-bg-base-color !important;
    border: 0 !important;
    color: $uni-white !important;
  }

  ::v-deep .uni-file-picker__header {
    .file-title {
      font-size: 24rpx;
      color: #999;
    }
    .file-count {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.foot {

}

.confirmBtn{
  color: $uni-btn-text-color;
}

.textstyle{
  font-size: 26rpx;
  color: $uni-secondary-color;
  padding-top: 10rpx;
  padding-bottom: 40rpx;
}

.text-white {
  color: $uni-white !important;
}

.specialText{
  color: $uni-primary;
  font-size: 26rpx;
}
	
</style>
