<template>
  <div class="form-container">
    <form-create v-model="fapi" :rule="rule" :option="option" @change="onChange"></form-create>
  </div>
</template>

<script>
/* eslint-disable */
import { setToken } from "../utils/auth";
import { getFormInfo, getFormInstanceData, getDepList } from  '../api/index.js'
//FcDesigner 生成的`JSON`
// const FcDesignerRule = '[{"type":"input","field":"cuk5qqdw3umc","title":"输入框","info":"","_fc_drag_tag":"input","hidden":false,"display":true}]';
//FcDesigner 生成的`options`
// const FcDesignerOptions = '{"form":{"labelPosition":"right","size":"mini","labelWidth":"125px","hideRequiredAsterisk":false,"showMessage":true,"inlineMessage":false}}';
// 在父窗口获取当前表单的值
// window.addEventListener('message',(e) => {
// this.formData = e.data
// },false);
export default {
  data() {
    return {
      formData: {},
      flatData: [],
      id: '',
      instanceId: '', // 表单填写记录ID
      token: '',
      fapi: null,
      rule: [],
      option: undefined,
      submitBtn: null,
      isReadonly: false,
      haveTimePicker: false,
      depList: []
    }
  },
  created(){
    this.id = this.getQueryString('id')
    this.instanceId = this.getQueryString('instanceId')
    this.token = this.getQueryString('token')
    this.isReadonly = this.getQueryString('readonly') === '1' ? true : false
    setToken(this.token)
    this.prepareDepList().then(() => {
      this.getFormInfo();
    })
  },
  mounted(){
    window.vum = this
  },
  methods: {
    // 提供给父窗口的数据
    getFormData(){
      const data = this.formData
      let flag = true
      let msg = ''
      // 扁平化
      this.flatData = []
      this.flatFn(this.rule)
      for(var item of this.flatData){
        if(item.validate){
          for(var item2 of item.validate){
            switch(item2.mode){
              case 'required':
                if(item.value === undefined || item.value.length === 0){
                  flag = false
                  msg = item2.message || item.title+('不能为空！')
                }
                break
              case 'min':
                if(item.value === undefined || item.value.length < item2.min){
                  flag = false
                  msg = item2.message || item.title+('不能小于'+item2.min+'个！')
                }
                break
              case 'pattern':
                const reg = new RegExp(item2.pattern);
                if(item.value === undefined || !reg.test(item.value)){
                  flag = false
                  msg = item2.message || item.title+('填写不正确！')
                }
                break
              case 'max':
                if(item.value === undefined || item.value.length > item2.max){
                  flag = false
                  msg = item2.message || item.title+('不能多于'+item2.max+'个！')
                }
                break
              case 'len':
                if(item.value === undefined || item.value.length !== item2.len){
                  flag = false
                  msg = item2.message || item.title+('必须为'+item2.len+'个！')
                }
                break
            }
            if(!flag){
              break
            }
          }
        }
        if(!flag){
          break
        }
      }
      if(flag){
        const ddd = JSON.parse(JSON.stringify(data))
        ddd.id = this.id
        for(let key in ddd){
          if(ddd[key] instanceof Array){
            ddd[key] = 'hxz1412350_'+JSON.stringify(ddd[key])
          }
        }
        return ddd;
      }else{
        return {
          error: true,
          msg: msg
        };
      }
    },
    // 向父级发送数据
    postMsg(data){
      let flag = true
      let msg = ''
      // 扁平化
      this.flatData = []
      this.flatFn(this.rule)
      for(var item of this.flatData){
        if(item.validate){
          for(var item2 of item.validate){
            switch(item2.mode){
              case 'required':
                if(item.value === undefined || item.value.length === 0){
                  flag = false
                  msg = item2.message || item.title+('不能为空！')
                }
                break
              case 'min':
                if(item.value === undefined || item.value.length < item2.min){
                  flag = false
                  msg = item2.message || item.title+('不能小于'+item2.min+'个！')
                }
                break
              case 'pattern':
                const reg = new RegExp(item2.pattern);
                if(item.value === undefined || !reg.test(item.value)){
                  flag = false
                  msg = item2.message || item.title+('填写不正确！')
                }
                break
              case 'max':
                if(item.value === undefined || item.value.length > item2.max){
                  flag = false
                  msg = item2.message || item.title+('不能多于'+item2.max+'个！')
                }
                break
              case 'len':
                if(item.value === undefined || item.value.length !== item2.len){
                  flag = false
                  msg = item2.message || item.title+('必须为'+item2.len+'个！')
                }
                break
            }
            if(!flag){
              break
            }
          }
        }
        if(!flag){
          break
        }
      }
      if(flag){
        const ddd = JSON.parse(JSON.stringify(data))
        ddd.id = this.id
        for(let key in ddd){
          if(ddd[key] instanceof Array){
            ddd[key] = 'hxz1412350_'+JSON.stringify(ddd[key])
          }
        }
        window.parent.postMessage(JSON.stringify(ddd),this.getParentUrl());
      }else{
        window.parent.postMessage(JSON.stringify({
          error: true,
          msg: msg
        }),this.getParentUrl());
      }
    },
    // 扁平化数据
    flatFn(d){
      if(d instanceof Array){
        for(let item of d){
          this.flatFn(item)
        }
      }else if(d?.children?.length){
        for(let item of d.children){
          this.flatFn(item)
        }
      }else{
        this.flatData.push(d)
      }
    },
    // 获取父级的url
    getParentUrl() { 
      var url = null;
      if (parent !== window) { 
          try {
            url = parent.location.href; 
          }catch (e) { 
            url = document.referrer;
          } 
      }
      return url;
    },
    prepareDepList(){
      return new Promise((resolve, reject) => {
        // 组装部门信息
        getDepList({
          parentId: 'D000000001'
        }).then(resp => {
          if (resp && resp.status===200) {
            this.depList = resp.data.map(item => {
              return {
                value: item.id,
                label: item.name
              }
            })
            let xunfei = []
            getDepList({
              parentId: 'D000000002'
            }).then(resp2 => {
              if (resp2 && resp2.status===200) {
                xunfei = resp2.data.map(item => {
                  return {
                    value: item.id,
                    label: item.name
                  }
                })
                this.depList = this.depList.concat(xunfei)
                resolve()
              }
            }).catch((e) => {
              reject(e)
            })
          }
        }).catch((e) => {
          reject(e)
        })
      })
    },
    // 回显表单
    getFormInfo() {
      getFormInfo({
        id: this.id
      }).then(resp=>{
        if (resp && resp.status===200) {
          if(resp.data.formRenderJson){
            let haveEditor = 0
            this.rule = JSON.parse(resp.data.formRenderJson).rule
            this.flatFn(this.rule)
            this.flatData.forEach(item => {
              if(item.options && item.options.length>55){
                item.options = JSON.parse(JSON.stringify(this.depList))
              }
              if(this.isReadonly){
                // if(item.type !== 'upload') this.fapi.disabled(true, item.field);
                if(typeof item === 'object'){
                  if(!item.props){
                    item.props = {}
                  }
                  item.props.disabled = true
                }
                // 给upload加禁用样式
                var style = document.createElement('style')
                style.textContent = `
                  ._fc-upload .fc-upload-btn{
                    background-color: #F5F7FA;
                    border-color: #E4E7ED;
                    color: #C0C4CC;
                    cursor: not-allowed;
                  }
                  ._fc-upload .fc-upload-cover .el-icon-delete{
                    display: none
                  }
                `
                document.getElementsByTagName('head')[0].appendChild(style)
              }
              if(item.type === 'datePicker'){
                this.haveTimePicker = true
              }
              if(item.type === 'fc-editor'){
                haveEditor = true
                if(item.props === undefined) item.props = {}
                if(item.props.config === undefined) item.props.config = {}
                item.props.config.excludeMenus = ['video']
              }
              if(item.type === 'upload'){
                if(item.props === undefined) item.props = {}
                item.props.listType = 'text'
                item.props.handleIcon = true
                item.props.onHandle = (file) => {
                  const protocol = location.protocol
                  const host = location.host
                  const link = document.createElement('a')
                  link.style.display = 'none'
                  const arr = file.url.split('/')
                  link.download = arr[arr.length-1]
                  link.setAttribute('href', protocol+'//'+host+file.url)
                  document.body.appendChild(link)
                  link.click()
                  window.URL.revokeObjectURL(protocol+'//'+host+file.url)
                  // window.open(protocol+'//'+host+file.url, '_blank')
                }
                item.props.onSuccess = (res, file) => {
                  file.url = res.data
                  this.$nextTick(() => {
                    this.formData = {...this.fapi.form}
                    this.postMsg(this.formData)
                  })
                }
              }
            })
            this.option = JSON.parse(resp.data.formRenderJson).config
            this.$nextTick(() => {
              let childrens = document.querySelectorAll('.el-col.el-col-24')
              this.submitBtn = childrens[childrens.length-1].querySelector('.el-button')
              this.submitBtn.style.display = 'none'

              // 获取高度
              if(haveEditor){
                setTimeout(() => {
                  const domH = document.getElementsByClassName('form-container')[0].offsetHeight
                  window.parent.postMessage(JSON.stringify({winHeight: this.haveTimePicker ? domH<500 ? 500 :domH : domH, id: this.id }),this.getParentUrl());
                }, 500)
              }else{
                const domH = document.getElementsByClassName('form-container')[0].offsetHeight
                window.parent.postMessage(JSON.stringify({winHeight: this.haveTimePicker ? domH<500 ? 500 :domH : domH, id: this.id }),this.getParentUrl());
              }
            })
            // 对表单默认值进行赋值，可能会被下面的接口覆盖
            const defaultValue = resp.data.defaultValue
            if(defaultValue){
              for(let key in defaultValue){
                if(~defaultValue[key].indexOf('hxz1412350_')){
                  let jsonStr = defaultValue[key].split('_')[1]
                  if(jsonStr){
                    try{
                      defaultValue[key] = JSON.parse(jsonStr)
                    }catch(e){
                      console.log('解析失败：', e)
                    }
                  }
                }
              }
              this.formData = defaultValue
            }
            if(this.formData){
              this.postMsg(this.formData)
              for (let key in this.formData) {
                this.fapi.setValue({ [key]: this.formData[key] });
              }
            }
            // 获取表单填写内容
            this.fileForm();
            // 主动发送一次数据
            this.postMsg({})
          }
        }
      })
    },
    // 对表单进行赋值
    fileForm(){
      if(!this.instanceId) return;
      getFormInstanceData({
        formId: this.id,
        instanceId: this.instanceId
      }).then(resp=>{
        if (resp && resp.status===200) {
          const instanceData = resp.data.instanceData
          for(let key in instanceData){
            // 处理switch和富文本
            this.flatData.forEach(item => {
              if(item.field === key && item.type==='switch'){
                if(instanceData[key] === '0' || instanceData[key] === 0){
                  instanceData[key] = false
                }else if(instanceData[key] === '1' || instanceData[key] === 1){
                  instanceData[key] = true
                }
              }
              if(item.field === key && item.type === 'fc-editor' && instanceData[key]){
                instanceData[key] = instanceData[key].replace(/&lt;/g, '<')
                instanceData[key] = instanceData[key].replace(/&gt;/g, '>')
              }
            })
            // 处理数组
            if(typeof instanceData[key] === 'string' && ~instanceData[key].indexOf('hxz1412350_')){
              let jsonStr = instanceData[key].split('_')[1]
              if(jsonStr){
                try{
                  instanceData[key] = JSON.parse(jsonStr)
                }catch(e){
                  console.log('解析失败：', e)
                }
              }
            }
          }
          this.formData = instanceData
          if(this.formData){
            this.postMsg(this.formData)
            for (let key in this.formData) {
              this.fapi.setValue({ [key]: this.formData[key] });
            }
          }
          // this.$nextTick(() => {
          //   // 获取高度
          //   const domH = document.getElementsByClassName('form-container')[0].offsetHeight
          //   window.parent.postMessage(JSON.stringify({winHeight: this.haveTimePicker ? domH<500 ? 500 :domH : domH, id: this.id}),this.getParentUrl());
          // })
        }
      })
    },
    // 对表单进行赋值
    fileForm2(instanceData){
      for(let key in instanceData){
        // 处理switch和富文本
        this.flatData.forEach(item => {
          if(item.field === key && item.type==='switch'){
            if(instanceData[key] === '0' || instanceData[key] === 0){
              instanceData[key] = false
            }else if(instanceData[key] === '1' || instanceData[key] === 1){
              instanceData[key] = true
            }
          }
          if(item.field === key && item.type === 'fc-editor' && instanceData[key]){
            instanceData[key] = instanceData[key].replace(/&lt;/g, '<')
            instanceData[key] = instanceData[key].replace(/&gt;/g, '>')
          }
        })
        // 处理数组
        if(typeof instanceData[key] === 'string' && ~instanceData[key].indexOf('hxz1412350_')){
          let jsonStr = instanceData[key].split('_')[1]
          if(jsonStr){
            try{
              instanceData[key] = JSON.parse(jsonStr)
            }catch(e){
              console.log('解析失败：', e)
            }
          }
        }
      }
      this.formData = instanceData
      if(this.formData){
        this.postMsg(this.formData)
        for (let key in this.formData) {
          this.fapi.setValue({ [key]: this.formData[key] });
        }
      }
    },
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if(r != null) {
        return decodeURIComponent(r[2]);
      }
      return '';
    },
    onChange(field, value){
      this.$nextTick(() => {
        let tds = document.querySelectorAll('[contenteditable] td')
        let ths = document.querySelectorAll('[contenteditable] th')
        tds.forEach(item => {
          if(item.innerHTML === '') item.innerHTML = '&nbsp;'
        })
        ths.forEach(item => {
          if(item.innerHTML === '') item.innerHTML = '&nbsp;'
        })
      })
      this.formData[field] = value
      this.postMsg(this.formData)
    }
  }
}
</script>
<style>
html,body{
  margin: 0;
  padding: 0;
}
</style>
