<!--  -->
<template>
  <div class="">
    <p-PageForm ref="PageForm" :showHelp="true" :formDataList="formDataList" :PEvent="PEvent"  :layout="layout" :formRules="formRules"></p-PageForm>
    <a-button type="primary" @click="expression">
      Primary
    </a-button>
  </div>
</template>

<script>
import OSS from "ali-oss";
export default {
  // import引入的组件需要注入到对象中才能使用
  name: 'form',
  components: {},
  props: {
    // handA: {
    //   type: String,
    //   required: true,
    //   default: '100'
    // }
  },
  data() {
    // 这里存放数据
    let validatePass2 = (self,fieldName,msg,rule, value, callback ) => {
      console.log('#### 0==========>',fieldName,self, value);
      let url = self.formVAl[fieldName].card1.url || ''
      // let url =  ''
      console.log('#### 1==========>',fieldName,url,self);
      console.log( self.formDataList[8].value);
      

      if (url === '') {
        callback(new Error(`请上传${msg}文件`));
      }  else {
        callback();
      }
    };
    return {
        formVAl:{},
        layout:{ rowNum: 4, columnNum: 3, rowGap: "10px", rowHeight:'100px', coliumnGap: "10px", labelCol: { span: 4 }, wrapperCol: { span: 14 }},
        formRules:{
         
          'userName4':[
            { required: true, message: '请上传文件', trigger: 'blur' },
            { required: true,validator: (...args)=>{validatePass2(this,'userName4','任职受雇信息截图',...args)} }
          ],
          'userName8':[
            { required: true, message: 'userName8', trigger: 'blur' },
          ],
        },
        formDataList:[
            { enName:'userName5', cnName:'用户名5', type:'label',value:'1111'},
            { enName:'userName6', cnName:'用户名6', type:'label',value:'2222'},
            { enName:'userName9', cnName:'用户名9', type:'input',value:'', componentName:'Pbutton', componentItem:null, numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{},optionList:[],isChangeEvent:true,},
            { enName:'userName7', cnName:'用户名7', type:'input',value:''},
            { enName:'userName8', cnName:'用户名8', type:'input',value:''},
            { enName:'userName1', cnName:'用户名1', type:'input',value:''},
            { enName:'userName2', cnName:'用户名2', type:'input',value:''},
            { enName:'userName3', cnName:'用户名3', type:'imgGroup',value:[{url:'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/task/settlementDocument/1687748548983_1234567890.xlsx',name:'1687748548983_1234567890.xlsx'}]},
            { enName:'userName4', cnName:'用户名4', type:'UpLoad',value:{},isChangeEvent:true,itemAttr:{
                config: {
                  model: "单文件", //   单文件  多文件 身份证
                  showBG: true, // 可选 表示是否需要显示身份证背景
                  required: true, // 是否校验
                  tips: {
                    card1: "这是提示<span style='color:#eb0606'>信息</span>",
                    card2: "这是提示信息",
                    card3: "",
                  },
                  defaultFileList: {
                    card1: {url:'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/license/1688540243642_%E5%8A%9E%E5%85%AC.png',name:''},
                    // card1:{},
                    card2: {url:'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/license/1688540248058_%E5%8C%97%E4%BA%AC2.png',name:''},
                    card3: [{url:'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/task/settlementDocument/1687748548983_1234567890.xlsx',name:'1687748548983_1234567890.xlsx'},{url:'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/license/1688540248058_%E5%8C%97%E4%BA%AC2.png',name:''},{url:'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/license/1688540243642_%E5%8A%9E%E5%85%AC.png',name:''}],
                  },
                  fielConfig: {
                    type: { card1: "图片", card2: "图片", card3: "" }, // 允许上传的文件类型 当为空时表示不限制  默认为空   可供选择类型： 图片  文档  压缩包  发票  eg: 当值为string类型时，对所有（card1,card2,card3）的有效； 当值为对象（{"card1":'图片',"card2":'文档', "card3":'PDF'}）时，可指定每个（card1/card2/card3）所对应的类型
                    size: 30, // 允许上传的文件个数  默认值为1    eg: 1 表示只允许上传1个文件；  当值为对象（{"card1":1,"card2":2, "card3":3}）时，可指定每个（card1/card2/card3）所对应的类型
                    singleFileSize: 1, //上传的单个文件大小 单位为 MB  默认值为1 eg: 当值为 number 时，对所有（card1,card2,card3）的有效； 当值为对象（{"pdf":5,"xlsx":10, "zip":100}）时,可指定对应的文件类型的大小（单位：MB）
                  },
                },
                // 扩展文件校验 { 'groupName':'文档', suffixArr:['xlsx', 'xls', 'pptx', 'ppt', 'pdf', 'doc', 'docx', 'txt'],errorMsg:'只允许上传 PDF,DOC,DOCX,XLS,XLSX 类型文件' }
                extendedFileVerification: [
                  {
                    groupName: "文本",
                    suffixArr: ["txt"],
                    errorMsg: "只允许上传 txt 类型文件",
                  },
                ],
                customRequestEvent:this.customRequestEvent
            }},
        ]
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 方法集合
  methods: {
    PEvent(type,data, data1){
        console.log(type,data, data1);
        if(type=='change'){
          this.formVAl[data] = data1
        }
    },
    async customRequestEvent(action, dir_, that) {
      // https://webapitest.zxjztech.com/cloud/third/oss/getOssTemporaryToken?_t=1688552078
      const url = `https://webapitest.zxjztech.com/cloud/third/oss/getOssTemporaryToken`;
      const kk = () => {
        const date_ = new Date();
        const year = date_.getFullYear();
        let month = date_.getMonth() + 1;
        let day = date_.getDate();
        if (month < 10) month = "0" + month;
        if (day < 10) day = "0" + day;
        let hours = date_.getHours();
        let mins = date_.getMinutes();
        let secs = date_.getSeconds();
        const msecs = date_.getMilliseconds();
        if (hours < 10) hours = "0" + hours;
        if (mins < 10) mins = "0" + mins;
        if (secs < 10) secs = "0" + secs;
        if (msecs < 10) secs = "0" + msecs;
        return (
          year + "" + month + "" + day + "" + hours + "" + mins + "" + secs
        );
      };
      let options = {
        method: "GET",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
          "X-Access-Token":
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2OTExMjkyMTQsInVzZXJuYW1lIjoiMTIwNjE1MiJ9.F2518xYx6vQ8VaC29XOwmoHoaWlM-_RG8Ea3W52HGfk",
          "X-Sign": "E19D6243CB1945AB4F7202A1B00F77D5",
          "X-Timestamp": kk(),
        },
      };

      const file = action.file;
      let name =
        new Date().valueOf() +
        parseInt(Math.random() * 10000) +
        "_" +
        file.name;
      let dir = "/user/card/";
      const bucket = "zxcloud-test";
      // accessKeyId

    //   let progress = { percent: 1 };
    //   let speed = 100 / (action.file.size / 65000); //上传速度
    //   const intervalId = setInterval(() => {
    //     // 控制进度条防止在未上传成功时进度条达到100
    //     if (progress.percent < 99 && progress.percent + speed < 100) {
    //       progress.percent += speed; //控制进度条速度
    //       action.onProgress(progress); //onProgress接收一个对象{ percent: 进度 }在进度条上显示
    //     } else if ((progress.percent = 99)) {
    //       progress.percent++;
    //     } else if ((progress.percent = 100)) {
    //       clearInterval(intervalId);
    //     }
    //   }, 100);
      // console.log("stsInfo 1====>", url, options);
      const stsInfo = await fetch(url, options).then((res) => res.json());
      // console.log("stsInfo====>", stsInfo);
      const tempParam = {
        region: "oss-cn-hangzhou",
        accessKeyId: stsInfo.result.accessKeyId,
        accessKeySecret: stsInfo.result.accessKeySecret,
        bucket: bucket,
        stsToken: stsInfo.result.securityToken,
      };
      // console.log("+++++++++>", stsInfo, tempParam);
      const client = new OSS(tempParam);
      const resFile = await client.put(dir + name, file);
      // console.log("上传结果=======>", resFile);
      action.onSuccess(resFile, action.file);
      action.loading = false;
    //   progress.percent = 99;
      return { ...resFile, name: file.name };
    },
    expression(){
      this.$refs['PageForm'].onSubmit().then(formRes=>{
        console.log('校验======》',formRes);
        
      })
    }
  },
  }
</script>
<style lang='less' scoped>
</style>