<template>
  <van-field
    ref="input"
    class="field-custom-type"
    :label="label"
    :name="name"
    :border="border"
    :disabled="disabled"
    :readonly="readonly"
    :required="required"
    :clearable="clearable"
    :clickable="clickable"
    :is-link="isLink"
    :error="error"
    :error-message="errorMessage"

    :arrow-direction="arrowDirection"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    :error-message-align="errorMessageAlign"
    :autosize="autosize"
    :left-icon="leftIcon"
    :right-icon="rightIcon"
    :icon-prefix="iconPrefix"
    :rules="editable?rules:null"
  >
    <template #label>
      {{ label }}<van-icon v-if="desc && descPosition==='lableIcon'" name="warning" class="ibps-dialog-icon" @click="$action.descDialog({ title:label, message:desc })" />
    </template>
    <template #input>
      <ibps-link
        v-if="showType === 'link'"
        :underline="underline"
        :icon="'ibps-icon'+icon"
        :disabled="disabled"
        :type="type"
        @click="handleClick"
      >{{ showText }}</ibps-link>
      <van-button
        v-else
        :text="showText"
        :icon="icon"
        :icon-prefix="iconPrefix"
        :disabled="disabled"
        :type="type"
        size="small"
        @click="handleClick"
      />
      <!-- 弹窗模式 -->
      <custom-dialog
        ref="userDialog"
        :visible="openDialog"
        :components="customComponents"
        @close="visible => openDialog = visible"
      />
    </template>
  </van-field>
</template>
<script>
import { getScriptValue } from '@/api/platform/form/common.js'
import request from '@/utils/request'
import FieldMixin from '@/mixins/field'
import IbpsLink from '@/components/ibps-link'
import customDialog from './dialog'

