<template>
  <div v-loading="formLoading" class="maintain-record-page">
    <div class="page-header">
      <div class="page-header__main">
        <div class="page-header__icon"><Icon icon="ep:document" /></div>
        <div>
          <h2 class="page-title">{{ pageTitle }}</h2>
          <p class="page-subtitle">查看设备维修信息并维护维修过程记录</p>
        </div>
      </div>
      <el-button size="default" @click="close">
        <Icon icon="ep:arrow-left" class="mr-5px" />返回
      </el-button>
    </div>

    <section class="page-section info-section">
      <div class="section-header">
        <div class="section-title"><span></span>工单概览</div>
      </div>
      <div class="info-grid">
        <div class="info-item">
          <span class="info-label">油服编码</span>
          <span class="info-value" :title="repairInfo.yfDeviceCode || repairInfo.deviceCode || '-'">
            {{ repairInfo.yfDeviceCode || repairInfo.deviceCode || '-' }}
          </span>
        </div>
        <div class="info-item"
          ><span class="info-label">设备名称</span
          ><span class="info-value">{{ repairInfo.deviceName || '-' }}</span></div
        >
        <div class="info-item"
          ><span class="info-label">维修类型</span
          ><span class="info-value">{{
            getDictLabel(DICT_TYPE.PMS_MAIN_TYPE, repairInfo.type) || '-'
          }}</span></div
        >
        <div class="info-item"
          ><span class="info-label">维修开始时间</span
          ><span class="info-value">{{
            formatDate(repairInfo.maintainStartTime) || '-'
          }}</span></div
        >
        <div class="info-item"
          ><span class="info-label">维修结束日期</span
          ><span class="info-value">{{ formatDate(repairInfo.maintainEndTime) || '-' }}</span></div
        >
        <div class="info-item"
          ><span class="info-label">故障时间</span
          ><span class="info-value">{{ formatDate(repairInfo.failureTime) || '-' }}</span></div
        >
        <div class="info-item"
          ><span class="info-label">维修人员</span
          ><span class="info-value">{{ repairInfo.maintainPersonName || '-' }}</span></div
        >
        <div class="info-item"
          ><span class="info-label">故障系统</span
          ><span class="info-value">{{ repairInfo.failureSystem || '-' }}</span></div
        >
        <div class="info-item info-item--empty" aria-hidden="true"></div>
      </div>
    </section>

    <section class="page-section records-section">
      <div class="section-header">
        <div class="section-title"><span></span>维修记录</div>
        <div class="section-actions">
          <el-button size="default" type="primary" @click="openForm('create')">
            <Icon icon="ep:plus" class="mr-5px" />新增
          </el-button>
          <el-button size="default" type="warning" @click="viewTimeline">
            <Icon icon="ep:timer" class="mr-5px" />时间线
          </el-button>
        </div>
      </div>

      <el-form ref="queryFormRef" :model="queryParams" size="default" class="query-form">
        <el-form-item label="维修时间" prop="repairTime">
          <el-date-picker
            v-model="queryParams.repairTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="query-date" />
        </el-form-item>
        <el-form-item class="query-actions">
          <el-button size="default" type="primary" @click="handleQuery"
            ><Icon icon="ep:search" class="mr-5px" />搜索</el-button
          >
          <el-button size="default" @click="resetQuery"
            ><Icon icon="ep:refresh" class="mr-5px" />重置</el-button
          >
        </el-form-item>
      </el-form>

      <div class="table-wrap">
        <ZmTable
          :loading="loading"
          :data="list"
          :show-border="true"
          settings-cache-key="pms-maintain-record-list">
          <ZmTableColumn
            label="维修时间"
            prop="repairTime"
            :formatter="dateFormatter"
            min-width="150" />
          <ZmTableColumn label="维修项" prop="repairItem" />
          <ZmTableColumn label="维修内容" prop="repairContent" min-width="150" />
          <ZmTableColumn label="解决办法" prop="solution" min-width="150" />
          <ZmTableColumn label="图片" prop="pic" />
          <ZmTableColumn label="创建人" prop="createName" />
          <ZmTableColumn label="配合维修人员" prop="repairPersonName" />
          <ZmTableColumn label="备注" prop="remark" />
          <ZmTableColumn
            label="创建时间"
            prop="createTime"
            :formatter="dateFormatter"
            min-width="180" />
          <ZmTableColumn label="操作" width="90" fixed="right">
            <template #default="scope">
              <el-button
                v-if="userid.toString() === scope.row.creator"
                size="default"
                link
                type="primary"
                @click="openForm('update', scope.row.id)">
                编辑
              </el-button>
            </template>
          </ZmTableColumn>
        </ZmTable>
      </div>

      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </section>

    <IotJdRecordForm ref="formRef" @success="getList" />
    <MaintainRecordDrawer
      ref="showDrawer"
      :model-value="drawerVisible"
      @update:model-value="(val) => (drawerVisible = val)" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { IotMaintainApi, IotMaintainVO } from '@/api/pms/maintain'
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import dayjs from 'dayjs'
import { dateFormatter } from '@/utils/formatTime'
import { IotJdRecordApi, IotJdRecordVO } from '@/api/pms/maintain/record'
import IotJdRecordForm from '@/views/pms/maintain/record/IotJdRecordForm.vue'
import MaintainRecordDrawer from '@/views/pms/maintain/MaintainRecordDrawer.vue'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'

