<template>
  <el-dialog v-model="dialogTableVisible" title="标签" width="1100">
    <el-table
      :data="showTableData()"
      border
      row-key="id"
      style="width: 1050px; max-height: 70vh; overflow-y: auto"
      v-if="tableData.length > 0 && dialogTableVisible == true"
      v-loading="isLoading"
    >
      <el-table-column type="expand" width="50">
        <template #default="scope">
          <div
            style="margin-left: 400px; margin-top: -8px; margin-bottom: -8px"
            v-if="scope.row.secondPackUnit && scope.row.secondPackQty"
          >
            <el-table
              :data="scope.row.packageList"
              border
              style="width: 550px"
              row-key="id"
              :row-class-name="getRowClass"
            >
              <el-table-column type="expand" width="50">
                <template #default="scope1">
                  <div style="margin-left: 150px; margin-top: -8px; margin-bottom: -8px">
                    <el-table :data="scope1.row.children" border style="width: 300px" row-key="id">
                      <el-table-column label="箱行号" width="100" prop="xPoNumber" align="center" />
                      <el-table-column label="数量" width="100" prop="qtyTwo" align="center">
                        <template #default="scope2">
                          <el-input
                            v-model="scope2.row.qtyTwo"
                            @blur="blurTwo(scope.row, scope1.row, scope2.row)"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="添加箱" width="100" prop="add" align="center">
                        <template #header>
                          <el-button
                            type="primary"
                            link
                            @click="addX(scope.row, scope.$index, scope1.row, scope1.$index, 1)"
                            >添加箱</el-button
                          >
                        </template>
                        <template #default="scope2">
                          <el-button
                            type="warning"
                            link
                            @click="
                              removeX(
                                scope.row,
                                scope.$index,
                                scope1.row,
                                scope1.$index,
                                scope2.row,
                                scope2.$index,
                                1
                              )
                            "
                            >移出</el-button
                          >
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="托行号" width="100" prop="tPoNumber" align="center" />
              <el-table-column label="箱个数" width="100" prop="xNumber" align="center">
                <template #default="scope1">
                  <el-input v-model="scope1.row.xNumber" @blur="blurOne(scope.row, scope1.row)" />
                </template>
              </el-table-column>
              <el-table-column label="数量" width="100" prop="qtyOne" align="center" />
              <el-table-column label="操作" width="100" prop="action" align="center">
                <template #default="scope1">
                  <el-button
                    type="warning"
                    link
                    @click="removeT(scope.row, scope.$index, scope1.row, scope1.$index)"
                    >移出</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="添加托" width="100" prop="add" align="center">
                <template #header>
                  <el-button type="primary" link @click="addT(scope.row)">添加托</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-left: 550px; margin-top: -8px; margin-bottom: -8px" v-else>
            <div v-for="(item, index) in scope.row.packageList" :key="index">
              <el-table :data="item.children" border style="width: 300px" row-key="id">
                <el-table-column label="箱行号" width="100" prop="xPoNumber" align="center" />
                <el-table-column label="数量" width="100" prop="qtyOne" align="center">
                  <template #default="scope1">
                    <el-input
                      v-model="scope1.row.qtyTwo"
                      @blur="blurThree(scope.row, item, scope1.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="添加箱" width="100" prop="add" align="center">
                  <template #header>
                    <el-button
                      type="primary"
                      link
                      @click="addX(scope.row, scope.$index, item, index)"
                      >添加箱</el-button
                    >
                  </template>
                  <template #default="scope1">
                    <el-button
                      type="warning"
                      link
                      @click="removeX(scope.row, scope.$index, item, index)"
                      >移出</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物料代码" width="150" prop="itemCode" align="center" />
      <el-table-column label="批次" width="150" prop="batch" align="center" />
      <el-table-column label="数量" width="100" prop="qty" align="center" />
      <el-table-column label="计量单位" width="100" prop="uom" align="center" />
      <el-table-column label="托个数" width="100" prop="allTuoQty" align="center" />
      <el-table-column label="托规格" width="100" prop="secondPackUnit" align="center" />
      <el-table-column label="托数量" width="100" prop="secondPackQty" align="center" />
      <el-table-column label="箱规格" width="100" prop="packUnit" align="center" />
      <el-table-column label="箱数量" width="100" prop="packQty" align="center" />
    </el-table>
    <el-pagination
      v-show="tableData.length > 10"
      style="margin-top: 10px"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :small="true"
      :background="false"
      layout="total, prev, pager, next, jumper"
      :total="tableData.length"
    />
    <template #footer>
      <slot name="foorter"></slot>
      <ButtonBase :Butttondata="Butttondata" @button-base-click="buttonBaseClick" />
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import * as defaultButtons from '@/utils/disposition/defaultButtons'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const props = defineProps({
  // 列表 相关信息
  tableAllSchemas: {
    type: Array,
    required: true,
    default: null
  }
})

