<template>
  <ych-modal
    v-if="dialogSize !== 'drawer'"
    :fullscreen="dialogSize === 'default' || dialogSize === 'full'"
    :size="dialogSize"
    :title="title"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :destroyOnClose="true"
    @ok="handleOk"
    :footer="footer"
    @cancel="handleCancel">
    <form-redirect v-if="formType === 'form'"
                   ref="formRedirect"
                   :func="func"
                   :formId="formId"
                   :formCode="formCode"
                   :fks="fks"
                   :parentValue="parentValue"
                   :saveInPage="saveInPage"
                   :disQueryDB="disQueryDB"
                   :record="record"
                   :stores="stores"
                   :hiddenSaveBut="true"
                   @close="close"
                   @hideDialogButtons="hideDialogButtons"
                   @addParentSpinning="addSpinning"
                   @delParentSpinning="delSpinning"
                   @refreshParent="refreshParent"
                   @setFormTitle="setFormTitle"
                   @setEnableDraft="setEnableDraft"
                   :is-transport="isTransport"
                   @closeTopPage="closeTopPage"
    >
    </form-redirect>
    <view-layout-redirect v-else-if="formType === 'view'"
                          ref="viewRedirect"
                          :view-code="formCode"
                          :stores="stores"
                          :formOption="formOption"
                          :parameterValue="parameterValue"
                          @closeFromView="close"
                          @hideDialogButtonsFromView="hideDialogButtons"
                          @addParentSpinningFromView="addSpinning"
                          @delParentSpinningFromView="delSpinning"
                          @refreshParent="refreshParent"
                          @handleOkFromView="handleOk"
                          @setFormTitleFromView="setFormTitle"
                          @setEnableDraft="setEnableDraft">
    </view-layout-redirect>
    <template slot="footer">
      <a-button key="back" @click="handleCancel" :disabled="spinning > 0">{{ $locle('m.common.button.close') }}</a-button>
      <a-button key="saveDraft" type="primary" @click="saveDraft" v-if="!readOnly && enableDraft"
                :disabled="spinning > 0">{{ $locle('m.common.button.saveDraft') }}
      </a-button>
      <a-button key="submit" type="primary" @click="handleOk" v-if="!readOnly" :disabled="spinning > 0">
        {{ $locle('m.common.button.save') }}
      </a-button>
    </template>
  </ych-modal>
  <div class="drawer-container" v-else>
    <a-drawer
      placement="right"
      id="drawer"
      :closable="false"
      :mask="false"
      style="margin-top: 50px"
      :width="computedWidth"
      :visible="visible"
    >
      <template slot="title">
        <div style="display: flex;justify-content: space-between;">
          <div style="width: 70%">{{ title }} </div>
          <div style="display: flex;justify-content: space-between;width: 15%;">
            <div style="display: flex;cursor: pointer">
              <div @click="clickArrow('left')"><a-icon type="arrow-left"  :style="'color:' + (showLeft ? 'black' :'grey')"  /></div>
              <div @click="clickArrow('right')" style="margin-left: 30px;"><a-icon type="arrow-right"  :style="'color:' + (showRight ? 'black' :'gray')" /></div>
            </div>
            <div style="cursor: pointer;" @click="onClose"><a-icon type="close" /></div>
          </div>
        </div>
      </template>
      <a-divider id="drag" class="drawer-divider" type="vertical"/>
      <div v-if="visible">
        <form-redirect v-if="formType === 'form'"
                       ref="formRedirect"
                       :func="func"
                       :formId="formId"
                       :formCode="formCode"
                       :fks="fks"
                       :parentValue="parentValue"
                       :saveInPage="saveInPage"
                       :disQueryDB="disQueryDB"
                       :record="record"
                       :stores="stores"
                       :hiddenSaveBut="true"
                       @close="close"
                       @hideDialogButtons="hideDialogButtons"
                       @addParentSpinning="addSpinning"
                       @delParentSpinning="delSpinning"
                       @refreshParent="refreshParent"
                       @setFormTitle="setFormTitle"
                       @setEnableDraft="setEnableDraft"
                       :is-transport="isTransport"
                       @closeTopPage="closeTopPage">
        </form-redirect>
      </div>
      <div v-if="visible">
        <!--      <a-button key="back" @click="handleCancel" :disabled="spinning > 0">{{ $locle('m.common.button.close') }}</a-button>-->
        <a-button key="saveDraft" type="primary" @click="saveDraft" v-if="!readOnly && enableDraft"
                  :disabled="spinning > 0">{{ $locle('m.common.button.saveDraft') }}
        </a-button>
        <a-button key="submit" type="primary" @click="handleOk" v-if="!readOnly" :disabled="spinning > 0">
          {{ $locle('m.common.button.save') }}
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>

