<template>
  <MyLayout>
    <el-card class="my-query-box mt8" shadow="never">
      <template #header>
        <el-form ref="queryFormRef" :model="state.filter" :inline="true" class="demo-form-inline">
          <el-form-item label="策略名称">
            <el-input v-model="state.filter.keyWord" placeholder="请输入策略名称" clearable />
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="state.filter.stDate"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="state.filter.edDate"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="ele-Search" @click="handleQuery">查询</el-button>
            <el-button v-if="hasAuth('api:admin:usp-feeding-config:add')" type="primary" icon="ele-Plus" @click="handleAdd">
            新增
          </el-button>
          </el-form-item>
        </el-form>
      </template>
    </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-loading="state.loading"
        :data="state.tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="configName" label="策略名称" min-width="120" show-overflow-tooltip />
        <el-table-column label="补料方式" min-width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="info" v-if="row.isTwoStep === 1">二段式</el-tag>
            <el-tag type="success " v-else>三段式</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="feedTime" label="补料时长 min" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.isTwoStep === 1">-</span>
            <span v-else>{{ row.feedTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="calibrateDuration" label="校准阶段时长/s" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.isTwoStep === 1">-</span>
            <span v-else>{{ row.calibrateDuration }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="calibrateVolumePercent" label="校准阶段补料占总量百分比/%" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.isTwoStep === 1">-</span>
            <span v-else>{{ row.calibrateVolumePercent }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="highSpeedPercent" label="高速阶段泵速比例/%" min-width="140" show-overflow-tooltip />
        <el-table-column prop="highSpeedVolumePercent" label="高速阶段补料占比/%" min-width="140" show-overflow-tooltip />
        <el-table-column prop="lowSpeedPercent" label="低速阶段泵速比例/%" min-width="140" show-overflow-tooltip />
        <el-table-column prop="lowSpeedVolumePercent" label="低速阶段补料占比/%" min-width="140" show-overflow-tooltip />
        <el-table-column label="状态" width="80" 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 label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
              v-if="hasAuth('api:admin:usp-feeding-config:update')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
              v-if="hasAuth('api:admin:usp-feeding-config:soft-delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <feeding-config-form
      ref="formRef"
      v-model="showForm"
      @refresh="getList"
      title="泵速策略"
    />
  </MyLayout>
</template>

<script lang="ts" setup name="admin/feeding-config">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UspFeedingConfigApi } from '/@/api/admin/UspFeedingConfigApi'
import {
  PageInputFeedingConfigGetPageInput,
  FeedingConfigGetPageOutput,
  FeedingConfigGetPageInput
} from '/@/api/admin/data-contracts'
import FeedingConfigForm from './components/feeding-config-form.vue'
import { auth as hasAuth } from '/@/utils/authFunction'
import { filter } from 'lodash-es'

const { proxy } = getCurrentInstance() as any

const formRef = ref()

const state = reactive({
  loading: false,
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as PageInputFeedingConfigGetPageInput,
  tableData: [] as FeedingConfigGetPageOutput[],
  filter: {
    keyWord: '',
      stDate: '',
      edDate: ''
  },
})

// 初始化API实例
const uspFeedingConfigApi = new UspFeedingConfigApi()  // HttpClient 默认配置

const getList = async () => {
  state.loading = true
  try {
    state.pageInput.filter = {
      keyWord: state.filter.keyWord || '',
      stDate: state.filter.stDate || null,
      edDate: state.filter.edDate || null,
    }

    const res = await uspFeedingConfigApi.getPage(state.pageInput)
    console.log(res)
    if (res.success && res.data) {
      state.tableData = res.data.list || []
      state.total = res.data.total || 0
    } else {
      state.tableData = []
      state.total = 0
      ElMessage.warning(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取列表数据出错:', error)
    ElMessage.error('获取列表数据出错')
  } finally {
    state.loading = false
  }
}

const handleQuery = () => {
  state.pageInput.currentPage = 1
  getList()
}

const resetQuery = () => {
  state.filter.keyWord = ''
  state.filter.stDate = ''
  state.filter.edDate = ''
  handleQuery()
}

const handleSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  getList()
}

const handleAdd = () => {
  formRef.value?.open()
}

const handleEdit = (row: FeedingConfigGetPageOutput) => {
  formRef.value?.open(row)
}

const handleDelete = (row: FeedingConfigGetPageOutput) => {
  ElMessageBox.confirm('确认要删除该泵速策略吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log(row)
      const res = await uspFeedingConfigApi.softDelete({ id: row.id })
      if (res) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除出错:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const showForm = ref(false)

onMounted(() => {
  getList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
