import { Message, Modal } from 'ant-design-vue'
import LawService from '../law-service'
import FlowService from '@/webflow/flow-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
function at(n) {
  n = Math.trunc(n) || 0
  if (n < 0) n += this.length
  if (n < 0 || n >= this.length) return undefined
  return this[n]
}
const TypedArray = Reflect.getPrototypeOf(Int8Array)
for (const C of [Array, String, TypedArray]) {
  Object.defineProperty(C.prototype, 'at', {
    value: at,
    writable: true,
    enumerable: false,
    configurable: true,
  })
}
const CaseMixins = {
  data() {
    return {
      stage: [],
      parentstage: [],
      flag: true,
      create: false,
      type: '',
      caseStage: '',
      caseType: '',
    }
  },
  created() {
    this.caseStage = this.$route.query?.cs
    this.caseType = this.$route.query?.ct
    if (this.$route.params.id && this.$route.params.id === '0') {
      this.create = true
    }
  },
  methods: {
    initData() {
      if (this.create) {
        if (this.type === 'progress') {
          LawService.getCaseTree(this.caseType, '').then((r) => {
            LawService.getCaseTree(this.caseType, this.caseStage).then((res) => {
              this.parentstage = [...r.data]
              this.stage = [...res.data]
              LawService.getProgressData(this.$route.query.id).then((res) => {
                const obj = res.data.find((d) => d.props.stepType === 'progress')
                const sn = this.stage.find((i) => i.id === this.$route.query?.stage).text
                const psn = this.parentstage.find((i) => i.id === this.$route.query?.cs).text
                const ini = setInterval(() => {
                  if (this.$refs.webflow) {
                    clearInterval(ini)
                    this.$refs.webflow.setFieldValue('CASE_ID', this.$route.query.id)
                    this.$refs.webflow.setFieldValue('CASE_STAGE', this.$route.query?.stage)
                    this.$refs.webflow.setFieldValue('CASE_STAGE_NAME', psn)
                    this.$refs.webflow.setFieldValue('PROGRESS_CODE', this.$route.query?.stage)
                    this.$refs.webflow.setFieldValue('STEP_NAME', sn)
                    this.$refs.webflow.setFieldValue('CASE_NAME', res.data[0].text)
                    if (
                      this.$route.query.parentid !== '' &&
                      this.$route.query.parentid !== 'progress'
                    ) {
                      this.$refs.webflow.setFieldValue('PARENT_STEP_ID', this.$route.query.parentid)
                    }
                    if (!(this.$route.query.flag && this.$route.query.flag === '1')) {
                      const stageinfo = {
                        stagecode: this.$route.query.cs,
                        parentstagecode: this.$route.query.ct,
                        parentstagename: psn,
                      }
                      this.$refs.webflow.setFieldValue('STAGE_INFO', JSON.stringify(stageinfo))
                    }
                  }
                }, 100)
              })
            })
          })
        } else {
          LawService.getAllcaseproStage().then((res) => {
            const stage = []
            res.data.forEach((d) => {
              stage.push({
                name: d.EXECUTE_NAME,
                code: d.EXECUTE_CODE,
                businessTypeId: d.businessTypeId,
              })
            })
            this.zxstage = stage
            LawService.getProgressData(this.$route.query.id).then((res) => {
              const sn = this.zxstage.find((i) => i.code === this.$route.query?.stage)?.name
              this.$refs.webflow.setFieldValue('CASE_ID', this.$route.query.id)
              this.$refs.webflow.setFieldValue('PROGRESS_CODE', this.$route.query?.stage)
              this.$refs.webflow.setFieldValue('STEP_NAME', sn)
              this.$refs.webflow.setFieldValue('CASE_NAME', res.data[0].text)
              if (this.$route.query.parentid !== '' && this.$route.query.parentid !== 'execute') {
                this.$refs.webflow.setFieldValue('PARENT_STEP_ID', this.$route.query.parentid)
              }
              LawService.getCaseData(this.$route.query.id).then((res) => {
                this.$refs.webflow.setFieldValue('CASE_TYPE', res.data.caseType)
              })
            })
          })
        }
      }
    },
    /**
     * 提交后事件
     */
    afterDispatch(obj) {
      // 提交也认为是保存
      obj.defaultPrevented = true
      Message.success({ content: `提交成功`, duration: 1 }).then(() => {
        const e = false
        const t = true
        const snap = this.$refs.webflow.getFormSnap()
        if (
          e &&
          this.$refs.webflow.FlowData.mode === 'EDIT' &&
          (this.$refs.webflow.getFormSnap() !== snap || this.$refs.webflow.disableActionAlert)
        )
          if (!window.confirm('正在编辑文档或正文附件，确认是否离开此网站')) return
        crossWindowWatcher.notifyChange(t)
        return FlowService.unLock(this.$refs.webflow.FlowData.instId).finally(() => {
          crossWindowWatcher.notifyChange(true)
          this.$refs.webflow.close()
          const url = window.location.href
          const obj = { url: url, type: this.type + 'close' }
          window.parent.postMessage(obj, '*')
        })
      })
      return obj
    },
    save() {
      if (this.create) {
        if (window.location.href.indexOf('draft/0') === -1) {
          if (window.parent) {
            const obj = { url: window.location.href, type: this.type }
            window.parent.postMessage(obj, '*')
          }
          this.create = false
        }
      }
    },
    actionBtnClick(evt, { button, FlowData }) {
      if (button.fakeId === 'we-doc$close') {
        this.$refs.webflow.close()
        window.parent.opener = null
        window.parent.open('', '_self')
        window.parent.close()
      } else {
        if (this.create) {
          if (button.fakeId === 'save' || button.fakeId === 'workflow-push') {
            evt.waitUntil(
              new Promise((resolve, reject) => {
                this.validForm().then((res) => {
                  if (!res) {
                    evt.preventDefault()
                  }
                  resolve()
                })
              })
            )
          }
        }
      }
    },

    validForm() {
      const validForm = new Promise((resolve) => {
        // 校验最新的上级节点是否是当前 if (this.type === 'progress') {
        LawService.getProgressData(this.$route.query.id).then((res) => {
          const objsz = res.data.filter((r) => r.props.stepType === this.type)
          const obj = objsz[objsz.length - 1]
          let flag = true
          if (this.type === 'progress') {
            if (obj && obj.children && obj.children.length > 0) {
              const sobj = obj.children.at(-1)
              if (sobj.children && sobj.children.length > 0) {
                const scobj = sobj.children.at(-1)
                if (scobj.props.stepStatus === '0') {
                  flag = false
                }
              }
            }
            if (flag) {
              if (this.$route.query.parentid === 'progress') {
                if (obj && res.data.at(-1).props.stepType === 'progress') {
                  // 需要创建进展阶段时，但是已有，则有问题
                  flag = false
                }
              } else {
                if (res.data.at(-1).props.stepType !== 'progress' || !obj) {
                  // 不需要创建进展阶段时，但是没有，则有问题
                  flag = false
                } else {
                  // 当前创建的父节点id 不是当前需要创建的节点
                  if (
                    obj &&
                    this.$route.query.parentid !== obj.id &&
                    this.$route.query.parentid !== obj.children.at(-1).id
                  ) {
                    flag = false
                  }
                }
              }
            }
          } else if (this.type === 'execute') {
            if (obj && obj.children && obj.children.length > 0) {
              const sobj = obj.children.at(-1)
              if (sobj.props.stepStatus === '0') {
                flag = false
              }
            }
            if (flag) {
              if (this.$route.query.parentid === 'execute') {
                if (obj && res.data.at(-1).props.stepType === 'execute') {
                  // 需要创建进展阶段时，但是已有，则有问题
                  flag = false
                }
              } else {
                if (res.data.at(-1).props.stepType !== 'execute' || !obj) {
                  // 不需要创建进展阶段时，但是没有，则有问题
                  flag = false
                } else {
                  // 当前创建的父节点id 不是当前需要创建的节点
                  if (obj && this.$route.query.parentid !== obj.id) {
                    flag = false
                  }
                }
              }
            }
          } else {
          }
          if (!flag) {
            Modal.warning({
              title: '提示',
              content: '当前案件信息已变动，请关闭后重新进入!',
            })
          }
          resolve(flag)
        })
      })
      return validForm
    },
  },
}
export default CaseMixins
