<template>
  <div class="device-ledger-layout">
    <ContentWrap class="device-ledger-left">
      <el-tree
v-loading="typeTreeLoading" :data="brandTreeData" node-key="id" highlight-current :props="typeTreeProps"
        :default-expanded-keys="typeTreeExpandedKeys" :expand-on-click-node="false" @node-click="handleTypeNodeClick" />
    </ContentWrap>

    <div class="device-ledger-right">
      <ContentWrap>
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item :label="t('MoldManagement.Mold.code')" prop="code">
            <el-input
v-model="queryParams.name" :placeholder="t('MoldManagement.Mold.code')" clearable @keyup.enter="handleQuery"
              class="!w-240px" />
          </el-form-item>
          <el-form-item :label="t('MoldManagement.Mold.name')" prop="name">
            <el-input
v-model="queryParams.name" :placeholder="t('MoldManagement.Mold.name')" clearable @keyup.enter="handleQuery"
              class="!w-240px" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" /> {{ t('common.query') }}
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" /> {{ t('common.reset') }}
            </el-button>
            <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['erp:mold-brand:create']">
              <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
            </el-button>
            <el-button
type="success" plain @click="handleExport" :loading="exportLoading"
              v-hasPermi="['erp:mold-brand:export']">
              <Icon icon="ep:download" class="mr-5px" /> {{ t('action.export') }}
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
<el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column :label="t('MoldManagement.Mold.code')" align="center" prop="code" />
      <el-table-column :label="t('MoldManagement.Mold.name')" align="left" prop="name" />
      <el-table-column :label="t('MoldManagement.Mold.useTime')" align="center" prop="useTime" />
      <el-table-column :label="t('MoldManagement.Mold.status')" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_MOLD_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.Mold.machineName')" align="center" prop="machineName" />
      <el-table-column :label="t('MoldManagement.Mold.remark')" align="center" prop="remark" />
      <el-table-column :label="t('MoldManagement.Mold.isEnable')" align="center" prop="isEnable">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isEnable" />
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.Mold.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column :label="t('MoldManagement.Mold.operate')" align="center" fixed="right" width="200px">
        <template #default="scope">
          <el-button link @click="openDetail(scope.row.id)">
            {{ t('MoldManagement.Mold.detail') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:mold-brand:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:mold-brand:delete']"
          >
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
        <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </ContentWrap>
    </div>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <!-- 表单弹窗：添加/修改 -->
  <MoldForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：添加/修改 -->
  <MoldRecordForm ref="recordFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceLedgerApi } from '@/api/mes/deviceledger'
import { DeviceTypeApi, DeviceTypeTreeVO } from '@/api/mes/devicetype'
import { MoldBrandApi, MoldBrandTreeVO,MoldVO } from '@/api/erp/mold'
import { useDictStoreWithOut } from '@/store/modules/dict'
import MoldForm from '@/views/erp/mold/components/MoldForm.vue'
import MoldRecordForm from "@/views/erp/mold/components/MoldRecordForm.vue";

/** 设备类型 列表 */
defineOptions({ name: 'DeviceLedger' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(false) // 列表的加载中
const list = ref<MoldVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  brand: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const tableRef = ref()
const selectedIds = ref<number[]>([])

const dictStore = useDictStoreWithOut()
const dictReady = ref(false)

const typeTreeLoading = ref(false)
const typeTreeData = ref<DeviceTypeTreeVO[]>([])
const brandTreeData = ref<MoldBrandTreeVO[]>([])
const typeTreeProps = { label: 'name', children: 'children' }
const typeTreeExpandedKeys = ref<number[]>([0])
const deviceTypeNameMap = ref<Record<number, string>>({})

const buildDeviceTypeNameMap = (nodes: DeviceTypeTreeVO[]) => {
  const map: Record<number, string> = {}
  const stack = [...nodes]
  while (stack.length) {
    const node = stack.pop()!
    if (typeof node.id === 'number') map[node.id] = node.name
    if (Array.isArray(node.children) && node.children.length) stack.push(...node.children)
  }
  deviceTypeNameMap.value = map
}

const getTypeTree = async () => {
  typeTreeLoading.value = true
  try {
    const data = await DeviceTypeApi.getDeviceTypeTree({ pageNo: 1, pageSize: 10 })
    const dd = await MoldBrandApi.getMoldBrandTree()
    console.log(dd)
    brandTreeData.value = [{ id: 0, code: '', name: '全部', remark: '', sort: 0, children: dd } as any]
    console.log(brandTreeData.value)
    const treeChildren = JSON.parse(JSON.stringify(data ?? []))
    typeTreeData.value = [{ id: 0, code: '', name: '全部', remark: '', sort: 0, children: treeChildren } as any]
    buildDeviceTypeNameMap(treeChildren)
    typeTreeExpandedKeys.value = [0]
  } finally {
    typeTreeLoading.value = false
  }
}

const handleTypeNodeClick = (node: any) => {
  const id = node?.id
  queryParams.brand = id === 0 ? undefined : id
  queryParams.pageNo = 1
  getList()
}


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MoldBrandApi.getMoldPage({
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      deviceCode: queryParams.code,
      deviceName: queryParams.name,
      brandId: queryParams.brand
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (type == 'create' && !queryParams.brand) {
    message.error('请选择一个模具型号')
    return
  }
  formRef.value.open(type, id, queryParams.brand)
}

/** 删除按钮操作 */
const buildIdsParam = (ids: number | number[]) => {
  return Array.isArray(ids) ? ids.join(',') : String(ids)
}

const handleDelete = async (ids: number | number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const idsParam = buildIdsParam(ids)
    await DeviceLedgerApi.deleteDeviceLedger(idsParam)
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    tableRef.value?.clearSelection?.()
    // 刷新列表
    await getList()
  } catch { }
}



/** 导出按钮操作 */
const handleExport = async () => {
  if (!queryParams.brand) {
    message.error('请选择一个模具型号')
    return
  }
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await MoldBrandApi.exportMold({
      ...queryParams,
      brandId: queryParams.brand
    })
    download.excel(data, '模具.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


/** 初始化 **/
onMounted(async () => {
  await dictStore.setDictMap()
  dictReady.value = true
  getTypeTree()
  getList()
})

const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'ErpMoldDetail', params: { id } })
}
</script>

<style scoped>
.device-ledger-layout {
  display: flex;
  gap: 12px;
}

.device-ledger-left {
  width: 280px;
  flex: 0 0 auto;
}

.device-ledger-right {
  flex: 1;
  min-width: 0;
}

.device-ledger-detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.device-ledger-detail-title {
  font-size: 14px;
  font-weight: 600;
}

.device-ledger-history-steps {
  padding: 8px 8px 0;
}

.device-ledger-history-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
}

.device-ledger-history-time {
  font-weight: 600;
}

.device-ledger-history-operator {
  color: var(--el-text-color-secondary);
}

.device-ledger-tab-toolbar {
  margin-bottom: 8px;
  text-align: right;
}

.device-ledger-history-items {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 8px;
}

.device-ledger-history-item {
  display: flex;
  padding: 10px;
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  flex-direction: column;
  gap: 8px;
}

.device-ledger-history-item-head {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-ledger-history-item-body {
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 100%;
}

.device-ledger-history-item-row {
  display: flex;
  gap: 10px;
}

.device-ledger-history-item-label {
  width: 70px;
  flex: 0 0 70px;
  color: var(--el-text-color-secondary);
}

.device-ledger-history-item-value {
  flex: 1;
  color: var(--el-text-color-regular);
  word-break: break-word;
}

.device-ledger-history-item-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 4px;
}

.device-ledger-history-item-image {
  width: 76px;
  height: 76px;
  overflow: hidden;
  border-radius: 6px;
}

.device-ledger-history-image-error {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color);
  align-items: center;
  justify-content: center;
}

.device-ledger-repair-collapse {
  padding: 8px 8px 0;
}

.device-ledger-repair-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.device-ledger-repair-name {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.device-ledger-repair-meta {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.device-ledger-history-item-text {
  color: var(--el-text-color-regular);
}
</style>
