<template>
  <MyLayout>
    <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" @submit.stop.prevent>
        <el-form-item label="模板名称">
          <el-input v-model="state.filter.keyWord" placeholder="请输入模板名称" @keyup.enter="onQuery" />
        </el-form-item>
        <el-form-item label="反应器">
          <el-select v-model="state.filter.equReactorId" placeholder="请选择反应器" clearable style="width: 150px">
            <el-option
              v-for="item in state.reactorOptions"
              :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="开始日期"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="state.filter.edDate"
            type="date"
            placeholder="结束日期"
            value-format="YYYY-MM-DD"
            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:protocol: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">
      <div class="my-tools-box mb8 my-flex my-flex-between">
        <div>
        </div>
      </div>
      <el-table
        v-if="state.showProtocolList"
        :data="state.protocolListData"
        style="width: 100%"
        v-loading="state.loading"
        row-key="id"
        border
      >
        <el-table-column prop="protocolName" label="模板名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="equReactorId" label="反应器" width="120" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getReactorDescription(row.equReactorId) }}
          </template>
        </el-table-column>
        <el-table-column prop="equReactorId" label="规格" width="120" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getReactorSpec(row.equReactorId) }}
          </template>
        </el-table-column>
        <el-table-column prop="days" label="培养天数" min-width="100" show-overflow-tooltip />
        <el-table-column prop="feedingTaskCount" label="补料任务" min-width="100" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="success" v-if="row.enabled">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdUserName" label="创建者" min-width="100" show-overflow-tooltip />
        <el-table-column prop="createdTime" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="240" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button
              v-if="auth('api:admin:protocol:update')"
              icon="ele-EditPen"
              size="small"
              text
              type="primary"
              @click="onEdit(row.id)"
              >编辑</el-button
            >
            <el-button
              v-if="auth('api:admin:protocol:copy')"
              icon="ele-CopyDocument"
              size="small"
              text
              type="success"
              @click="onCopy(row)"
              >复制</el-button
            >
            <el-button
              v-if="auth('api:admin:protocol:soft-delete')"
              icon="ele-Delete"
              size="small"
              text
              type="danger"
              @click="onDelete(row)"
              >删除</el-button
            >
          </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>

    <protocol-form ref="protocolFormRef" :title="state.protocolFormTitle" @ok="Query" />
    
    <!-- 反应器选择弹窗 -->
    <reactor-select-dialog 
      ref="reactorSelectDialogRef" 
      :title="state.reactorDialogTitle"
      :reactor-options="state.reactorOptions"
      @confirm="handleReactorSelect"
    />
  </MyLayout>
</template>

<script lang="ts" setup name="admin/protocol">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { ProtocolApi } from '/@/api/admin/ProtocolApi'
import type { ProtocolDto, ProtocolPageInput, ProtocolPageDto } from '/@/api/types/protocolType'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ReactorApi } from '/@/api/admin/ReactorApi'

// 引入组件
const ProtocolForm = defineAsyncComponent(() => import('./components/protocol-form.vue'))
const ReactorSelectDialog = defineAsyncComponent(() => import('./components/reactor-select-dialog.vue'))

const { proxy } = getCurrentInstance() as any

const protocolFormRef = ref()
const reactorSelectDialogRef = ref()

const state = reactive({
  loading: false,
  protocolFormTitle: '',
  reactorDialogTitle: '',
  copyId: null as number | null,
  currentOperation: null as { type: 'copy' | 'delete', row: ProtocolDto } | null,
  filter: {
    keyWord: '',
    stDate: '',
    edDate: '',
    equReactorId: null as number | null
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as ProtocolPageInput,
  protocolListData: [] as Array<ProtocolPageDto>,
  showQuery: true,
  showProtocolList: true,
  reactorOptions: [] as Array<{ id: number; name: string; spec: string }>,
})

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

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

const Query = async () => {
  state.loading = true
  state.pageInput.filter = state.filter
  const res = await new ProtocolApi().getPage(state.pageInput).catch(() => {
    state.loading = false
})

  state.protocolListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}

const onAdd = () => {
  state.protocolFormTitle = '新增方案模板'
  protocolFormRef.value?.open()
}

const onEdit = (row: ProtocolDto) => {
  state.protocolFormTitle = '编辑方案模板'
  protocolFormRef.value?.open(row)
}

const onCopy = (row: ProtocolDto) => {
  state.reactorDialogTitle = '复制方案模板 - 选择目标反应器'
  state.currentOperation = { type: 'copy', row }
  state.copyId = row.id
  reactorSelectDialogRef.value?.open()
}

const onDelete = (row: ProtocolDto) => {
  proxy.$modal.confirm('确认要删除该记录吗？').then(async () => {
    try {
      const res = await new ProtocolApi().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 getReactorOptions = async () => {
  try {
    const res = await new ReactorApi().getPage({
      currentPage: 1,
      pageSize: 10000
    })

    if (res?.success) {
      state.reactorOptions = res.data?.list?.map(item => ({
        id: item.id ?? 0,
        name: item.productID ?? '',
        spec: item.specification ?? ''
      })) ?? []
    }
  } catch (error) {
    console.error('获取反应器列表失败:', error)
  }
}

const getReactorDescription = (reactorId: number) => {
  const reactor = state.reactorOptions.find(item => item.id == reactorId)
  return reactor?.name ?? ''
}

const getReactorSpec = (reactorId: number) => {
  const  reactor = state.reactorOptions.find(item => item.id == reactorId)
  return reactor?.spec ?? ''
}

const onReset = () => {
  state.filter = {
    keyWord: '',
    stDate: '',
    edDate: '',
    equReactorId: null
  }
  onQuery()
}

// 处理反应器选择确认
const handleReactorSelect = async (data: { reactorId: number | null, remark: string }) => {
  if (!state.currentOperation) return
  
  try {
    const { type, row } = state.currentOperation
    
    if (type === 'copy' && data.reactorId) {
      const res = await new ProtocolApi().copy({ 
        id: state.copyId!, 
        reactorId: data.reactorId 
      })
      
      if (res.success) {
        proxy.$modal.msgSuccess('复制成功')
        Query()
      }
    }
    
    // 关闭弹窗
    reactorSelectDialogRef.value?.closeDialog()
    state.currentOperation = null
    
  } catch (error) {
    console.error('操作失败:', error)
    reactorSelectDialogRef.value?.closeDialog()
  }
}
</script>

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

.my-fill {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.my-flex {
  display: flex;
}

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

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

.mt8 {
  margin-top: 8px;
}

.mb8 {
  margin-bottom: 8px;
}
</style> 