<template>
  <div class="stocking-application-order-page card h-100 flex overflow-hidden">
    <div class="order-status">
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="[]"
        :highlight-current="true"
        node-key="code"
        :data="treeData"
        :props="{ children: 'children', label: 'name' }"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="tree-node-label">{{ data.name }}</div>
            <div
              v-if="data.countQuantity || data.countQuantity === 0"
              class="tree-node-count"
            >
              {{ `(${data.countQuantity})` }}
            </div>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="order-content flex-1 flex-column overflow-hidden">
      <div class="header">
        <div class="header-search-form">
          <ElForm
            ref="searchFormRef"
            :model="searchForm"
            inline
            label-width="100px"
            class="search-form"
          >
            <ElFormItem label="入库申请单号" prop="warehouseApplyNo">
              <ElInput
                v-model="searchForm.warehouseApplyNo"
                clearable
                placeholder="入库申请单号"
              />
            </ElFormItem>
            <ElFormItem label="备货仓库" prop="warehouseId">
              <ElSelect
                v-model="searchForm.warehouseId"
                placeholder="请选择"
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                clearable
              >
                <ElOption
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </ElSelect>
            </ElFormItem>

            <ElFormItem label="关联单号" prop="manageNo">
              <ElInput
                v-model="searchForm.manageNo"
                clearable
                placeholder="关联单号"
              />
            </ElFormItem>

            <ElFormItem label="库存SKU" prop="warehouseSku">
              <ElInput
                v-model="searchForm.warehouseSku"
                clearable
                placeholder="库存SKU"
              />
            </ElFormItem>

            <ElFormItem label="商品名称" prop="warehouseSkuName">
              <ElInput
                v-model="searchForm.warehouseSkuName"
                clearable
                placeholder="商品名称"
              />
            </ElFormItem>

            <ElFormItem class="form-item-buttons">
              <ElButton type="primary" @click="() => search()">查询</ElButton>
              <ElButton @click="() => resetSearchForm()">重置</ElButton>
            </ElFormItem>
          </ElForm>
        </div>
        <div class="header-operation"></div>
      </div>
      <div class="table-content">
        <SplitDiv size="60">
          <template #top>
            <div v-loading="loading" class="table-list flex-1 overflow-hidden">
              <TableView
                ref="tableRef"
                highlight-current-row
                :selectionable="true"
                :serial-numberable="true"
                :columns="tableColumns"
                :paginated-data="tableData"
                @row-click="handleRowClick"
                @selection-change="handleSelectionChange"
              >
                <template #action="{ row }">
                  <ElButton
                    v-if="status === 'TO_BE_RECEIPT'"
                    link
                    type="success"
                    @click="warehouseReceipt(row)"
                    >仓库收货</ElButton
                  >
                  <ElButton
                    v-if="status === 'TO_BE_INSPECTED'"
                    link
                    type="warning"
                    @click="submitWarehousing(row)"
                    >提交入库</ElButton
                  >
                </template>
              </TableView>
            </div>
            <ElPagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[50, 100, 200, 300, 500]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              style="margin: 10px auto 0; text-align: right"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            ></ElPagination>
          </template>
          <template #bottom>
            <StockingApplyOrderDetailTabs :selected-row="selectedRow" />
          </template>
        </SplitDiv>
      </div>
    </div>
    <!-- 提交入库弹框 -->
    <SubmitWarehousingDialog ref="submitWarehousingDialogRef" @refresh="onRefresh" />
  </div>
</template>
<script setup lang="tsx">
import { ref } from 'vue'
import { TreeData } from '@/types/api/supply/stockingOrder'
import { loadWarehouseListApi } from '@/api/common'
import { WarehouseListData } from '@/types'
import usePageList from '@/utils/hooks/usePageList'
import {
  getStockingApplyOrderListApi,
  getStockingApplyOrderTreeApi,
  warehouseReceiptApi,
} from '@/api/warehouse/stockingApplyOrder'
import { TableData, SearchForm } from '@/types/api/warehouse/stockingApplyOrder'
import { useValue } from '@/utils/hooks/useValue'
import { ElTag, ElMessageBox, ElMessage } from 'element-plus'
import StockingApplyOrderDetailTabs from './StockingApplyOrderDetailTabs.vue'
import SubmitWarehousingDialog from './SubmitWarehousingDialog.vue'