const { t } = useI18n()
const message = useMessage()
const { delView } = useTagsViewStore()
const { push, currentRoute } = useRouter()
const { params } = useRoute()
const userStore = useUserStore()
const { ZmTable, ZmTableColumn } = useTableComponents<IotJdRecordVO>()
const total = ref(0) // 列表的总页数
const list = ref<IotJdRecordVO[]>([])
const loading = ref(true) // 列表的加载中
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const queryFormRef = ref() // 搜索的表单
/** 填报日报 表单 */
defineOptions({ name: 'MaintainRecord' })

/**打开时间线*/
const viewTimeline = () => {
  drawerVisible.value = true
  showDrawer.value.openDrawer(id)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, recordId: any) => {
  formRef.value.open(type, id, recordId)
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.repairId = id
    const data = await IotJdRecordApi.getIotJdRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: undefined,
  repairId: undefined,
  repairTime: [],
  repairContent: undefined,
  pic: undefined,
  solution: undefined,
  remark: undefined,
  createTime: [],
  deviceName: undefined
})

const formLoading = ref(false)
// 页面标题计算
const pageTitle = computed(() => {
  return (
    repairInfo.value.yfDeviceCode ||
    repairInfo.value.deviceCode + repairInfo.value.deviceName + '维修记录'
  )
})

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotMaintain', params: {} })
}

const formatDate = (timestamp: number) => {
  if (!timestamp) return ''
  return dayjs(timestamp).format('YYYY-MM-DD')
}

const repairInfo = ref<IotMaintainVO>({})
const id = params.id //维修工单主键id
const userid = ref('')
onMounted(async () => {
  userid.value = useUserStore().getUser.id
  debugger
  formLoading.value = true
  try {
    repairInfo.value = await IotMaintainApi.getIotMaintain(id)
    await getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    message.error('数据加载失败')
  } finally {
    formLoading.value = false
  }
})
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .table-row {
    flex-direction: column;
  }

  .table-cell {
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
  }

  .table-cell:last-child {
    border-bottom: none;
  }
}

@media (width <= 1200px) {
  .info-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .info-item--empty {
    display: none;
  }
}

@media (width <= 768px) {
  .maintain-record-page {
    padding: 12px;
  }

  .page-header,
  .section-header {
    padding-right: 12px;
    padding-left: 12px;
  }

  .page-subtitle {
    display: none;
  }

  .section-header {
    align-items: flex-start;
    flex-direction: column;
    padding-top: 12px;
    padding-bottom: 12px;
  }

  .section-actions {
    justify-content: flex-start;
    width: 100%;
  }

  .info-grid {
    grid-template-columns: minmax(0, 1fr);
    margin: 12px;
  }

  .query-form,
  .table-wrap {
    padding-right: 12px;
    padding-left: 12px;
  }

  .query-form,
  .query-form :deep(.el-form-item),
  .query-date {
    width: 100%;
  }
}

.info-table {
  overflow: hidden;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  display: flex;
  min-height: 44px;
  padding: 12px 8px;
  border-right: 1px solid #e0e0e0;
  flex: 1;
  align-items: center;
}

.table-cell:last-child {
  border-right: none;
}

.table-cell.full-width {
  flex: 1;
  border-right: none;
}

.cell-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.cell-label {
  min-width: 80px;
  margin-right: 8px;

  /* 统一字体大小为 14px（Element 表单默认） */
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  flex-shrink: 0;
}

.cell-value {
  /* 统一字体大小为 14px（Element 输入框默认） */
  font-size: 14px;

  /* 统一行高为 1.5（Element 组件默认行高） */
  line-height: 1.5;
  color: #303133;
  word-break: break-all;
  flex: 1;
}

.daily-report-title {
  padding: 5px;
  margin: 5px 0;
  text-align: center;
  border-bottom: 2px solid #409eff;
}

.daily-report-title h2 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

/* 为第二、三部分增加左右留白 */
.section-padding {
  padding-right: 40px;
  padding-left: 0;
}