export default {
  name: 'ibps-hyperlink',
  components: {
    IbpsLink,
    customDialog
  },
  mixins: [FieldMixin],
  props: {
    showType: { // 是按钮还是文本
      type: String,
      default: 'link',
      validator: function(value) {
        return ['link', 'button'].indexOf(value) !== -1
      }
    },
    text: String,
    iconPrefix: {
      type: String,
      default: 'ibps-icon'
    },

    previewEntrance: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object
    },
    textJavascript: {
      type: String
    },
    linkType: { // 打开链接的类型
      type: String,
      default: 'fixed',
      validator: function(value) { // fixed 固定值; dynamic groovy脚本; javascript js 脚本
        return ['fixed', 'dynamic', 'javascript'].indexOf(value) !== -1
      }
    },
    textType: { // 文本展示的类型
      type: String,
      default: 'fixed',
      validator: function(value) { // fixed 固定值; dynamic groovy脚本; javascript js 脚本
        return ['fixed', 'dynamic', 'javascript'].indexOf(value) !== -1
      }
    },
    link: {
      type: String
    },
    type: {
      type: String,
      default: 'default'
    },
    underline: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // href: {
    //   type: String
    // },
    icon: {
      type: String
    },
    isNewTab: { // 新开窗口还是弹框显示
      type: Boolean,
      default: true
    },
    beforeClick: { // 方法参数（ linkData, text, cb） cb 是回调函数
      type: Function
    },
    afterClick: {
      type: Function
    }
  },
  data() {
    return {
      linkData: '',
      showText: this.text || '暂无数据',
      openType: '',
      openDialog: false,
      show: true,
      customComponents: {}
    }
  },
  watch: {
    formData(val, oldVal) {
      // 提供脚本监听属性。
      console.info(val)
    },
    textType: {
      handler: function(val) {
        if (!this.previewEntrance) return
        // this.showText = ''
        this.setVal(val, 'text', this.textJavascript)
      },
      immediate: true
    },
    linkType: {
      handler: function(val) {
        if (!this.previewEntrance) return
        this.setVal(val, 'link', this.link)
      },
      immediate: true
    }
  },
  methods: {
    /**
     * val 属性的值
     * prop [link]
     */
    setVal(val, prop, script, motion) {
      if (val === 'fixed') {
        this.showText = this.text || ''
      } else if (val === 'dynamic') {
        this.runGroovy(prop, script)
      } else if (val === 'javascript') {
        this.runScript(prop, script, motion)
      }
    },
    runScript(prop, scrip, motion) {
      var formData = this.formData
      const options = {
        formData: formData,
        request: request,
        router: this.$router,
        message: this.$notify,
        link: this
      }
      if (this.$utils.isEmpty(scrip)) return
      const promise = new window.Promise((resolve, reject) => {
        new Function('options', 'resolve', scrip)(options, resolve)
      })
      promise.then(result => {
        if (this.$utils.isEmpty(result)) {
          this.showText = '暂无数据'
          return
        }
        options.result = result
        if (prop === 'text') {
          this.showText = result || '暂无数据'
        } else {
          result.formData = formData
          this.linkData = result || ''
          if (result.constructor === Object && result.openType && this.showType === 'link' && motion === 'click') {
            switch (result.openType) {
              case 'dialog':
                this.customComponents = result
                this.openDialog = true
                break
              case 'url':
                // this.$router.push({ name: 'iframe', meta: { defaultUrl: result.url }})
                window.open(result.url)
                break
              case 'tab':
                this.$router.push(result.url)
                break
              default:
                break
            }
          } else if (this.showType === 'button') {
            if (result.constructor === Array) {
              const promise = new window.Promise((resolve, reject) => {
                result.forEach(item => {
                  if (item.event === 'beforeSubmit' && motion !== 'click') {
                    new Function('options', 'resolve', item.logic)(options, resolve)
                  } else if (item.event === 'afterSubmit' && motion === 'click') {
                    new Function('options', 'resolve', item.logic)(options, resolve)
                  }
                })
              })
              promise.then(res => {
                this.conditionalExecution(res.constructor === Object && res.openType, res, 'openType')
              })
            } else {
              this.$notify({
                message: '请按规定脚本格式填写脚本',
                type: 'warning'
              })
            }
          }
        }
      })
    },
    conditionalExecution(condition, res, key) {
      if (condition) {
        switch (res[key]) {
          case 'dialog':
            this.customComponents = res
            this.openDialog = true
            break
          case 'url':
            // this.$router.push({ name: 'iframe', meta: { defaultUrl: res.url }})
            window.open(res.url)
            break
          case 'tab':
            this.$router.push(res.url)
            break
          default:
            break
        }
      }
    },
    // TODO: 待完善
    runGroovy(prop, scrip) {
      var formData = this.formData
      const str = JSON.parse(JSON.stringify(scrip))
      const arr = []
      const vars = {}
      for (var i in formData.models) {
        if (str.indexOf(i) !== -1) {
          arr.push(str.substring(str.indexOf(i), str.indexOf(i) + i.length))
        }
      }
      arr.forEach(a => {
        vars[a] = formData.models[a]
      })
      if (this.$utils.isNotEmpty(scrip)) {
        getScriptValue({
          script: scrip,
          vars: JSON.stringify(vars) || ''
        }).then(res => {
          this[scrip + 'Data'] = res.content
          if (prop === 'text') {
            this.showText = res.data || '暂无数据'
          }
          // this.$notify({
          //   showClose: true,
          //   message: '动态脚本执行成功！',
          //   type: 'success'
          // })
        }).catch(err => {
          console.log(err)
        })
      }
    },
    handleClick() {
      this.setVal(this.linkType, 'link', this.link, 'click')
    }
    // handleClick(e) {
    //   this.$emit('click', e)
    // }
  }
}
</script>
<style lang="scss">
.field-custom-type{
  .van-button--info{
    color: #FFF;
    background-color: #909399;
    border-color: #909399;
  }
  .van-button--success{
    color: #FFF;
    background-color: #67C23A;
    border-color: #67C23A;
  }
  .van-button--warning {
    color: #FFF;
    background-color: #E6A23C;
    border-color: #E6A23C;
  }
  .van-button--danger {
    color: #FFF;
    background-color: #F56C6C;
    border-color: #F56C6C;
  }
  .van-button--primary{
    color: #FFF;
    background-color: #409EFF;
    border-color: #409EFF;
  }
}
</style>