const treeData = ref<TreeData[]>([])
const treeRef = ref()
const tableRef = ref()
const selectedRow = ref<TableData | null>(null)
const submitWarehousingDialogRef = ref<InstanceType<typeof SubmitWarehousingDialog>>()
const [searchForm, resetSearchForm] = useValue<SearchForm>({} as SearchForm)
const status = ref<string>('TO_BE_RECEIPT')
const warehouseList = ref<WarehouseListData[]>([])
const getStockingApplyOrderStatusName = (status: string) => {
  const statusText = treeData.value[0]?.children?.find(
    (item) => item.code === status,
  )?.name
  return statusText || ''
}
const tableColumns = computed(() => [
  {
    label: '入库申请单号',
    prop: 'warehouseApplyNo',
    width: 160,
    align: 'center',
  },
  {
    label: '关联单号',
    prop: 'manageNo',
    width: 160,
    align: 'center',
  },
  {
    label: '单据状态',
    prop: 'storeStatus',
    width: 120,
    align: 'center',
    render: (row: TableData) => {
      return (
        <ElTag type="primary">
          {getStockingApplyOrderStatusName(row.storeStatus)}
        </ElTag>
      )
    },
  },
  {
    label: '入库仓库',
    prop: 'warehouseName',
    width: 160,
    align: 'center',
  },
  {
    label: 'SKU个数',
    prop: 'skuTotal',
    width: 100,
    align: 'right',
  },
  {
    label: '申请数量',
    prop: 'total',
    width: 100,
    align: 'right',
  },
  {
    label: '入库数量',
    prop: 'buyStored',
    width: 100,
    align: 'right',
  },
  {
    label: '预计到货日期',
    prop: 'expectDeliveryTime',
    width: 160,
    align: 'center',
  },
  {
    label: '实际到货日期',
    prop: 'deliveryTime',
    width: 160,
    align: 'center',
  },
  {
    label: '制单人',
    prop: 'createUserName',
    width: 100,
    align: 'center',
  },
  {
    label: '制单时间',
    prop: 'createTime',
    width: 160,
    align: 'center',
  },
  {
    label: '操作',
    prop: 'action',
    fixed: 'right',
    width: 100,
    align: 'center',
    slot: 'action',
  },
])
const selection = ref<TableData[]>([])
const loadWarehouseList = async () => {
  try {
    const res = await loadWarehouseListApi()
    if (res.code !== 200) return
    warehouseList.value = res.data || []
  } catch (e) {
    console.error(e)
  }
}
const loadTreeData = async () => {
  try {
    const res = await getStockingApplyOrderTreeApi()
    if (res.code !== 200) return
    treeData.value = [
      { code: '-1', name: '全部', children: res.data || [] } as TreeData,
    ]
    await nextTick(() => {
      treeRef.value!.setCurrentKey(status.value, true)
    })
  } catch (e) {
    console.error(e)
  }
}
const nodeClick = (data: TreeData) => {
  status.value = data.code
  search()
}
const {
  currentPage,
  pageSize,
  loading,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList<TableData>({
  query: (page, pageSize) =>
    getStockingApplyOrderListApi(
      {
        ...searchForm.value,
        storeStatus: status.value === '-1' ? undefined : status.value,
      },
      page,
      pageSize,
    ).then(async (res) => {
      const { records } = res.data
      await nextTick(() => {
        tableRef.value.setCurrentRow(records[0])
        selectedRow.value = (records as never)[0]
      })
      return res.data
    }),
  initLoad: true,
})
const handleRowClick = (row: TableData) => {
  if (row) {
    selectedRow.value = row
  } else {
    selectedRow.value = null
  }
}
const handleSelectionChange = (val: TableData[]) => {
  selection.value = val
}
const warehouseReceipt = async (row: TableData) => {
  try {
    await ElMessageBox.confirm(
      `<div>
        <p style="margin-bottom: 10px;">SKU个数：<span style="color: #F56C6C; font-weight: bold;">${row.skuTotal}</span>，预计到货数量：<span style="color:#F56C6C; font-weight: bold;">${row.total}</span></p>
        <p>确认仓库是否收到货？</p>
      </div>`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      },
    )
  } catch {
    return
  }
  try {
    const res = await warehouseReceiptApi(row.id)
    if (res.code !== 200) return
    ElMessage.success('收货成功')
    search()
    loadTreeData()
  } catch (e) {
    console.error(e)
  }
}

const submitWarehousing = (row: TableData) => {
  submitWarehousingDialogRef.value?.open({
    id: row.id,
    warehouseId: row.warehouseId,
  })
}

const onRefresh = () => {
  search()
  loadTreeData()
}
onMounted(async () => {
  await loadWarehouseList()
  await loadTreeData()
})
</script>
<style lang="scss" scoped>
.order-status {
  width: 160px;
  :deep(.el-tree-node__content) {
    height: 30px;
    line-height: 30px;
  }
  :deep(.el-tree-node__label) {
    font-size: 13px;
    cursor: pointer;
    display: inline-block;
    width: 100%;
    color: black !important;

    padding: 3px 7px;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  :deep(.is-current) {
    .tree-node-label,
    .tree-node-count {
      background-color: #ecf5ff;
      color: #409eff !important;
    }

    .el-tree-node__children {
      .tree-node-label,
      .tree-node-count {
        background-color: transparent !important;
        color: black !important;
      }
    }
  }
  :deep(.el-tree-node__label) {
    font-size: 13px;
    color: rgb(96, 98, 102);
    cursor: pointer;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  :deep(.el-tree-node__label) {
    display: inline-block;
    width: 100%;
    color: black !important;

    padding: 3px 7px;
  }

  :deep(.is-current) {
    .el-tree-node__label {
      background-color: #ecf5ff;
      color: #409eff !important;
    }

    .el-tree-node__children {
      .el-tree-node__label {
        background-color: transparent !important;
        color: black !important;
      }
    }
  }
}
.tree-node {
  display: flex;
  color: #333;
  font-weight: 500;
}
.table-content {
  flex: 1;
  margin-top: 10px;
  overflow: hidden;
  :deep(#top) {
    height: 100%;
  }
}

.search-form {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  align-items: flex-start;
  :deep(.el-form-item) {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