:deep(.el-textarea .el-textarea__inner) {
  min-height: 80px;
}

/* 确保表单label不换行 */
:deep(.el-form-item__label) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 甲方字段：单行显示+超出省略 */
.single-line-ellipsis {
  /* 超出容器部分隐藏 */
  overflow: hidden;

  /* 超出部分显示省略号 */
  text-overflow: ellipsis;

  /* 避免文本被截断（可选，根据需求调整） */
  word-break: normal;

  /* 强制文本单行显示 */
  white-space: nowrap;
}

/* 设备配置字段：换行缩进（与首行对齐） */
.indent-multiline {
  /* 首行及换行后缩进 2em（与 label 宽度匹配，可根据需求调整） */
  text-indent: 0;

  /* 允许长文本换行（覆盖原有 cell-value 的 break-all，确保中文换行正常） */
  word-break: break-word;

  /* 保证换行后文本正常显示（可选，清除可能的 nowrap 影响） */
  white-space: normal;
}

/* 审批模式下表单字段的只读样式 */
:deep(.el-form-item.is-disabled .el-input__inner),
:deep(.el-form-item.is-disabled .el-textarea__inner) {
  color: #c0c4cc;
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

:deep(.el-form-item.is-disabled .el-select .el-input__inner) {
  color: #c0c4cc;
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

:deep(.el-form-item.is-disabled .el-date-editor .el-input__inner) {
  color: #c0c4cc;
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

/* 只读模式下表单字段的样式 */
:deep(.el-form-item.is-disabled .el-input__inner),
:deep(.el-form-item.is-disabled .el-textarea__inner),
:deep(.el-form-item.is-disabled .el-select .el-input__inner),
:deep(.el-form-item.is-disabled .el-date-editor .el-input__inner) {
  color: #606266; /* 保持文字可读性 */
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

/* 详情模式下的特殊样式 */
.detail-mode .cell-value {
  font-weight: normal;
  color: #303133;
}

/* 审批意见文本域样式 */
:deep(.approval-opinion .el-textarea__inner) {
  min-height: 100px;
  resize: vertical;
}

/* 审批意见标签样式 */
:deep(.approval-opinion .el-form-item__label) {
  font-weight: bold;
  color: #606266;
}

:deep(.el-transfer-panel) {
  width: 40% !important;
}

:deep(.el-transfer-panel__item) {
  display: flex !important;
  height: 32px !important;
  padding: 0 8px !important;
  margin: 0 !important;
  overflow: hidden;
  line-height: 32px !important;
  text-overflow: ellipsis;
  white-space: nowrap;
  align-items: center !important;
}

:deep(.el-transfer-panel__list) {
  width: 100% !important;
}

/* 只读模式下的设备显示样式 */
:deep(.is-disabled) .device-display-container {
  color: #606266;
  cursor: not-allowed;
  background-color: #f5f7fa;
}

.maintain-record-page {
  min-height: calc(
    100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
  );
  padding: 16px;
  background: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  margin-bottom: 16px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 8%);
}

.page-header__main {
  display: flex;
  align-items: center;
  min-width: 0;
}

.page-header__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  margin-right: 12px;
  font-size: 20px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 8px;
}

.page-title {
  max-width: min(720px, 65vw);
  margin: 0;
  overflow: hidden;
  font-size: 18px;
  font-weight: 600;
  line-height: 26px;
  color: var(--el-text-color-primary);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.page-subtitle {
  margin: 2px 0 0;
  font-size: 13px;
  line-height: 20px;
  color: var(--el-text-color-secondary);
}

.page-section {
  margin-bottom: 16px;
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 5%);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  min-height: 54px;
  padding: 0 20px;
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.section-title {
  display: flex;
  align-items: center;
  flex: 0 0 auto;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.section-title span {
  width: 4px;
  height: 18px;
  margin-right: 10px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.section-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-end;
}

.section-actions :deep(.el-button),
.query-actions :deep(.el-button) {
  margin-left: 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 1px;
  margin: 16px 20px;
  overflow: hidden;
  background: var(--el-border-color-lighter);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
}

.info-item {
  display: flex;
  align-items: center;
  min-width: 0;
  min-height: 48px;
  padding: 10px 14px;
  background: var(--el-bg-color);
}

.info-label {
  flex: 0 0 104px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}

.info-value {
  min-width: 0;
  overflow: hidden;
  font-weight: 500;
  color: var(--el-text-color-primary);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px 20px;
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.query-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.query-date {
  width: 260px;
}

.query-actions :deep(.el-form-item__content) {
  display: flex;
  gap: 8px;
}

.table-wrap {
  padding: 16px 20px;
}

.records-section :deep(.pagination-container) {
  padding: 12px 20px;
}
</style>
