<template>
  <!-- dutyLogApproval  审批按钮权限 -->
  <div class="edit-add-detail">
    <div
      v-loading="formLoading"
      class="form-content"
      element-loading-background="rgba(10 ,38 ,61, 0.95)"
      element-loading-text="数据加载中..."
    >
      <el-form
        ref="addEditForm"
        :model="addEditForm"
        :rules="addEditRules"
        label-position="left"
        label-suffix="："
        label-width="120px"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">值班日志</div>
          </div>
        </div>
        <div class="form-wrapper">
          <div class="title">
            <div>运行监测调度中心</div>
            <div>值 班 记 录</div>
          </div>
          <el-descriptions :column="3" border :labelStyle="{width: '140px'}">
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star">*</span>所属路段
              </template>
              <el-form-item prop="roadInfos">
                <el-select
                  v-model="addEditForm.roadInfos"
                  multiple
                  placeholder="请选择所属路段"
                >
                  <el-option
                    v-for="item in roadOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <span class="required-star">*</span>班次
              </template>
              <el-form-item prop="shiftName">
                <el-select
                  v-model="addEditForm.shiftName"
                  style="width: 100%"
                  placeholder="请选择班次"
                  clearable
                >
                  <el-option
                    v-for="item in getDictionaryByCode('pbbc')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="2">
              <template slot="label">
                <span class="required-star">*</span>工作时间
              </template>
              <el-form-item prop="dateRange">
                <el-date-picker
                  range-separator="至"
                  start-placeholder="工作开始时间"
                  end-placeholder="工作结束时间"
                  v-model="addEditForm.dateRange"
                  type="datetimerange"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:00"
                  :default-time="['00:00:00', '23:59:59']"
                ></el-date-picker>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star">*</span>值班人员
              </template>
              <el-form-item prop="dutyPersonnel">
                <el-input
                  type="textarea"
                  rows="2"
                  v-model="addEditForm.dutyPersonnel"
                  placeholder="请输入值班人员"
                  @blur="trimField('dutyPersonnel')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star text-row"
                  >* <span class="text-row-color">值班记录</span></span
                >
              </template>
              <el-form-item
                :prop="
                  !isNewData && addEditForm.dutySituation
                    ? 'dutySituation'
                    : 'dutySituationList'
                "
              >
                <!-- 编辑旧数据：有 dutySituation 字符串时使用 el-input -->
                <el-input
                  v-if="!isNewData && addEditForm.dutySituation"
                  type="textarea"
                  rows="12"
                  placeholder="请输入当班情况记录"
                  v-model="addEditForm.dutySituation"
                  @blur="trimField('dutySituation')"
                ></el-input>
                <!-- 新增数据或编辑列表模式数据：使用表格形式 -->
                <div v-else class="duty-table-wrapper">
                  <el-table
                    size="small"
                    :data="addEditForm.dutySituationList"
                    border
                    style="width: 100%"
                  >
                    <el-table-column
                      align="center"
                      label="序号"
                      type="index"
                      width="60"
                    />
                    <!-- <el-table-column align="center" label="时间" width="150">
                      <template v-slot="{ row }">
                        <el-time-picker
                          v-model="row.recordTime"
                          size="small"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder="选择时间"
                          style="width: 100%"
                        />
                      </template>
                    </el-table-column> -->
                    <el-table-column align="center" label="记录">
                      <template v-slot="{row}">
                        <el-input
                          v-model="row.content"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入记录内容"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="80">
                      <template v-slot="{$index}">
                        <el-link
                          type="danger"
                          :underline="false"
                          @click="handleDeleteDutyItem($index)"
                        >
                          删除
                        </el-link>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="table-actions">
                    <el-button
                      type="primary"
                      size="small"
                      icon="el-icon-plus"
                      @click="handleAddDutyItem"
                    >
                      添加
                    </el-button>
                  </div>
                </div>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions
            :column="6"
            border
            class="el-descriptions-table"
            direction="vertical"
          >
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              交通事故
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="trafficAccidentCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.trafficAccidentCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="trafficAccidentDetail">
                <el-input
                  v-model="addEditForm.trafficAccidentDetail"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              人员伤亡
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="casualtyCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.casualtyCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="casualtyDetail">
                <el-input v-model="addEditForm.casualtyDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              管制情况
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="controlSituationCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.controlSituationCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="controlSituationDetail">
                <el-input
                  v-model="addEditForm.controlSituationDetail"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              重大事件记录
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="majorEventCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.majorEventCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="majorEventDetail">
                <el-input v-model="addEditForm.majorEventDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              拥堵情况
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="congestionCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.congestionCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="congestionDetail">
                <el-input v-model="addEditForm.congestionDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              设备报修
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="equipmentRepairCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.equipmentRepairCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="equipmentRepairDetail">
                <el-input
                  v-model="addEditForm.equipmentRepairDetail"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              投诉记录
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="complaintCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.complaintCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="complaintDetail">
                <el-input v-model="addEditForm.complaintDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              清障救援
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="rescueCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.rescueCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="rescueDetail">
                <el-input v-model="addEditForm.rescueDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              外单位来访
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="visitCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.visitCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="visitDetail">
                <el-input v-model="addEditForm.visitDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              来电询问
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="inquiryCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.inquiryCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="inquiryDetail">
                <el-input v-model="addEditForm.inquiryDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions border :labelStyle="{width: '140px'}">
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star text-row"
                  >* <span class="text-row-color">交接情况</span></span
                >
              </template>
              <el-form-item
                :prop="
                  !isNewData && addEditForm.handoverSituation
                    ? 'handoverSituation'
                    : 'handoverSituationList'
                "
              >
                <!-- 编辑旧数据：有 handoverSituation 字符串时使用 el-input -->
                <el-input
                  v-if="!isNewData && addEditForm.handoverSituation"
                  type="textarea"
                  rows="6"
                  placeholder="请输入交接情况"
                  v-model="addEditForm.handoverSituation"
                  @blur="trimField('handoverSituation')"
                ></el-input>
                <!-- 新增数据或编辑列表模式数据：使用表格形式 -->
                <div v-else class="duty-table-wrapper">
                  <el-table
                    :data="addEditForm.handoverSituationList"
                    border
                    style="width: 100%"
                  >
                    <el-table-column
                      align="center"
                      label="序号"
                      type="index"
                      width="60"
                    />
                    <!-- <el-table-column align="center" label="时间" width="150">
                      <template v-slot="{ row }">
                        <el-time-picker
                          v-model="row.recordTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder="选择时间"
                          style="width: 100%"
                        />
                      </template>
                    </el-table-column> -->
                    <el-table-column align="center" label="记录">
                      <template v-slot="{row}">
                        <el-input
                          v-model="row.content"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入记录内容"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="80">
                      <template v-slot="{$index}">
                        <el-link
                          type="danger"
                          :underline="false"
                          @click="
                            handleDeleteTableItem(
                              'handoverSituationList',
                              $index
                            )
                          "
                        >
                          删除
                        </el-link>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="table-actions">
                    <el-button
                      type="primary"
                      size="small"
                      icon="el-icon-plus"
                      @click="handleAddTableItem('handoverSituationList')"
                    >
                      添加
                    </el-button>
                  </div>
                </div>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star text-row"
                  >* <span class="text-row-color">设施设备</span></span
                >
              </template>
              <el-form-item
                :prop="
                  !isNewData && addEditForm.facilityStatus
                    ? 'facilityStatus'
                    : 'facilityStatusList'
                "
              >
                <!-- 编辑旧数据：有 facilityStatus 字符串时使用 el-input -->
                <el-input
                  v-if="!isNewData && addEditForm.facilityStatus"
                  type="textarea"
                  rows="6"
                  placeholder="请输入设施设备情况"
                  v-model="addEditForm.facilityStatus"
                  @blur="trimField('facilityStatus')"
                ></el-input>
                <!-- 新增数据或编辑列表模式数据：使用表格形式 -->
                <div v-else class="duty-table-wrapper">
                  <el-table
                    :data="addEditForm.facilityStatusList"
                    border
                    style="width: 100%"
                  >
                    <el-table-column
                      align="center"
                      label="序号"
                      type="index"
                      width="60"
                    />
                    <!-- <el-table-column align="center" label="时间" width="150">
                      <template v-slot="{ row }">
                        <el-time-picker
                          v-model="row.recordTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder="选择时间"
                          style="width: 100%"
                        />
                      </template>
                    </el-table-column> -->
                    <el-table-column align="center" label="记录">
                      <template v-slot="{row}">
                        <el-input
                          v-model="row.content"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入记录内容"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="80">
                      <template v-slot="{$index}">
                        <el-link
                          type="danger"
                          :underline="false"
                          @click="
                            handleDeleteTableItem('facilityStatusList', $index)
                          "
                        >
                          删除
                        </el-link>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="table-actions">
                    <el-button
                      type="primary"
                      size="small"
                      icon="el-icon-plus"
                      @click="handleAddTableItem('facilityStatusList')"
                    >
                      添加
                    </el-button>
                  </div>
                </div>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star">*</span>接班人员
              </template>
              <el-form-item prop="nextShiftPersonnel">
                <el-input
                  type="textarea"
                  rows="2"
                  placeholder="请输入接班人员"
                  v-model="addEditForm.nextShiftPersonnel"
                  @blur="trimField('nextShiftPersonnel')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item
              :span="3"
              v-if="BtnAuth('dutyLogApproval') && id"
            >
              <template slot="label">
                <span class="required-star">*</span>管理员意见
              </template>
              <el-form-item prop="adminComment">
                <el-input
                  type="textarea"
                  rows="2"
                  v-model="addEditForm.adminComment"
                  placeholder="请输入管理员意见"
                  @blur="trimField('adminComment')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form>
    </div>

    <div slot="footer" class="footer">
      <el-button
        v-if="BtnAuth('dutyLogApproval') && id"
        :disabled="formLoading"
        :loading="saveLoading"
        type="warning"
        @click="handleSave('audit')"
      >
        审核并保存
      </el-button>
      <el-button
        :disabled="formLoading"
        :loading="saveLoading"
        type="primary"
        @click="handleSave"
      >
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>

    <el-backtop :visibility-height="10" target=".el-form">
      <div class="top-box">UP</div>
    </el-backtop>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import moment from 'moment'