// import FormRedirect from './FormRedirect'
import locleUtil from "../../utils/LocleUtil";
export default {
  name: 'FormRedirectModal',
  components: {
    FormRedirect: () => import('./FormRedirect'),
    ViewLayoutRedirect: () => import('./ViewLayoutRedirect')
  },
  props: {
    // 仅在页面暂时存储，用于子表添加
    saveInPage: {
      type: Boolean,
      default: false
    },
    stores: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //获取当前行
    itemRecordRow: {
      type: Object,
      default: () => {
        return {}
      },
      required: false
    }
  },
  computed: {
    formOption() {
      return {
        func: this.func,
        formId: this.formId,
        fks: this.fks,
        parentValue: this.parentValue,
        saveInPage: this.saveInPage,
        disQueryDB: this.disQueryDB,
        record: this.record,
        isTab: true,
      }
    },
    bodyStyle() {
      if (this.formType === 'view') {
        return {
          padding: 0,
          margin: 0,
          background: "#F0F2F5"
        }
      }
      return {}
    },
    //   抽屉 箭头按钮权限
    showLeft(){
      return this.currentIndex !== 0 ? true :false
    },
    showRight(){
      return this.currentIndex !== this.currentTableData.length - 1 ? true :false
    },
  },
  data() {
    return {
      title: this.$locle('m.eform.formDesign.label.biao-dan-ye-mian'),
      visible: false,
      func: null,
      formId: null,
      formCode: null,
      fks: null,
      parentValue: {},
      readOnly: false,
      footer: undefined,
      dialogSize: 'default',
      spinning: 0,
      disQueryDB: false, // 不查询数据库
      record: null, // 页面对象
      formType: 'form',
      parameterValue: [],
      enableDraft: false,
      needClose: false,
      isTransport: false,
      computedWidth: 960,
      currentTableData: [],
      currentDetailRow: null,
      currentIndex: 0,
    }
  },
  created() {
    console.log('formredirectdivModal', this)
  },
  watch:{
    visible(val){
      if (val){
        if (this.dialogSize == 'drawer'){
          setTimeout(() => {
            this.currentTableData = this.$parent.dataSource
            this.currentIndex = this.currentTableData.findIndex(item => item.id == this.itemRecordRow.id)
            this.changeHeight()
          },500)
        }
      }else{
        this.currentDetailRow = null
        this.currentTableData = []
      }
    }
  },
  methods: {
    $locle(params){
      return locleUtil.getLocale(params)
    },
    clickArrow(type){
      this.currentDetailRow = this.currentDetailRow || this.itemRecordRow
      const currentRow = this.currentDetailRow
      const currentTableData = this.currentTableData
      this.currentIndex = currentTableData && currentTableData.findIndex(item => item.id == currentRow.id)
      if ((type == 'left' && this.currentIndex == 0) || (type == 'right' && this.currentIndex == currentTableData.length - 1)) {
        return
      }
      const numIndex = type == 'left' ? (this.currentIndex - 1) : (this.currentIndex + 1)
      for (let i = 0; i < currentTableData.length; i++) {
        if (i == numIndex) {
          this.currentDetailRow = currentTableData[numIndex]
          this.currentIndex = i
          this.$parent.rowButton && this.$parent[this.$parent.rowButton.openType].apply(this.$parent, [this.$parent.rowButton, this.currentDetailRow])
          break
        }
      }
    },
    changeHeight(){
      sessionStorage.setItem('drawerWidth',this.computedWidth)
      let d = document.getElementById('drag')
      let child = document.getElementsByClassName('ant-drawer-content')[0]
      let that = this
      d.onmousedown = function(e) {
        let startX = e.clientX;
        document.onmousemove = function (e) {
          let endX = e.clientX;
          let dragLen = startX - endX + parseInt(sessionStorage.getItem('drawerWidth'));
          if(dragLen < 600) dragLen = 600
          if(dragLen > 1300) dragLen = 1300
          that.computedWidth = dragLen
        }
        document.onmouseup = function () {
          sessionStorage.setItem('drawerWidth',that.computedWidth)
          document.onmousemove = null;
          document.onmouseup = null;
          d.releaseCapture && d.releaseCapture();
        };
      };
      d.releaseCapture && d.releaseCapture();
    },
    onClose() {
      this.visible = false;
      this.$parent.rowButton = null;
    },
    //设置标题
    setFormTitle(title) {
      let titleName = title || this.$locle('m.eform.formDesign.label.biao-dan')
      let funcName = this.$locle('m.common.button.add')
      if (this.func === 'edit') {
        funcName = this.$locle('m.common.button.update')
      } else if (this.func === 'detail') {
        funcName = this.$locle('m.common.title.detail')
      }
      this.title = funcName + " " + titleName
    },
    handleCancel() {
      if (this.spinning > 0) {
        this.needClose = true
        return;
      }
      this.visible = false
    },
    //关闭顶层窗口
    closeTopPage() {
      this.$emit('closeTopPage', true)
    },
    handleOk($vue, isDraft) {
      const that = this;
      this.addSpinning();
      console.log(this.formType, 'this.formType')
      if (this.formType === 'form') {
        this.$refs.formRedirect.save(this.afterSave)
      } else {
        $vue.save(this.afterSave, null, isDraft)
      }
      setTimeout(function () {
        that.delSpinning();
      }, 500)
    },
    saveDraft() {
      const that = this;
      this.addSpinning();
      this.$refs.formRedirect.save(this.afterSave, null, true)
      setTimeout(function () {
        that.delSpinning();
      }, 500)
    },
    afterSave(id, saveSucessMsg) {
      if (saveSucessMsg) {
        this.$message.success(saveSucessMsg)
      } else {
        this.$message.success(this.$locle('m.eform.formDesign.label.bao-cun-cheng-gong'))
      }
      // view方式时，不关闭当前页面
      // 普通模式（form）时，关闭当前页面
      // 后续改为可配置参数
      if (this.formType === 'form') {
        this.visible = false
      }
    },
    hideDialogButtons() {
      this.setFooter(null)
    },
    //关闭页面
    close() {
      this.handleCancel()
    },
    //刷新父页面
    refreshParent(id, tableName, formData) {
      this.$emit('refreshParent', id, tableName, formData)
    },
    setFooter(value) {
      this.footer = this.formType === 'view' ? null : value
    },
    add(formCode, fks, parentValue, dialogSize) {
      this.addForm({
        formCode: formCode,
        fks: fks,
        parentValue: parentValue,
        dialogSize: dialogSize,
      })
    },
    addForm(options) {
      this.formType = null;
      console.log(options, 'aoptions')
      setTimeout(() => {
        this.isTransport = options.isTransport
        this.formType = options.formType || 'form'
        this.dialogSize = options.dialogSize || 'default'
        this.disQueryDB = false
        this.record = null
        this.func = 'add'
        this.formId = undefined
        this.formCode = options.formCode
        this.fks = options.fks
        this.parentValue = options.parentValue || {}
        this.parameterValue = options.parameterValue || []
        this.title = this.$locle('m.common.button.add')
        this.readOnly = false
        this.enableDraft = false
        this.visible = true
        this.needClose = false
        this.setFooter(undefined)
        this.spinning = 0;
      }, 100)
    },
    edit(id, formCode, dialogSize, disQueryDB, record) {
      this.editForm({
        id: id,
        formCode: formCode,
        dialogSize: dialogSize,
        disQueryDB: disQueryDB,
        record: record,
      })
    },
    editForm(options) {
      this.formType = null;
      setTimeout(() => {
        console.log(options, 'eoptions')
        this.isTransport = options.isTransport
        this.formType = options.formType || 'form'
        this.dialogSize = options.dialogSize || 'default'
        this.disQueryDB = options.disQueryDB;
        this.record = options.record;
        this.func = 'edit'
        this.formId = options.id
        this.formCode = options.formCode
        this.fks = null
        this.parentValue = options.parentValue || {}
        this.parameterValue = options.parameterValue || []
        this.title = this.$locle('m.common.button.update')
        this.readOnly = false
        this.enableDraft = false
        this.visible = true
        this.needClose = false
        this.setFooter(undefined)
        this.spinning = 0;
      }, 100)
    },
    detail(id, formCode, dialogSize, disQueryDB, record) {
      this.detailForm({
        id: id,
        formCode: formCode,
        dialogSize: dialogSize,
        disQueryDB: disQueryDB,
        record: record,
      })
    },
    detailForm(options) {
      this.formType = null;
      // this.visible = false
      setTimeout(() => {
        this.formType = options.formType || 'form'
        this.dialogSize = options.dialogSize || 'default'
        this.disQueryDB = options.disQueryDB;
        this.record = options.record;
        this.func = 'detail'
        this.formId = options.id
        this.formCode = options.formCode
        this.fks = null
        this.parentValue = options.parentValue || {}
        this.parameterValue = options.parameterValue || []
        // 纯列表页面不需要标题，表单页面会设置标题
        this.title = this.$locle('m.common.title.detail')
        this.readOnly = true
        this.visible = true
        this.needClose = false
        this.setFooter(undefined)
        this.spinning = 0;
      }, 100)
    },
    addSpinning() {
      this.spinning++
    },
    delSpinning() {
      this.spinning--
      if (this.spinning === 0 && this.needClose) {
        this.needClose = false
        this.handleCancel()
      }
      if (this.spinning === 0 && this.needClose) {
        this.needClose = false
        this.handleCancel()
      }
    },
    setEnableDraft(enableDraft) {
      this.enableDraft = enableDraft
    }
  }
}
</script>
<style scoped>
.drawer-container {
  position: relative;
}

.drawer-divider {
  position: absolute;
  left: -10px;
  height: 100%;
  width: 5px;
  cursor: ew-resize;
  background-color: transparent;
  box-shadow: 2px 4px 5px 1px #f1f1f1;
}
</style>
