<template>
  <div class="app-container">
    <GoBack :title="title" @goBack="goBack" />
    <el-tabs v-model="activeName" :before-leave="beforeClick">
      <el-tab-pane label="施工装备" name="EquipmentAdd"></el-tab-pane>
      <el-tab-pane label="编码工具" name="AddCode"></el-tab-pane>
      <el-tab-pane label="数量工具" name="AddNum"></el-tab-pane>
    </el-tabs>
    <component ref="componentRef" :is="isShowComponent" />
  </div>
</template>

<script>
import GoBack from '@/components/GoBack'
import EquipmentAdd from '@/views/stockManagement/entryApply/components/EquipmentAdd'
import AddNum from '@/views/stockManagement/entryApply/components/AddNum'
import AddCode from '@/views/stockManagement/entryApply/components/AddCode'

export default {
  name: 'ApplyDetails',
  components: {
    GoBack,
    EquipmentAdd,
    AddNum,
    AddCode,
  },
  data() {
    return {
      isShowComponent: 'EquipmentAdd',
      activeName: 'EquipmentAdd',
      leaving: false,
      title: '入库申请'
    }
  },
  created() {
    let title = '新增'
    const routerParams = this.$route.query
    if (routerParams.isEdit) {
      title = '编辑'
    } else if (routerParams.isView) {
      title = '详情'
      this.title = '入库审批'
    }
    const obj = Object.assign({}, this.$route, { title })
    this.$tab.updatePage(obj)
  },
  methods: {
    goBack() {
      this.$router.push({ path: '/stockManagement/inventoryAudit' }).then(() => {
        this.$tab.closePage({ path: '/stockManagement/entryApply/apply' })
      })
    },
    async beforeClick(activeName, oldActiveName) {
      if (this.leaving) return false
      // 如果是同一个 tab，直接放行
      if (activeName === oldActiveName) return true
      let isEmpty = false
      let allHasOrderId = false
      if (oldActiveName == 'EquipmentAdd') {
        const tableList = this.$refs.componentRef.tableData || []
        isEmpty = tableList.length === 0
        allHasOrderId = tableList.every((item) => !!item.maId)
      } else if (oldActiveName == 'AddNum' || oldActiveName == 'AddCode') {
        const tableList = this.$refs.componentRef.dialogList || []
        isEmpty = tableList.length === 0
        allHasOrderId = tableList.every((item) => !!item.id)
      }

      if (isEmpty || allHasOrderId) {
        this.isShowComponent = activeName
        return true
      }

      const confirm = await this.confirmLeave()
      if (!confirm) {
        // ❌ 用户取消
        this.isShowComponent = activeName
        return true
      }
      try {
        let result = null
        if (oldActiveName == 'EquipmentAdd') {
          // 调用保存
          const tableList = this.$refs.componentRef.tableData || []

          for (let i = 0; i < tableList.length; i++) {
            const row = tableList[i]
            const res = await this.$refs.componentRef.submitRow(row)
            if (!res) {
              result = false
              break
            }
          }
        } else if (oldActiveName == 'AddNum' || oldActiveName == 'AddCode') {
          result = await this.$refs.componentRef.submit()
          console.log('🚀 ~ result:', result)
        }
        if (!result) {
          setTimeout(() => {
            this.leaving = true
            this.activeName = oldActiveName
            setTimeout(() => {
              this.leaving = false
            }, 200)
          }, 200)
          return false
        } else {
          this.isShowComponent = activeName
          return true
        }
      } catch (error) {
        console.log('error', error)
        setTimeout(() => {
          this.activeName = oldActiveName
        }, 200)
        return false
      }
    },
    confirmLeave(message = '是否暂存已添加的装备？', title = '提示') {
      return new Promise((resolve, reject) => {
        this.$confirm(message, title, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('用户点击「确定」')
            resolve(true)
          })
          .catch(() => {
            console.log('用户点击「取消」')
            resolve(false)
          })
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