import 'moment-duration-format'
import {getDictionaryByCode} from '@/utils/dictionary'
import {
  tableAdd,
  tableEdit,
  tableDetail,
  getDutyPerson,
  auditDutyRecord,
  getReplacePerson,
  unlockEdit
} from '@/api/patrolAndRescue/commandDispatch/reportManagement/dutyRecords.js'
import {roadData} from '@/api/patrolAndRescue/roadDamageComp/roadDamageRegister'
import utils from '@/utils/utils.js'

export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      dutyLogApproval: '',
      isNewData: true, // 新增: 标识是否为新增数据
      addEditForm: {
        roadInfos: [],
        shiftName: '',
        dateRange: [
          moment()
            .subtract(1, 'day')
            .hour(9)
            .minute(0)
            .second(0)
            .format('YYYY-MM-DD HH:mm:ss'),
          moment()
            .subtract(1, 'day')
            .hour(18)
            .minute(0)
            .second(0)
            .format('YYYY-MM-DD HH:mm:ss')
        ],
        startTime: '',
        endTime: '',
        dutyPersonnel: '',
        dutySituation: '',
        dutySituationList: [{content: '', type: 'duty'}], // 新增: 表格形式的数据，默认一条示例数据
        handoverSituation: '',
        handoverSituationList: [{content: '', type: 'handover'}],
        facilityStatus: '',
        facilityStatusList: [{content: '', type: 'facility'}],
        nextShiftPersonnel: '',
        trafficAccidentCount: 0,
        trafficAccidentDetail: '详见突发事件记录',
        casualtyCount: 0,
        casualtyDetail: '详见突发事件记录',
        controlSituationCount: 0,
        controlSituationDetail: '详见值班日志',
        majorEventCount: 0,
        majorEventDetail: '详见重大事件记录',
        congestionCount: 0,
        congestionDetail: '详见值班日志',
        equipmentRepairCount: 0,
        equipmentRepairDetail: '详见设备报修记录',
        complaintCount: 0,
        complaintDetail: '详见投诉记录',
        rescueCount: 0,
        rescueDetail: '详见清障救援记录',
        visitCount: 0,
        visitDetail: '详见外单位来访记录',
        inquiryCount: 0,
        inquiryDetail: '详见来电记录',
        adminComment: ''
      },
      addEditRules: {
        roadInfos: [
          {required: true, message: '路段不能为空', trigger: 'change'}
        ],
        shiftName: [
          {required: true, message: '班次不能为空', trigger: 'change'}
        ],
        dateRange: [
          {required: true, message: '日期不能为空', trigger: 'change'}
        ],
        dutyPersonnel: [
          {required: true, message: '值班人员不能为空', trigger: 'change'}
        ],
        dutySituation: [
          {required: true, message: '值班情况不能为空', trigger: 'change'}
        ],
        dutySituationList: [
          {
            validator: (_, value, callback) => {
              // 如果是旧数据模式（有 dutySituation），跳过验证
              if (!this.isNewData && this.addEditForm.dutySituation) {
                callback()
                return
              }
              // 表格模式：验证至少有一条数据且每条数据都有内容
              if (!value || value.length === 0) {
                callback(new Error('值班情况不能为空'))
                return
              }
              // 验证每条记录是否完整
              const emptyItem = value.find(item => !item.content)
              if (emptyItem) {
                callback(new Error('请完善值班记录的时间和内容'))
                return
              }
              callback()
            },
            trigger: 'change'
          }
        ],
        handoverSituation: [
          {required: true, message: '交接情况不能为空', trigger: 'change'}
        ],
        handoverSituationList: [
          {
            validator: (_, value, callback) => {
              if (!this.isNewData && this.addEditForm.handoverSituation) {
                callback()
                return
              }
              if (!value || value.length === 0) {
                callback(new Error('交接情况不能为空'))
                return
              }
              const emptyItem = value.find(item => !item.content)
              if (emptyItem) {
                callback(new Error('请完善交接记录的时间和内容'))
                return
              }
              callback()
            },
            trigger: 'change'
          }
        ],
        facilityStatus: [
          {required: true, message: '设施设备不能为空', trigger: 'change'}
        ],
        facilityStatusList: [
          {
            validator: (_, value, callback) => {
              if (!this.isNewData && this.addEditForm.facilityStatus) {
                callback()
                return
              }
              if (!value || value.length === 0) {
                callback(new Error('设施设备不能为空'))
                return
              }
              const emptyItem = value.find(item => !item.content)
              if (emptyItem) {
                callback(new Error('请完善设施设备记录的时间和内容'))
                return
              }
              callback()
            },
            trigger: 'change'
          }
        ],
        nextShiftPersonnel: [
          {required: true, message: '接班人员不能为空', trigger: 'change'}
        ],
        adminComment: [
          {required: true, message: '管理员意见', trigger: 'change'}
        ]
      },
      saveLoading: false, // 上传loading
      formLoading: false, // 上传loading
      roadOptions: [], // 路段数据
      id: '', // id标识符
      pubSub: null
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {},
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      this.getRoadData()
      // 新增或修改
      if (data.id) {
        this.id = data.id
        this.isNewData = false // 编辑模式
        this.getDetail(data.id)
      } else {
        this.isNewData = true // 新增模式
        this.getDutyPersonData()
        this.getReplacePersonData()
        this.addEditForm.shiftName =
          this.getDictionaryByCode('pbbc')[0].value || ''
        // 新增时初始化表格数据，默认一条示例数据
        this.addEditForm.dutySituationList = [{content: '', type: 'duty'}]
        this.addEditForm.handoverSituationList = [
          {content: '', type: 'handover'}
        ]
        this.addEditForm.facilityStatusList = [{content: '', type: 'facility'}]
      }
    })

    // 监听页面退出事件
    window.addEventListener('beforeunload', this.handlePageUnload)
    window.addEventListener('popstate', this.handlePageUnload)
  },
  methods: {
    // 页面退出时解锁
    async handlePageUnload() {
      if (this.id) {
        try {
          await unlockEdit(this.id)
        } catch (error) {
          console.error('解锁失败:', error)
        }
      }
    },

    // 删除
    saveConfirm(type = 'save') {
      this.$confirm(
        `确定${type === 'audit' ? '审核并保存' : '保存'}值班日志吗？`,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          this.saveLoading = true
          let {
            dateRange = [],
            roadInfos = [],
            dutySituation,
            dutySituationList,
            handoverSituation,
            handoverSituationList,
            facilityStatus,
            facilityStatusList,
            ...addEditForm
          } = this.addEditForm
          const API =
            this.id && type === 'audit'
              ? auditDutyRecord
              : this.id
              ? tableEdit
              : tableAdd

          const roadInfosAll = this.roadOptions.filter(item =>
            roadInfos.includes(item.id)
          )

          // 构建提交数据
          const submitData = {
            ...addEditForm,
            roadInfos: roadInfosAll,
            startTime: dateRange[0],
            endTime: dateRange[1]
          }

          // 根据数据模式提交对应字段
          if (
            !this.isNewData &&
            dutySituation !== undefined &&
            dutySituation !== null &&
            dutySituation !== ''
          ) {
            submitData.dutySituation = dutySituation
          } else {
            submitData.dutySituationList = dutySituationList
          }
          if (
            !this.isNewData &&
            handoverSituation !== undefined &&
            handoverSituation !== null &&
            handoverSituation !== ''
          ) {
            submitData.handoverSituation = handoverSituation
          } else {
            submitData.handoverSituationList = handoverSituationList
          }
          if (
            !this.isNewData &&
            facilityStatus !== undefined &&
            facilityStatus !== null &&
            facilityStatus !== ''
          ) {
            submitData.facilityStatus = facilityStatus
          } else {
            submitData.facilityStatusList = facilityStatusList
          }

          try {
            let {state, message} = await API(submitData)

            if (state) {
              message =
                this.id && type === 'audit'
                  ? '审核并保存'
                  : this.id
                  ? '修改'
                  : '新增'
              this.$message.success(`值班日志${message}成功`)
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        })
        .catch(_ => _)
    },
    trimField(fieldName) {
      if (this.addEditForm[fieldName]) {
        this.addEditForm[fieldName] = this.addEditForm[fieldName].trim()
      }
    },

    // 添加值班记录项
    handleAddDutyItem() {
      this.addEditForm.dutySituationList.push({
        content: '',
        type: 'duty'
      })
    },

    // 删除值班记录项
    handleDeleteDutyItem(index) {
      this.$confirm('确定删除该条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addEditForm.dutySituationList.splice(index, 1)
      })
    },

    // 通用添加表格项
    handleAddTableItem(fieldName) {
      const typeMap = {
        handoverSituationList: 'handover',
        facilityStatusList: 'facility'
      }
      this.addEditForm[fieldName].push({
        content: '',
        type: typeMap[fieldName]
      })
    },

    // 通用删除表格项
    handleDeleteTableItem(fieldName, index) {
      this.$confirm('确定删除该条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addEditForm[fieldName].splice(index, 1)
      })
    },
    BtnAuth(btnCode) {
      return utils.BtnAuth(btnCode)
    },
    async getDutyPersonData() {
      const res = await getDutyPerson()
      const dutyPerson = res.reduce((acc, cur) => {
        return (acc += cur.userName + ',')
      }, '')
      this.addEditForm.dutyPersonnel = dutyPerson.slice(0, -1)
    },
    async getReplacePersonData() {
      const res = await getReplacePerson()
      const dutyPerson = res.reduce((acc, cur) => {
        return (acc += cur.userName + ',')
      }, '')
      this.addEditForm.nextShiftPersonnel = dutyPerson.slice(0, -1)
    },
    async getRoadData() {
      try {
        const {rows = []} = await roadData({pageBean: {pageSize: -1}})
        this.roadOptions = rows
        if (!this.id) {
          this.addEditForm.roadInfos = rows[0] && [rows[0].id || '']
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 获取详情
    async getDetail(id) {
      this.formLoading = true
      try {
        let {
          startTime = '',
          endTime = '',
          roadInfos = [],
          dutySituation,
          dutySituationList,
          handoverSituation,
          handoverSituationList,
          facilityStatus,
          facilityStatusList,
          ...addEditForm
        } = await tableDetail(id)

        const roadInfosId = roadInfos.map(i => i.id)

        // 直接返回列表数据，不需要转换
        const processField = (strValue, listValue, type) => {
          const hasString =
            strValue !== undefined && strValue !== null && strValue !== ''
          let listData = []
          if (hasString) {
            // 有字符串数据，不显示列表
            listData = []
          } else if (listValue && listValue.length > 0) {
            // 有列表数据，直接使用
            listData = listValue
          } else {
            // 无数据，创建默认列表
            listData = [{content: '', type}]
          }
          return {hasString, strValue: hasString ? strValue : '', listData}
        }

        const dutyResult = processField(
          dutySituation,
          dutySituationList,
          'duty'
        )
        const handoverResult = processField(
          handoverSituation,
          handoverSituationList,
          'handover'
        )
        const facilityResult = processField(
          facilityStatus,
          facilityStatusList,
          'facility'
        )

        this.addEditForm = {
          ...addEditForm,
          dutySituation: dutyResult.strValue,
          dutySituationList: dutyResult.listData,
          handoverSituation: handoverResult.strValue,
          handoverSituationList: handoverResult.listData,
          facilityStatus: facilityResult.strValue,
          facilityStatusList: facilityResult.listData,
          dateRange: [startTime, endTime],
          startTime,
          endTime,
          roadInfos: roadInfosId
        }
        console.log(this.addEditForm, 'addEditForm')
      } finally {
        this.formLoading = false
      }
    },

    // 打开页面执行
    openPage() {},

    // 关闭页面执行
    closePage() {
      const {addEditRules, pubSub} = this

      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        addEditRules,
        pubSub
      })

      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 保存
    handleSave(type = 'save') {
      // 保存原始的adminComment验证规则
      const originalAdminCommentRule = this.addEditRules.adminComment

      // 根据操作类型动态设置adminComment的验证规则
      if (type === 'audit') {
        // 审核操作：adminComment为必填
        this.addEditRules.adminComment = [
          {required: true, message: '管理员意见', trigger: 'change'}
        ]
      } else {
        // 保存操作：adminComment为非必填
        this.addEditRules.adminComment = []
      }

      this.$refs.addEditForm.validate(async (valid, object) => {
        // 验证完成后恢复原始的验证规则
        this.addEditRules.adminComment = originalAdminCommentRule

        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveConfirm(type)
        }
      })
    },

    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      // 退出编辑页面时解锁
      if (this.id && pageName === 'TablePage') {
        this.handlePageUnload()
      }
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    },
    getDictionaryByCode
  },
  beforeDestroy() {
    // 组件销毁时解锁
    if (this.id) {
      this.handlePageUnload()
    }
    // 移除事件监听
    window.removeEventListener('beforeunload', this.handlePageUnload)
    window.removeEventListener('popstate', this.handlePageUnload)
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep
  .el-descriptions
  .el-descriptions__body
  .el-descriptions-row
  .el-descriptions-item__cell.el-descriptions-item__label {
  width: auto;
  text-align: center;
}
::v-deep
  .el-descriptions
  .el-descriptions__body
  .el-descriptions-row
  .el-descriptions-item__cell.el-descriptions-item__content {
  text-align: center;
}
.required-star {
  color: #f56c6c;
  padding-right: 4px;
}

.edit-add-detail {
  .form-content .el-form {
    display: flex;
    flex-direction: column;
    overflow-y: hidden !important;
  }

  .form-wrapper {
    flex: 1;
    overflow-y: auto;
    width: 1220px;
    margin: 0 auto 10px;
    padding: 0 100px;
    .title {
      margin: 10px 0;
      > div {
        font-size: 24px;
        text-align: center;
      }
    }
  }
}
::v-deep .el-input-number {
  width: 100px;
}
.text-row {
  writing-mode: vertical-rl;
  letter-spacing: 12px;
}
.text-row-color {
  font-size: 15px;
  font-family: PingFang SC-Medium, PingFang SC, serif;
  color: #f0f0f0;
}
.duty-table-wrapper {
  .el-table {
    margin-bottom: 10px;
    /* 降低表头高度 */
    ::v-deep .el-table__header-wrapper {
      .el-table__header {
        th {
          padding: 4px 0 !important;
          height: 32px;
        }
        .cell {
          line-height: 24px;
        }
      }
    }
    /* 降低行高度 */
    ::v-deep .el-table__body-wrapper {
      .el-table__body {
        td {
          padding: 8px 0;
        }
      }
    }
  }
  .table-actions {
    text-align: right;
  }
}
</style>
