<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-position="top" @submit.prevent="handleQuery">
      <el-form-item label="场站名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入场站名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备场站" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入设备场站"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item style="margin-right: 0;">
        <div class="item-search">&nbsp;</div>
        <div class="item-search" style="display: flex; gap: 8px;">
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="场站名称" prop="deptName" />
      <el-table-column label="设备场站" prop="stationName" />
      <el-table-column label="天数" prop="runtimeRange">
        <template #default="scope">
          {{ scope.row.runtimeRange }}
        </template>
      </el-table-column>
      <el-table-column label="安全运行设备数量" prop="runningNum">
        <template #default="scope">
          <el-link type="primary" @click="handleShowOrders(scope.row, 'running')">{{ scope.row.runningNum }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="停运设备数量" prop="stopNum">
        <template #default="scope">
          <el-link type="primary" @click="handleShowOrders(scope.row, 'stopped')">{{ scope.row.stopNum }}</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />



    <!-- 订单列表弹窗 -->
    <el-dialog :title="ordersTitle" v-model="openOrders" width="1200px" append-to-body>
      <el-table v-loading="ordersLoading" :data="ordersList" style="width: 100%">
        <el-table-column prop="pcsDeviceName" label="风机编号" width="120" />
        <el-table-column prop="model" label="机型" width="150" />
        <el-table-column prop="pcsStationName" label="设备场站" width="150" />
        <el-table-column prop="orderType" label="工单类型" width="100">
          <template #default="scope">
            {{ scope.row.orderType == 1 ? '维保工单' : scope.row.orderType == 2 ? '维修工单' : '' }}
          </template>
        </el-table-column>
        <el-table-column label="工单编码" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="handleWorkOrderClick(scope.row)">{{ scope.row.workOrderProjectNo }}</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="isStop" prop="pauseTime" label="停机时间"/>
        <el-table-column prop="restartTime" label="复运时间"/>
        <el-table-column v-if="isStop" prop="stopDays" label="停机天数" />
        <el-table-column v-if="!isStop" prop="runningDays" label="安全运行天数" />
      </el-table>
      <!-- 订单列表分页 -->
      <pagination
        v-show="orderTotal > 0"
        :total="orderTotal"
        v-model:page="orderQueryParams.itemNum"
        v-model:limit="orderQueryParams.itemSize"
        @pagination="getOrdersByNextPage"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openOrders = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MonthRuntime">
import { ref, reactive, toRefs, getCurrentInstance } from "vue"
import { useRouter } from "vue-router"
import { listMonthRuntime,getOrders } from "@/api/gxt/monthRuntime";

const router = useRouter()

const { proxy } = getCurrentInstance()

const list = ref([])
const openOrders = ref(false)
const loading = ref(true)
const ordersLoading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const ordersTitle = ref("")
const isStop = ref(false)
const orderTotal = ref(0)

const orderQueryParams = ref({ itemNum: 1, itemSize: 10, pid: 0, stationId: 0, fromDays: 0, toDays: 0, isStop: false })

const data = reactive({
  formData: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: undefined,
    stationName: undefined,
    monthPeriod: undefined
  },
  ordersList: [],
  rules: {
  }
})

const { queryParams, formData, ordersList, rules } = toRefs(data)

/** 查询月度运行时长列表 */
function getList() {
  loading.value = true
  listMonthRuntime(queryParams.value).then(response => {
    list.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  reset()
}

/** 表单重置 */
function reset() {
  formData.value = {}
  proxy.resetForm("form")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

function getOrdersByNextPage() {
  // 调用API获取订单列表
  ordersLoading.value = true;
  getOrders(orderQueryParams.value).then(response => {
    ordersList.value = response.rows || [];
    orderTotal.value = response.total || 0;
    openOrders.value = true;
    ordersLoading.value = false;
  }).catch(error => {
    console.error('获取订单列表失败:', error);
    ordersLoading.value = false;
  });
}

/** 显示订单列表 */
function handleShowOrders(row, type) {
  isStop.value = type === 'stopped';
  const title = isStop.value ? '停运设备列表' : '安全运行设备列表';
  
  ordersTitle.value = title;

  orderQueryParams.value = { itemNum: 1, itemSize: 10, pid: row.deptId, stationId: row.stationId, fromDays: row.fromDays, toDays: row.toDays || 0, isStop: isStop.value };
  
  // 调用API获取订单列表
  getOrdersByNextPage()
}


    
// 处理工单编码点击事件
function handleWorkOrderClick(row) {
  // 记录来源路由和工单编码
  if (!row.workOrderProjectNo) return
  openOrders.value = false;
  if (row.orderType==1) {
    sessionStorage.setItem('fromRoute', '/workScore/monthScore');
    sessionStorage.setItem('workOrderProjectNo', row.workOrderProjectNo);
    // 跳转到维保工单列表页面
    router.push({
      path: '/workOrder/gxtOrder'
    });
  }else{
    // 记录来源路由和工单编码
    sessionStorage.setItem('fromRouteRepair', '/workScore/monthScore');
    sessionStorage.setItem('workOrderProjectNoRepair', row.workOrderProjectNo);
    // 跳转到维保工单列表页面
    router.push({
      path: '/workOrder/repairOrder'
    });
  }
}

getList()
</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px;
}

.item-search {
  display: flex;
  justify-content: flex-start;;
  align-items: center;
}
</style>