const dialogTableVisible = ref(false)
const defaultExpandAll = ref(false)
const tableData = ref([])
const isLoading = ref(false)
const oneId = ref(0) //每托的id
const twoId = ref(0) //每箱的id
const openLabel =async (tableList) => {
  dialogTableVisible.value = true
  tableData.value = tableList
  defaultExpandAll.value = false
  await intData()
}
const currentPage = ref(1)
const pageSize = ref(10)
const showTableData = () => {
  if (tableData.value.length > 10) {
    return tableData.value.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  } else {
    return tableData.value
  }
  
}
const intData =async () => {
  tableData.value.forEach((row) => {
    if (row.secondPackUnit && row.secondPackQty) {
      // 数量%托数量  获取总共几托
      row.allTuoQty = Math.ceil(parseFloat(row.qty) / parseFloat(row.secondPackQty))
    } else {
      // 数量%每箱数量  获取总共几箱
      row.allTuoQty = Math.ceil(parseFloat(row.qty) / parseFloat(row.packQty))
    }
   expandChange(row)
  })
}
const expandChange = (row: any, expandedRows: any[]) => {
  // 判断托信息是否存在
  if (row.secondPackUnit && row.secondPackQty) {
    // 数量除以托数量获取余数
    row.lastNumber = parseFloat(row.qty) % parseFloat(row.secondPackQty)
    // 托数量/箱数量  一托可以放几箱
    row.otherNumber = parseFloat(row.secondPackQty) / parseFloat(row.packQty)
    // 数量%托数量  获取总共几托
    row.allTuoQty = Math.ceil(parseFloat(row.qty) / parseFloat(row.secondPackQty))
    row.packageList = []
    // 循环托
    for (let i = 0; i < row.allTuoQty; i++) {
      oneId.value++
      // 先给所有托一个默认对象值
      row.packageList[i] = {
        id: oneId.value,
        tPoNumber: i + 1,
        xNumber: '',
        qtyOne: '',
        isTuo: 1 //有托
      }
      // 如果有余数
      if (row.lastNumber) {
        // 最后一条信息直接展示余数的信息
        if (i == row.allTuoQty - 1) {
          row.packageList[i].xNumber = Math.ceil(row.lastNumber / parseFloat(row.packQty))
          row.packageList[i].qtyOne = row.lastNumber
        } else {
          // 其他数据展示一托的全部箱数和全部数量
          row.packageList[i].xNumber = row.otherNumber
          row.packageList[i].qtyOne = row.secondPackQty
        }
      } else {
        // 如果沒有余数,直接展示一托的全部箱数和全部数量
        row.packageList[i].xNumber = row.otherNumber
        row.packageList[i].qtyOne = row.secondPackQty
      }
    }
    // 判断箱信息是否存在
    if (row.packUnit && row.packQty) {
      row.packageList.forEach((cur, key) => {
        cur.children = []
        // 数量除以箱数量获取余数
        cur.xLastNumber = parseFloat(cur.qtyOne) % parseFloat(row.packQty)
        // cur.xiangNumber = Math.ceil(parseFloat(cur.qtyOne) / parseFloat(item.secondPackQty))
        for (let j = 0; j < cur.xNumber; j++) {
          twoId.value++
          cur.children[j] = {
            id: twoId.value,
            xPoNumber: j + 1
          }
          // 如果有余数
          if (cur.xLastNumber) {
            // 最后一条信息直接展示余数的信息
            if (j == cur.xNumber - 1) {
              cur.children[j].qtyTwo = cur.xLastNumber
            } else {
              // 其他数据展示一托的全部箱数和全部数量
              cur.children[j].qtyTwo = row.packQty
            }
          } else {
            // 如果沒有余数,直接展示一托的全部箱数和全部数量
            cur.children[j].qtyTwo = row.packQty
          }
        }
      })
    }
  } else {
    // 数量%每箱数量  获取总共几箱
    row.allXiangQty = Math.ceil(parseFloat(row.qty) / parseFloat(row.packQty))
    row.packageList = []
    row.allTuoQty = 1
    // 循环箱
    for (let i = 0; i < row.allTuoQty; i++) {
      oneId.value++
      // 先给所有托一个默认对象值
      row.packageList[i] = {
        id: oneId.value,
        xPoNumber: i + 1,
        qtyOne: row.qty,
        isTuo: 0 //无托
      }
    }
    row.packageList.forEach((cur) => {
      cur.children = []
      for (let j = 0; j < row.allXiangQty; j++) {
        twoId.value++
        cur.children[j] = {
          id: twoId.value,
          xPoNumber: j + 1
        }
        // 数量除以箱数量获取余数
        cur.lastNumber = parseFloat(row.qty) % parseFloat(row.packQty)
        // 如果有余数
        if (cur.lastNumber) {
          // 最后一条信息直接展示余数的信息
          if (j == row.allXiangQty - 1) {
            cur.children[j].qtyTwo = cur.lastNumber
          } else {
            // 其他数据展示一托的全部箱数和全部数量
            cur.children[j].qtyTwo = row.packQty
          }
        } else {
          // 如果沒有余数,直接展示一托的全部箱数和全部数量
          cur.children[j].qtyTwo = row.packQty
        }
      }
    })
  }
}

