<template>
  <MyLayout>
    <el-card class="my-query-box" shadow="never">
      <el-form :model="state.filter" :inline="true" @keyup.enter="onQuery">
        <el-form-item label="关键字">
          <el-input 
            v-model="state.filter.keyWord" 
            placeholder="批次名称/编号" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="项目">
          <el-select 
            v-model="state.filter.projectId" 
            placeholder="请选择项目" 
            clearable 
            style="width: 200px"
          >
            <el-option
              v-for="item in state.projectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="state.filter.stDate"
            type="date"
            placeholder="开始时间"
            style="width: 150px"
          />      
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="state.filter.edDate"
            type="date"
            placeholder="结束时间"
            style="width: 150px"
          />
        </el-form-item>



        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="onQuery">查询</el-button>
          <el-button v-auth="'api:admin:pre-batch:add'" type="primary" icon="ele-Plus" @click="onAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <el-table
        :data="state.preBatchListData"
        style="width: 100%"
        v-loading="state.loading"
        row-key="id"
        border
      >
        <el-table-column prop="preBatchName" label="批次名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="preBatchNo" label="批次编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="projectId" label="项目" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getProjectName(row.projectId) }}
          </template>
        </el-table-column>
        <el-table-column prop="projectUserName" label="项目负责人" min-width="100" show-overflow-tooltip />
        <el-table-column prop="createdUserRealName" label="创建者" min-width="100" show-overflow-tooltip />
        <el-table-column prop="createdTime" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="auth('api:admin:pre-batch:update')"
                icon="ele-EditPen"
                size="small"
                text
                type="primary"
                @click="onEdit(row)"
                >编辑</el-button
              >
              <el-button
                v-if="auth('api:admin:pre-batch:soft-delete')"
                icon="ele-Delete"
                size="small"
                text
                type="danger"
                @click="onDelete(row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination
          v-model:currentPage="state.pageInput.currentPage"
          v-model:page-size="state.pageInput.pageSize"
          :total="state.total"
          :page-sizes="[10, 20, 50, 100]"
          size="small"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <PrebatchForm ref="preBatchFormRef" :title="state.formTitle" @ok="Query" />
  </MyLayout>
</template>

<script lang="ts" setup name="admin/dspBatch">
import { ref, reactive, onMounted, getCurrentInstance, defineAsyncComponent } from 'vue'
import { PreBatchApi } from '/@/api/admin/PreBatchApi'
import { ProjectApi } from '/@/api/admin/ProjectApi'
import type { PreBatchDto, PreBatchPageInput, PreBatchPageDto } from '/@/api/types/preBatchType'
import { auth } from '/@/utils/authFunction'

// 引入组件
const PrebatchForm = defineAsyncComponent(() => import('./components/prebatch-form.vue'))

const { proxy } = getCurrentInstance() as any

const preBatchFormRef = ref()

const state = reactive({
  loading: false,
  formTitle: '',
  filter: {
    keyWord: '',
    projectId: null as number | null,
    isDown: true,
    stDate: '',
    edDate: ''
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as PreBatchPageInput,
  preBatchListData: [] as Array<PreBatchPageDto>,
  projectOptions: [] as Array<{ id: number; name: string }>,
})

onMounted(() => {
  Query()
  getProjectOptions()
})

const onQuery = () => {
  Query()
}

const Query = async () => {
  state.loading = true
  state.pageInput.filter = state.filter
  try {
    const res = await new PreBatchApi().getPage(state.pageInput)
    state.preBatchListData = res?.data?.list ?? []
    state.total = res?.data?.total ?? 0
  } catch (error) {
    console.error('查询失败:', error)
  } finally {
    state.loading = false
  }
}

const onAdd = () => {
  state.formTitle = '新增预批次'
  preBatchFormRef.value?.open()
}

const onEdit = (row: PreBatchDto) => {
  state.formTitle = '编辑预批次'
  preBatchFormRef.value?.open(row)
}

const onDelete = (row: PreBatchDto) => {
  proxy.$modal.confirm('确认要删除该记录吗？').then(async () => {
    try {
      const res = await new PreBatchApi().softDelete({ id: row.id! })
      if (res.success) {
        proxy.$modal.msgSuccess('删除成功')
        Query()
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

const onSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  Query()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  Query()
}

const onReset = () => {
  state.filter = {
    keyWord: '',
    projectId: null,
    isDown: true,
    stDate: '',
    edDate: ''
  }
  Query()
}

const getProjectOptions = async () => {
  try {
    const res = await new ProjectApi().getPage({
      currentPage: 1,
      pageSize: 10000
    })

    if (res?.success) {
      state.projectOptions = res.data?.list?.map(item => ({
        id: item.id ?? 0,
        name: item.projectName ?? ''
      })) ?? []
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

const getProjectName = (projectId: number) => {
  const project = state.projectOptions.find(item => item.id === projectId)
  return project?.name ?? ''
}
</script>

<style lang="scss" scoped>
.my-query-box {
  margin-top: 8px;
  
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
  
  :deep(.el-form--inline .el-form-item) {
    margin-right: 16px;
  }
}

.my-fill {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.my-flex {
  display: flex;
  align-items: center;
}

.my-flex-between {
  justify-content: space-between;
}

.my-flex-end {
  justify-content: flex-end;
}

.mt8 {
  margin-top: 8px;
}

.mb8 {
  margin-bottom: 8px;
}

// 表格样式优化
:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #fafafa;
      color: #606266;
      font-weight: 500;
    }
  }
  
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

// 分页样式优化
:deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  
  .el-pager li.is-active {
    background-color: var(--el-color-primary);
    color: white;
  }
}

// 按钮组样式
.action-buttons {
  display: flex;
  gap: 8px;
  
  .el-button {
    margin-left: 0;
  }
}

// 状态标签样式
.status-tag {
  &.enabled {
    background-color: #f0f9ff;
    color: #1890ff;
    border: 1px solid #d4edda;
  }
  
  &.disabled {
    background-color: #fff2f0;
    color: #ff4d4f;
    border: 1px solid #ffccc7;
  }
}
</style> 