<template>
  <ContentWrap v-loading="formLoading">
    <!-- 第一部分：日报标题 -->
    <div class="daily-report-title">
      <h2>{{ pageTitle }}</h2>
    </div>

    <!-- 第二部分：项目/任务信息 -->
    <ContentWrap>
      <div class="info-table" style="margin-top: 0.5em">
        <!-- 表格行 -->
        <div class="table-row">
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">油服编码：</span>
              <!-- 甲方字段：添加 single-line-ellipsis 类 + title 绑定完整内容 -->
              <span
                class="cell-value single-line-ellipsis"
                :title="repairInfo.yfDeviceCode || repairInfo.deviceCode || '-'"
              >
                {{ repairInfo.yfDeviceCode || repairInfo.deviceCode || '-' }}
              </span>
            </div>
          </div>
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">设备名称：</span>
              <span class="cell-value">{{ repairInfo.deviceName || '-' }}</span>
            </div>
          </div>
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">维修类型：</span>
              <span class="cell-value">{{
                getDictLabel(DICT_TYPE.PMS_MAIN_TYPE, repairInfo.type)
              }}</span>
            </div>
          </div>
        </div>

        <div class="table-row">
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">维修开始时间：</span>
              <span class="cell-value">{{ formatDate(repairInfo.maintainStartTime) || '-' }}</span>
            </div>
          </div>
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">维修结束日期：</span>
              <span class="cell-value">{{ formatDate(repairInfo.maintainEndTime) || '-' }}</span>
            </div>
          </div>
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">故障时间：</span>
              <span class="cell-value">{{ formatDate(repairInfo.failureTime) || '-' }}</span>
            </div>
          </div>
        </div>
        <div class="table-row">
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">维修人员：</span>
              <span class="cell-value">{{ repairInfo.maintainPersonName || '-' }}</span>
            </div>
          </div>
          <div class="table-cell">
            <div class="cell-content">
              <span class="cell-label">故障系统：</span>
              <span class="cell-value">{{ repairInfo.failureSystem || '-' }}</span>
            </div>
          </div>
          <div class="table-cell">
            <div class="cell-content">
              <!--              <span class="cell-label">故障时间：</span>-->
              <!--              <span class="cell-value">{{ formatDate(repairInfo.failureTime) || '-' }}</span>-->
            </div>
          </div>
        </div>
      </div>
    </ContentWrap>
    <ContentWrap>
      <el-form :inline="true" ref="queryFormRef" :model="queryParams">
        <el-form-item>
          <el-form-item label="维修时间" prop="createTime">
            <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="!w-220px"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button type="primary" @click="openForm('create')">
            <Icon icon="ep:plus" /> 新增
          </el-button>
          <el-button type="warning" @click="viewTimeline">
            <Icon icon="ep:timer" /> 时间线
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column
          label="维修时间"
          align="center"
          prop="repairTime"
          :formatter="dateFormatter"
          width="150px"
        />
        <el-table-column label="维修项" align="center" min-width="90" prop="repairItem" />
        <el-table-column label="维修内容" align="center" min-width="150" prop="repairContent" />
        <el-table-column label="解决办法" align="center" prop="solution" min-width="150" />
        <el-table-column label="图片" align="center"  prop="pic" />
        <el-table-column label="创建人" align="center" prop="createName" />
        <el-table-column label="配合维修人员" align="center" prop="repairPersonName" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="操作" align="center" min-width="90px">
          <template #default="scope">
            <el-button link type="primary" v-if="userid.toString()===scope.row.creator" @click="openForm('update', scope.row.id)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
    <IotJdRecordForm ref="formRef" @success="getList" />
    <MaintainRecordDrawer
      ref="showDrawer"
      :model-value="drawerVisible"
      @update:model-value="(val) => (drawerVisible = val)"
    />
  </ContentWrap>
</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'

const { t } = useI18n()
const message = useMessage()
const { delView } = useTagsViewStore()
const { push, currentRoute } = useRouter()
const { params } = useRoute()
const userStore = useUserStore()
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: 'FillDailyReport', 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>
.info-table {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

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

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

.table-cell {
  flex: 1;
  border-right: 1px solid #e0e0e0;
  padding: 12px 8px;
  min-height: 44px;
  display: flex;
  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 {
  font-weight: 500;
  /* 统一字体大小为 14px（Element 表单默认） */
  font-size: 14px;
  color: #606266;
  min-width: 80px;
  margin-right: 8px;
  flex-shrink: 0;
}

.cell-value {
  /* 统一字体大小为 14px（Element 输入框默认） */
  font-size: 14px;
  color: #303133;
  /* 统一行高为 1.5（Element 组件默认行高） */
  line-height: 1.5;
  flex: 1;
  word-break: break-all;
}

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

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

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

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

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

/* 为第二、三部分增加左右留白 */
.section-padding {
  padding-left: 0px;
  padding-right: 40px;
}
:deep(.el-textarea .el-textarea__inner) {
  min-height: 80px;
}

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

/* 甲方字段：单行显示+超出省略 */
.single-line-ellipsis {
  /* 强制文本单行显示 */
  white-space: nowrap;
  /* 超出容器部分隐藏 */
  overflow: hidden;
  /* 超出部分显示省略号 */
  text-overflow: ellipsis;
  /* 避免文本被截断（可选，根据需求调整） */
  word-break: normal;
}

/* 设备配置字段：换行缩进（与首行对齐） */
.indent-multiline {
  /* 首行及换行后缩进 2em（与 label 宽度匹配，可根据需求调整） */
  text-indent: 0em;
  /* 允许长文本换行（覆盖原有 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) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

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

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

/* 只读模式下表单字段的样式 */
: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) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266; /* 保持文字可读性 */
  cursor: not-allowed;
}

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

/* 审批意见文本域样式 */
: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;
  align-items: center !important;
  height: 32px !important;
  line-height: 32px !important;
  padding: 0 8px !important;
  margin: 0 !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

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

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