/** 弹窗按钮 */
let Butttondata: any = []
Butttondata = [
  defaultButtons.formSaveBtn(null), // 保存
  defaultButtons.formCloseBtn(null) // 关闭
]

/** 按钮事件 */
const buttonBaseClick = (val) => {
  // 保存
  if (val == 'save') {
    submitForm()
  }
  // 关闭
  else if (val == 'close') {
    dialogTableVisible.value = false
  }
}
// 保存
const submitForm = () => {
  let arr = tableData.value.map((item) => {
    item.allNumber = 0
    // 判断托信息是否存在
    item.packageList.forEach((cur) => {
      item.allNumber += parseFloat(cur.qtyOne) || 0
    })
    if (item.allNumber == parseFloat(item.qty)) {
      return true
    } else {
      return false
    }
  })
  const isBol = arr.some((item) => item == false)
  if (isBol) {
    message.warning('当前添加的数量与总数量不一致')
    return
  }
  emit('submitForm', tableData.value)
}
// 添加托
const addT = (oneRow) => {
  oneId.value++
  oneRow.packageList.push({
    id: oneId.value,
    tPoNumber: oneRow?.packageList?.length>0?oneRow.packageList[oneRow.packageList.length - 1]?.tPoNumber  + 1 :1, //行号是上一行的行号加1
    xNumber: '',
    qtyOne: ''
  })
  oneRow.allTuoQty = oneRow.packageList.length
}
// 移出托
const removeT = (oneRow, oneIndex, twoRow, twoIndex) => {
  oneRow.packageList.splice(twoIndex, 1)
  oneRow.allTuoQty = oneRow.packageList.length
}
// 添加箱
const addX = (oneRow, oneIndex, twoRow, twoIndex, type) => {
  twoId.value++
  //  有父级托的时候
  if (type == 1) {
    // 在托下添加箱
    twoRow.children.push({
      id: twoId.value,
      xPoNumber: twoRow?.children?.length>0? twoRow?.children[twoRow.children.length - 1]?.xPoNumber + 1 :1,
      qtyOne: ''
    })
    twoRow.xNumber = twoRow.children.length
  } else {
    // 直接添加箱
    twoRow.children.push({
      id: twoId.value,
      xPoNumber:twoRow.children.length>0? twoRow.children[twoRow.children.length - 1].xPoNumber + 1:1,
      qtyTwo: ''
    })
    oneRow.allTuoQty = twoRow.children.length
  }
}
// 移除箱
const removeX = (oneRow, oneIndex, twoRow, twoIndex, threeRow, threeIndex, type) => {
  //  有父级托的时候
  if (type == 1) {
    // 在托下移除箱
    twoRow.children.splice(threeIndex, 1)
    let num = 0
    twoRow.children.forEach((item) => {
      num += parseFloat(item.qtyTwo) || 0
    })
    twoRow.qtyOne = num
    twoRow.xNumber = twoRow.children.length
  } else {
    twoRow.children.splice(twoIndex, 1)
    oneRow.allTuoQty = twoRow.children.length
  }
}
// 是否显示展开图标
const getRowClass = (row) => {
  if (!row.row.children || row.row.children.length == 0) {
    return 'row-expand-cover'
  }
}
// 托失去焦点
const blurOne = (oneRow, twoRow) => {
  if (!twoRow.xNumber) {
    twoRow.qtyOne = ''
  }
  if (parseFloat(twoRow.xNumber) > parseFloat(oneRow.otherNumber)) {
    message.warning('每托箱个数最多' + oneRow.otherNumber + '箱')
    twoRow.xNumber = oneRow.otherNumber
    twoRow.children = []
    twoRow.qtyOne = parseFloat(twoRow.xNumber) * parseFloat(oneRow.packQty)
  }
  twoRow.qtyOne = parseFloat(twoRow.xNumber) * parseFloat(oneRow.packQty)
  let num = 0
  oneRow.packageList.forEach((item) => {
    num += parseFloat(item.xNumber) || 0
  })
  if (num > oneRow.allPackQty) {
    message.warning('总箱数不可以大于' + oneRow.allPackQty)
    twoRow.xNumber = ''
    twoRow.qtyOne = ''
    return
  }
  // 托信息修改的時候箱数据自动排列
  // 判断箱信息是否存在
  if (oneRow.packUnit && oneRow.packQty) {
    oneRow.packageList.forEach((cur, key) => {
      cur.children = []
      // 数量除以托数量获取余数
      cur.xLastNumber = parseFloat(cur.xNumber) % parseFloat(oneRow.packQty)
      for (let j = 0; j < cur.xNumber; j++) {
        twoId.value++
        // 如果有余数
        if (cur.xLastNumber) {
          // 最后一条信息直接展示余数的信息
          if (j == cur.xNumbery - 1) {
            cur.children.push({
              id: twoId.value,
              xPoNumber: j + 1,
              qtyTwo: cur.xLastNumber
            })
          } else {
            // 其他数据展示一托的全部箱数和全部数量
            cur.children.push({
              id: twoId.value,
              xPoNumber: j + 1,
              qtyTwo: oneRow.packQty
            })
          }
        } else {
          // 如果沒有余数,直接展示一托的全部箱数和全部数量
          cur.children.push({
            id: twoId.value,
            xPoNumber: j + 1,
            qtyTwo: oneRow.packQty
          })
        }
      }
    })
  }
}
//在托下方的箱数量失去焦点
const blurTwo = (oneRow, twoRow, threeRow) => {
  if (parseFloat(threeRow.qtyTwo) > parseFloat(oneRow.packQty)) {
    message.warning('数量最多为' + oneRow.packQty)
    threeRow.qtyTwo = oneRow.packQty
    return
  }
  let num = 0
  twoRow.children.forEach((item) => {
    num += parseFloat(item.qtyTwo) || 0
  })
  twoRow.qtyOne = num
}
// 箱数量失去焦点
const blurThree = (oneRow, twoRow, thereeRow) => {
  if (parseFloat(thereeRow.qtyTwo) > parseFloat(oneRow.packQty)) {
    message.warning('每箱个数最多' + oneRow.packQty)
    thereeRow.qtyTwo = oneRow.packQty
  }
  let num = 0
  twoRow.children.forEach((item) => {
    num += parseFloat(item.qtyTwo) || 0
  })
  twoRow.qtyOne = num
}
// 传递给父类
const emit = defineEmits(['submitForm'])
defineExpose({ openLabel, dialogTableVisible, isLoading }) // 提供 open 方法，用于打开弹窗
</script>
<style lang="scss" scoped>
::v-deep .row-expand-cover td .el-table__expand-icon {
  visibility: hidden;
}
</style>