<template>
  <div class="layout-pd">
    <el-row>
      <!--操作-->
      <el-col :xs="24">
        <el-card class="mt8" shadow="hover">
          <el-form :model="state.filter" :inline="true" @submit.stop.prevent>
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="应用">
                  <el-input v-model="state.appName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="油机标识">
                  <el-input v-model="state.filter.MachineId" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="设备sn">
                  <el-input v-model="state.filter.SN" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="登录账户">
                  <el-input v-model="state.filter.Account" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="使用类型">
                  <el-input v-model="state.filter.OpreationType" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>

          <hr>


          <el-row justify="space-between" class="submit-button" style="margin-bottom: -9px;">
            <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
            <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
          </el-row>
        </el-card>
      </el-col>
      <!--表格-->
      <el-col :xs="24">
        <el-card style="height: 70vh" class="my-fill mt8" shadow="hover">
          <el-table v-loading="state.loading" stripe :data="state.tableModel" row-key="id" style="width: 100%">
            <el-table-column type="selection" width="50"></el-table-column>

            <el-table-column v-for="column in state.dynamicColumns" :key="column.prop" :prop="column.prop"
              :label="column.label">
            </el-table-column>
            <el-table-column label="操作" fixed="right" header-align="center" align="center" class="right-operation"
              width="140">
              <template #default="{ row }">
                <el-link class="my-el-link mr12 ml12" type="primary" icon="ele-Upload" @click="onDataDetail(row)"
                  :underline="false" target="_blank">详情</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination v-model:currentPage="pageState.pageInput.currentPage"
              v-model:page-size="pageState.pageInput.pageSize" :total="state.total" :page-sizes="[10, 15, 20, 50, 100]"
              small background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <RecordDetailDialog ref="recordDetailRef"></RecordDetailDialog>
  </div>
</template>
<script setup lang="ts">
import { defineAsyncComponent, onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import eventBus from "/@/utils/mitt";
import { Api } from "/@/api/appOperationRecord/api";
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";

// 使用组合式函数获取分页状态
const pageState = useDynamicPageSize(10, 15);
import { RecordOutput } from "/@/api/appOperationRecord/dto";
import type { pageInput } from "/@/api/appOperationRecord/dto"
import router from "/@/router";
import { PermissionApi } from "/@/api/admin/Permission";
import { ElMessage } from "element-plus";

/**引入组件*/
const RecordDetailDialog = defineAsyncComponent(() => import('./components/record_detail.vue'))
const recordDetailRef = ref()

/**数据对象*/
const state = reactive({
  /**加载显示 */
  loading: false,
  /** 应用名称 */
  appName: "",
  /**条件查询模块 */
  filter: {
    /**油机唯一标识 */
    MachineId: "",
    /**应用的 app id */
    AppId: "",
    /**设备 sn */
    SN: "",
    /**登录账户 */
    Account: "",
    /**使用类型 */
    OpreationType: "",
  },
  /**表格信息 */
  tableModel: [] as RecordOutput,
  /**动态表头 */
  dynamicColumns: [
    { prop: 'machineId', label: '油机唯一标识' },
    { prop: 'sn', label: '设备 sn' },
    { prop: 'account', label: '登录账户' },
    { prop: 'opreationType', label: '使用类型' },
    // { prop: 'recodeJson', label: '使用记录' },
    { prop: 'createTime', label: '操作记录时间' },],
  /**分页标识 */
  pageInput: {
    CurrentPage: 1,
    PageSize: 10,
  } as pageInput,
  /**分页总数 */
  total: 0,
})
onMounted(() => {
  // 初始化分页大小
  state.pageInput.PageSize = pageState.pageInput.pageSize;
  init()
  eventBus.off('refreshView')
  eventBus.on('refreshView', async () => {
    await init()
  })
  console.log()
})
onBeforeMount(() => {
  eventBus.off('refreshView')
})
/**
* 监听变换
*/
// watch(() => { })
/**条件查询 */
const onQuery = async () => {
  state.loading = true;
  try {
    const res: any = await new Api().getList({ 
      ...pageState.pageInput, 
      "Filter.MachineId": state.filter.MachineId,
      "Filter.SN": state.filter.SN,
      "Filter.Account": state.filter.Account,
      "Filter.AppId": state.filter.AppId,
      "Filter.OpreationType": state.filter.OpreationType
    })
    state.total = res?.data?.total ?? 0
    state.tableModel = res?.data?.list ?? []
  } catch (error) {
    console.error('获取操作记录列表失败:', error);
    ElMessage.error('获取操作记录列表失败');
  } finally {
    state.loading = false;
  }
  
}
/**初始化 */
const init = async () => {

  try {
    const name = router.currentRoute.value.params.id;
    const appData = await new PermissionApi().getApplyInfo({ Name: name });
    state.appName = appData.data[0].name;
    state.filter.AppId = appData.data[0].appid;
  } catch (error) {
    console.error('获取应用信息失败:', error);
    ElMessage.error('获取应用信息失败');
  } finally {
    state.loading = false;
    onQuery();
  }

  state.loading = true
  
  state.loading = false
}
/**重置 */
const onReset = () => { }
/**详情 */
const onDataDetail = (row) => {
  recordDetailRef.value.open(row)
}

/**
* 页条变化
* @param val
*/
const onSizeChange = (val: number) => {
  state.pageInput.PageSize = val
  //需按照页面对象修改Data
  onQuery()
}

/**
 * 页数 变化
 * @param val
 */
const onCurrentChange = (val: number) => {
  state.pageInput.CurrentPage = val
  //需按照页面对象修改Data
  onQuery()
}
</script>
<style scoped lang="scss">
.el-input,
.el-select {
  width: 240px;
}

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
  // 字体大小14，5个字符，12px右间距
  width: 14*5px+12px;
  justify-content: start;
}

/* 数据表头 设置灰色样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #F6F6F6;
}
</style>