<template>
  <div>
    <el-dialog :visible.sync="dialogVisible"
               :title="dialogTitle"
               :before-close="handleClose"
               :width="width"
               :top="top"
               center
               v-dialogDrag="dialogDrag"
               :append-to-body="appendToBody" :close-on-click-modal="false"
               style="overflow-y: hidden" class="yc-dialog">
      <el-form class="small-space"
               :ref="formName"
               :rules="formRules"
               :model="form"
               :label-position="labelPosition"
               :label-width="labelWidth">
        <slot></slot>
      </el-form>
      <div v-if="footerVisible" slot="footer" style="text-align: center;">
        <slot name="footer"></slot>
        <auth-button v-if="editModel!=='V' && saveFlag && footerBtnShow"
                     size="medium"
                     type="primary"
                     :label="saveLabel"
                     :loading="loading"
                     :menuCode="menuCode"
                     :perms="savePerms"
                     @click="save"></auth-button>
        <auth-button v-if="footerBtnShow" size="medium" :label="closeLabel" @click="dialogClose" :openPerms="false" :menuCode="menuCode" :perms="closePerms"></auth-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import mixin from '@/components/element/assetaudit/CgMixin'
import AuthButton from '@/components/element/assetaudit/CgAuthButton'
export default {
  inheritAttrs: false,
  components: { AuthButton },
  mixins: [mixin],
  props: {
    // 所属菜单Code-->全局唯一
    menuCode: {
      type: String,
      default: null
    },
    // 按钮权限标识，外部使用者传入
    savePerms: {
      type: String,
      default: null
    },
    // 按钮权限标识，外部使用者传入
    closePerms: {
      type: String,
      default: null
    },
    visible: {
      required: true,
      type: [Boolean],
      default: function () {
        return false
      }
    },
    appendToBody: { // 是否是内层的嵌套dialog
      type: Boolean,
      default: function () {
        return false
      }
    },
    editModel: {
      required: true,
      type: [Number, String]
    },
    form: {
      required: true,
      type: [Object]
    },
    formRules: {
      type: [Object]
    },
    labelWidth: {
      default: function () {
        return '120px'
      }
    },
    width: {
      default: function () {
        return '70%'
      }
    },
    title: {
      type: [String],
      required: true
    },
    // 自定义的提示信息
    newTitle: {
      type: [String],
      required: false
    },
    autoSave: {
      type: [Boolean],
      default: function () {
        return true
      }
    },
    api: {
      type: [Object],
      required: false
    },
    labelPosition: {
      type: [String],
      default: function () {
        return 'right'
      }
    },
    footerVisible: {
      type: [Boolean],
      default: function () {
        return true
      }
    },
    footerBtnShow: {
      type: [Boolean],
      default: function () {
        return true
      }
    },
    beforeSave: {
      type: [Boolean],
      required: false
    },
    createCode: {
      type: String,
      default () {
        return ''
      }
    },
    editCode: {
      type: String,
      default () {
        return ''
      }
    },
    reviewCode: {
      type: String,
      default () {
        return ''
      }
    },
    saveFlag: {
      type: Boolean,
      default () {
        return true
      }
    },
    top: {
      type: String,
      default () {
        return '100px'
      }
    },
    saveLabel: {
      type: String,
      default () {
        return '保 存'
      }
    },
    closeLabel: {
      type: String,
      default () {
        return '关 闭'
      }
    },
    autoClose: {
      type: Boolean,
      default () {
        return false
      }
    },
    // 按钮加载标识
    loading: {
      type: Boolean,
      default: false
    },
    // 是否拖拽，默认是false
    dialogDrag: {
      type: Boolean,
      default: false
    }
  },
  data: function () {
    return {
      formName: 'editForm',
      autoTitle: ''
    }
  },
  computed: {
    dialogTitle: function () {
      return this.title
    },
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    }
  },
  directives: {
    'dialogDrag': {
      bind (el, binding, vnode, oldVnode) {
        if (!binding.value) { // 不能拖拽
          return
        }
        const dialogHeaderEl = el.querySelector('.el-dialog__header')
        const dragDom = el.querySelector('.el-dialog')
        dialogHeaderEl.style.cursor = 'move'
        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null)
        const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)

        dialogHeaderEl.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft
          const disY = e.clientY - dialogHeaderEl.offsetTop
          // 获取到的值带px 正则匹配替换
          let styL, styT
          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (sty.left.includes('%')) {
            // styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
            // styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
            styL = +document.body.clientWidth * (+sty.left.replace(/\\%/g, '') / 100)
            styT = +document.body.clientHeight * (+sty.top.replace(/\\%/g, '') / 100)
          } else {
            styL = +sty.left.replace(/\px/g, '')
            styT = +sty.top.replace(/\px/g, '')
          }
          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            const l = e.clientX - disX
            const t = e.clientY - disY
            // 移动当前元素
            dragDom.style.left = `${l + styL}px`
            dragDom.style.top = `${t + styT}px`
          }
          document.onmouseup = function (e) {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    }
  },
  methods: {
    resetForm: function () {
      let $this = this
      $this.$refs[this.formName].clearValidate()
    },
    resetFields: function () {
      let $this = this
      $this.$refs[this.formName].resetFields()
    },
    save: function () {
      let $this = this
      this.$refs[this.formName].validate((valid) => {
        if (valid) {
          if (!$this.autoSave) {
            $this.$emit('onSaved', this.form)
            return false
          }
          if ($this.beforeSave) {
            $this.$emit('beforeSaved', $this.form)
          }
          if ($this.editModel === 'C') {
            $this.api.create($this.form).then(res => {
              if ($this.success) {
                if (this.autoTitle) {
                  $this.createCode === '' ? $this.success(`新增${this.autoTitle}成功`) : $this.message(res, $this.createCode)
                } else {
                  $this.createCode === '' ? $this.success(`新增${this.title}成功`) : $this.message(res, $this.createCode)
                }
              } else {
                if (this.autoTitle) {
                  $this.success(`新增${$this.autoTitle}成功`)
                } else {
                  $this.success(`新增${$this.title}成功`)
                }
              }
              $this.$emit('onSave', { from: this.form, res: res.data })
              $this.dialogVisible = false
            }).catch(res => {
              this.$emit('errSave', res)
            })
          } else if (this.editModel === 'E' || this.editModel === 'R') {
            $this.api.update(this.form.keyId, this.form).then(res => {
              if ($this.success && $this.editModel === 'E') {
                if (this.autoTitle) {
                  $this.editCode === '' ? $this.success(`修改${this.autoTitle}成功`) : $this.message(res, $this.editCode)
                } else {
                  $this.editCode === '' ? $this.success(`修改${this.title}成功`) : $this.message(res, $this.editCode)
                }
              } else if ($this.success && $this.editModel === 'R') {
                if (this.autoTitle) {
                  $this.reviewCode === '' ? $this.success(`复核${this.autoTitle}成功`) : $this.message(res, $this.reviewCode)
                } else {
                  $this.reviewCode === '' ? $this.success(`复核${this.title}成功`) : $this.message(res, $this.reviewCode)
                }
              }
              $this.$emit('onSave', { from: this.form, res: res.data })
              $this.dialogVisible = false
            }).catch(res => {
              $this.$emit('errSave', res)
            })
          }
        } else {
          if ($this.error) {
            $this.error('表单填写错误，请检查')
          } else {
            $this.error('表单填写错误，请检查')
          }
          return false
        }
      })
    },
    handleClose (done) {
      if (this.autoClose) {
        this.$emit('close')
      } else {
        done()
      }
    },
    dialogClose () {
      if (this.autoClose) {
        this.$emit('close')
      } else {
        this.dialogVisible = false
      }
    }
  },
  watch: {
    dialogVisible: function (value, old) {
      this.$nextTick(() => {
        this.resetForm()
      })
      if (value) { // 统一处理提示消息title 中的 维护字符
        if (this.newTitle === undefined) {
          this.autoTitle = this.title
          if (this.autoTitle.indexOf('维护') !== -1) {
            let reg = new RegExp('维护', 'g')
            let a = this.autoTitle.replace(reg, '')
            this.autoTitle = a
          }
        } else {
          this.autoTitle = this.newTitle
        }
      }
    }
  }
}
</script>
