<template>
  <super-dialog
    v-model="isShowDialog"
    :modal="false"
    :title="'运行监测调度总中心突发事件记录单导出预览'"
    :top="top"
    :width="width"
    v-bind="$attrs"
    @closed="closed"
    @open="open"
  >
    <div class="rescueInfo-dialog">
      <div
        v-loading="dataLoading"
        element-loading-background="rgba(10 ,38 ,61, 0.9)"
        style="position: relative;"
      >
        <div ref="btnPanel" class="btn-box">
          <el-button
            v-if="BtnAuth('EventReportAudit') &&detailInfo.status !== 1"
            class="btn btn-plus"
            icon="el-icon-s-check"
            size="small"
            type="success"
            @click="showAuditDialog"
            >审核
          </el-button>
          <el-button
            v-if="detailInfo.status !== 1"
            :loading="dataLoading"
            class="btn btn-plus"
            icon="el-icon-refresh"
            size="small"
            type="warning"
            @click="updateData"
            >更新
          </el-button>
          <el-button
            v-if="detailInfo.status !== 1"
            :loading="saveLoading"
            class="btn btn-plus"
            icon="el-icon-circle-check"
            size="small"
            type="primary"
            @click="saveData"
            >保存
          </el-button>
          <el-button
            :loading="downloadLoading"
            class="btn btn-plus"
            icon="el-icon-download"
            size="small"
            type="primary"
            @click="exportData"
            >Excel 导出
          </el-button>
        </div>
        <table style="display: inline-table;">
          <template v-for="(row, index) in tableConfig">
            <!-- 标题行 -->
            <tr v-if="row.type === 'title'" :key="'title-' + index">
              <td class="th-title" :colspan="row.colspan">{{ row.content }}</td>
            </tr>
            <!-- 分组标题 -->
            <tr v-else-if="row.type === 'section'" :key="'section-' + index">
              <td class="th-title" :rowspan="row.rowspan" :width="row.width">
                {{ row.title }}
              </td>
            </tr>
            <!-- 数据行 -->
            <tr v-else-if="row.type === 'row'" :key="'row-' + index">
              <template v-for="(cell, cellIndex) in row.cells">
                <!-- 标签单元格 -->
                <td
                  v-if="cell.type === 'label'"
                  :key="'label-' + cellIndex"
                  class="title"
                  :colspan="cell.colspan"
                  :width="cell.width"
                >
                  {{ cell.content }}
                </td>
                <!-- 字段单元格 -->
                <td
                  v-else-if="cell.type === 'field'"
                  :key="'field-' + cellIndex"
                  :colspan="cell.colspan"
                  @click="isFieldEditable(cell.field) && startEdit(cell.field)"
                  :class="{
                    'field-cell': true,
                    editable: isFieldEditable(cell.field),
                    'textarea-field':
                      getFieldConfig(cell.field).type === 'textarea'
                  }"
                >
                  <template v-if="isEditing(cell.field)">
                    <el-input
                      v-if="getFieldConfig(cell.field).type === 'input'"
                      v-model="detailInfo[cell.field]"
                      :placeholder="getFieldConfig(cell.field).placeholder"
                      @blur="endEdit"
                      @keyup.enter="endEdit"
                      size="small"
                    />
                    <div
                      v-if="getFieldConfig(cell.field).type === 'input-number'"
                      class="input-number-wrapper"
                    >
                      <span
                        v-if="getFieldConfig(cell.field).prevText"
                        class="field-unit"
                        >{{ getFieldConfig(cell.field).prevText }}</span
                      >
                      <el-input-number
                        style="flex: 1;"
                        v-model="detailInfo[cell.field]"
                        :placeholder="getFieldConfig(cell.field).placeholder"
                        @blur="endEdit"
                        @keyup.enter="endEdit"
                        :controls="false"
                        size="small"
                      />
                      <span
                        v-if="getFieldConfig(cell.field).unit"
                        class="field-unit"
                        >{{ getFieldConfig(cell.field).unit }}</span
                      >
                    </div>
                    <el-input
                      v-else-if="getFieldConfig(cell.field).type === 'textarea'"
                      v-model="detailInfo[cell.field]"
                      :placeholder="getFieldConfig(cell.field).placeholder"
                      @blur="endEdit"
                      @keyup.enter="endEdit"
                      size="small"
                      type="textarea"
                      :rows="getFieldConfig(cell.field).rows"
                    />
                  </template>
                  <span
                    v-else
                    :class="{
                      'field-content': true,
                      'textarea-content':
                        getFieldConfig(cell.field).type === 'textarea'
                    }"
                  >
                    <template
                      v-if="getFieldConfig(cell.field).type === 'input-number'"
                    >
                      <!-- 前置文本 -->
                      <span
                        v-if="
                          getFieldConfig(cell.field).prevText &&
                            detailInfo[cell.field] !== null &&
                            detailInfo[cell.field] !== undefined
                        "
                        style="margin-right: 2px; font-size: 14px;"
                        >{{ getFieldConfig(cell.field).prevText }}</span
                      >
                      <!-- 数值显示 -->
                      {{
                        detailInfo[cell.field] !== null &&
                        detailInfo[cell.field] !== undefined
                          ? detailInfo[cell.field]
                          : '/'
                      }}
                      <!-- 单位-->
                      <span
                        v-if="
                          getFieldConfig(cell.field).unit &&
                            detailInfo[cell.field] !== null &&
                            detailInfo[cell.field] !== undefined
                        "
                        style="margin-left: 2px; font-size: 14px;"
                        >{{ getFieldConfig(cell.field).unit }}</span
                      >
                    </template>
                    <!-- 其他类型显示 -->
                    <template v-else>
                      {{
                        getFieldConfig(cell.field).type === 'textarea'
                          ? (detailInfo[cell.field] || '').trim() || '/'
                          : detailInfo[cell.field] || '/'
                      }}
                      <span
                        v-if="
                          getFieldConfig(cell.field).unit &&
                            detailInfo[cell.field]
                        "
                        style="margin-left: 2px; font-size: 14px;"
                        >{{ getFieldConfig(cell.field).unit }}</span
                      >
                    </template>
                  </span>
                </td>
              </template>
            </tr>
          </template>
        </table>
      </div>
    </div>

    <!-- 审核弹窗 -->
    <super-dialog
      v-model="auditDialogVisible"
      title="审核意见"
      width="460px"
      custom-class="audit-dialog"
      :close-on-click-modal="false"
    >
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核意见">
          <el-input
            v-model="auditForm.opinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="auditLoading" @click="submitAudit"
          >提交</el-button
        >
      </template>
    </super-dialog>
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {
  exportDataFileBatch,
  getEventReport,
  saveEventReport,
  updateEventReport,
  auditEventReport
} from '@/api/patrolAndRescue/commandDispatch/eventManagement'
import utils from '@/utils/utils.js'

export default {
  name: 'FileDialog',
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    top: {
      default: '5vh',
      type: String
    },
    width: {
      default: '78%',
      type: String
    },
    height: {
      default: '80vh',
      type: String
    },
    fileInfo: {
      default() {
        return {}
      },
      type: Object
    }
  },
  components: {
    SuperDialog
  },
  data() {
    return {
      detailInfo: {},
      downloadLoading: false,
      dataLoading: false,
      saveLoading: false,
      updateLoading: false,
      editingField: null, // 当前编辑的字段
      auditDialogVisible: false,
      auditLoading: false,
      auditForm: {
        opinion: ''
      },
      fieldConfig: {
        roadName: {
          type: 'input',
          placeholder: '请输入路段名称',
          editable: true
        },
        recorder: {type: 'input', placeholder: '请输入记录人', editable: true},
        receiveTime: {
          type: 'input',
          placeholder: '请输入接警时间',
          editable: true
        },
        eventSrcText: {
          type: 'input',
          placeholder: '请输入信息来源',
          editable: true
        },
        eventTime: {
          type: 'input',
          placeholder: '请输入事件发生时间',
          editable: true
        },
        pegSVal: {
          type: 'input',
          placeholder: '请输入事件发生点',
          editable: true
        },
        lwEventType: {
          type: 'input',
          placeholder: '请输入事件类型',
          editable: true
        },
        deadUserNum: {
          type: 'input-number',
          placeholder: '请输入',
          unit: '(人)',
          editable: true
        },
        hurtUserNum: {
          type: 'input-number',
          placeholder: '请输入',
          unit: '(人)',
          editable: true
        },
        holdupUserNum: {
          type: 'input-number',
          placeholder: '请输入',
          unit: '(人)',
          editable: true
        },
        brokenCarNum: {
          type: 'input-number',
          placeholder: '请输入车辆损坏数量',
          prevText: '损坏车辆',
          unit: '(辆)',
          editable: true
        },
        roadLoss: {
          type: 'input-number',
          placeholder: '请输入路产损失金额',
          unit: '(元)',
          editable: true
        },
        roadTrafficConditions: {
          type: 'textarea',
          placeholder: '请输入道路通行状况',
          rows: 6,
          editable: true
        },
        memo: {
          type: 'textarea',
          placeholder: '请输入其他情况',
          rows: 6,
          editable: true
        },
        noticeInspectTime: {
          type: 'input',
          placeholder: '请输入通知巡查时间',
          editable: true
        },
        arriveInspectTime: {
          type: 'input',
          placeholder: '请输入巡查到达时间',
          editable: true
        },
        leaveInspectTime: {
          type: 'input',
          placeholder: '请输入巡查离场时间',
          editable: true
        },
        noticePoliceTime: {
          type: 'input',
          placeholder: '请输入通知交警时间',
          editable: true
        },
        arrivePoliceTime: {
          type: 'input',
          placeholder: '请输入交警到达时间',
          editable: true
        },
        leavePoliceTime: {
          type: 'input',
          placeholder: '请输入交警离场时间',
          editable: true
        },
        noticeEnforceTime: {
          type: 'input',
          placeholder: '请输入通知交通执法时间',
          editable: true
        },
        arriveEnforceTime: {
          type: 'input',
          placeholder: '请输入交通执法到达时间',
          editable: true
        },
        leaveEnforceTime: {
          type: 'input',
          placeholder: '请输入交通执法离场时间',
          editable: true
        },
        noticeRescueTime: {
          type: 'input',
          placeholder: '请输入通知救援时间',
          editable: true
        },
        arriveRescueTime: {
          type: 'input',
          placeholder: '请输入救援到达时间',
          editable: true
        },
        leaveRescueTime: {
          type: 'input',
          placeholder: '请输入救援离场时间',
          editable: true
        },
        noticeOtherTime: {
          type: 'input',
          placeholder: '请输入其他外协通知时间',
          editable: true
        },
        arriveOtherTime: {
          type: 'input',
          placeholder: '请输入其他外协到达时间',
          editable: true
        },
        leaveOtherTime: {
          type: 'input',
          placeholder: '请输入其他外协离场时间',
          editable: true
        },
        otherRemark: {
          type: 'textarea',
          placeholder: '请输入其他信息',
          rows: 2,
          editable: true
        },
        controlMeasures: {
          type: 'textarea',
          placeholder: '请输入控制措施',
          rows: 12,
          editable: true
        },
        eventLevelText: {
          type: 'input',
          placeholder: '请输入事件等级',
          editable: true
        },
        checkTime: {
          type: 'input',
          placeholder: '请输入审核时间',
          editable: false
        },
        checkUserName: {
          type: 'input',
          placeholder: '请输入审核人',
          editable: false
        },
        opinion: {
          type: 'textarea',
          placeholder: '请输入审核意见',
          rows: 2,
          editable: false
        }
      },
      tableConfig: [
        {
          type: 'title',
          content: '运行监测调度总中心突发事件记录单',
          colspan: 8
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '路段', width: '14%'},
            {type: 'field', field: 'roadName', colspan: 3},
            {type: 'label', content: '记录人', width: '14%'},
            {type: 'field', field: 'recorder', colspan: 3}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '接警时间'},
            {type: 'field', field: 'receiveTime', colspan: 3},
            {type: 'label', content: '信息来源'},
            {type: 'field', field: 'eventSrcText', colspan: 3}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '事件发生时间'},
            {type: 'field', field: 'eventTime', colspan: 3},
            {type: 'label', content: '事件发生点'},
            {type: 'field', field: 'pegSVal', colspan: 3}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '事件类型'},
            {type: 'field', field: 'lwEventType', colspan: 7}
          ]
        },
        {type: 'section', title: '事件情况', rowspan: 6, width: '14%'},
        {
          type: 'row',
          cells: [
            {type: 'label', content: '人员伤亡情况', colspan: 1},
            {type: 'label', content: '滞留', colspan: 1},
            {type: 'field', field: 'holdupUserNum'},
            {type: 'label', content: '受伤', colspan: 1},
            {type: 'field', field: 'hurtUserNum'},
            {type: 'label', content: '死亡', colspan: 1},
            {type: 'field', field: 'deadUserNum'}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '车辆损坏情况', colspan: 1},
            {type: 'field', field: 'brokenCarNum', colspan: 6}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '路产损失情况', colspan: 1},
            {type: 'field', field: 'roadLoss', colspan: 6}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '道路通行状况', colspan: 1},
            {type: 'field', field: 'roadTrafficConditions', colspan: 6}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '其他', colspan: 1},
            {type: 'field', field: 'memo', colspan: 6}
          ]
        },
        {type: 'section', title: '中心处理情况', rowspan: 7, width: '14%'},
        {
          type: 'row',
          cells: [
            {type: 'label', content: '通知巡查时间', colspan: 1},
            {type: 'field', field: 'noticeInspectTime', colspan: 2},
            {type: 'label', content: '到达时间', colspan: 1},
            {type: 'field', field: 'arriveInspectTime', colspan: 1},
            {type: 'label', content: '离场时间', colspan: 1},
            {type: 'field', field: 'leaveInspectTime', colspan: 1}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '通知交警时间', colspan: 1},
            {type: 'field', field: 'noticePoliceTime', colspan: 2},
            {type: 'label', content: '到达时间', colspan: 1},
            {type: 'field', field: 'arrivePoliceTime', colspan: 1},
            {type: 'label', content: '离场时间', colspan: 1},
            {type: 'field', field: 'leavePoliceTime', colspan: 1}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '通知交通执法时间', colspan: 1},
            {type: 'field', field: 'noticeEnforceTime', colspan: 2},
            {type: 'label', content: '到达时间', colspan: 1},
            {type: 'field', field: 'arriveEnforceTime', colspan: 1},
            {type: 'label', content: '离场时间', colspan: 1},
            {type: 'field', field: 'leaveEnforceTime', colspan: 1}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '通知救援时间', colspan: 1},
            {type: 'field', field: 'noticeRescueTime', colspan: 2},
            {type: 'label', content: '到达时间', colspan: 1},
            {type: 'field', field: 'arriveRescueTime', colspan: 1},
            {type: 'label', content: '离场时间', colspan: 1},
            {type: 'field', field: 'leaveRescueTime', colspan: 1}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '通知其他外协时间', colspan: 1},
            {type: 'field', field: 'noticeOtherTime', colspan: 2},
            {type: 'label', content: '到达时间', colspan: 1},
            {type: 'field', field: 'arriveOtherTime', colspan: 1},
            {type: 'label', content: '离场时间', colspan: 1},
            {type: 'field', field: 'leaveOtherTime', colspan: 1}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '其他', colspan: 1},
            {type: 'field', field: 'otherRemark', colspan: 6}
          ]
        },
        {
          type: 'row',
          cells: [
            {
              type: 'label',
              content:
                '事件发生后组织抢救、采取的安全措施、事发地点的控制情况等简要经过'
            },
            {type: 'field', field: 'controlMeasures', colspan: 7}
          ]
        },
        {type: 'section', title: '审核', rowspan: 3},
        {
          type: 'row',
          cells: [
            {type: 'label', content: '事件等级'},
            {type: 'field', field: 'eventLevelText', colspan: 2},
            {type: 'label', content: '审核时间'},
            {type: 'field', field: 'checkTime'},
            {type: 'label', content: '审核人'},
            {type: 'field', field: 'checkUserName'}
          ]
        },
        {
          type: 'row',
          cells: [
            {type: 'label', content: '审核意见', colspan: 1},
            {type: 'field', field: 'opinion', colspan: 6}
          ]
        }
      ]
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  methods: {
        BtnAuth(btnCode) {
      return utils.BtnAuth(btnCode)
    },
    dictionaryEscape,
    getDictionaryByCode,
    async exportData() {
      this.downloadLoading = true
      try {
        const param = 'ids=' + this.fileInfo.id
        await exportDataFileBatch(param)
        this.$message.success(`数据导出成功`)
      } catch {
        this.$message.error(`数据导出失败`)
      } finally {
        this.downloadLoading = false
      }
    },
    // 打开弹层时触发
    open() {
      this.getDetailData()
    },
    // 关闭弹层触发
    closed() {
      this.detailInfo = {}
    },
    // 开始编辑
    startEdit(field) {
      this.editingField = field
      this.$nextTick(() => {
        const input = this.$el.querySelector(`input, textarea`)
        if (input) {
          input.focus()
        }
      })
    },
    // 结束编辑
    endEdit() {
      // 对textarea类型字段去除首尾空格
      if (
        this.editingField &&
        this.getFieldConfig(this.editingField).type === 'textarea'
      ) {
        this.detailInfo[this.editingField] = this.detailInfo[
          this.editingField
        ]?.trim()
      }
      this.editingField = null
    },
    // 判断是否正在编辑
    isEditing(field) {
      return this.editingField === field
    },
    // 获取字段配置
    getFieldConfig(field) {
      return this.fieldConfig[field] || {}
    },
    // 判断字段是否可编辑
    isFieldEditable(field) {
      return this.fieldConfig[field]?.editable || false
    },

    // 更新数据
    async updateData() {
      try {
        await this.$confirm('更新操作会覆盖当前数据，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.dataLoading = true
        const {state, value, message} = await updateEventReport(
          this.fileInfo.id
        )
        if (state) {
          this.detailInfo = value
          this.$message.success('更新成功')
        } else {
          this.$message.success(message || '更新成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('更新失败')
        }
      } finally {
        this.dataLoading = false
      }
    },
    // 获取详情
    async getDetailData() {
      this.dataLoading = true
      try {
        this.detailInfo = await getEventReport(this.fileInfo.id)
      } finally {
        this.dataLoading = false
      }
    },
    async saveData() {
      try {
        this.saveLoading = true
        const {state, message} = await saveEventReport(this.detailInfo)
        if (state) {
          this.$message.success(`保存成功`)
          this.getDetailData()
        } else {
          this.$message.error(message || '保存失败')
        }
      } catch (error) {
        console.log(error)
        this.$message.error(error.message || '保存失败')
      } finally {
        this.saveLoading = false
      }
    },
    // 显示审核弹窗
    showAuditDialog() {
      this.auditForm.opinion = ''
      this.auditDialogVisible = true
    },
    // 提交审核
    async submitAudit() {
      if (!this.auditForm.opinion.trim()) {
        this.$message.warning('请输入审核意见')
        return
      }
      try {
        this.auditLoading = true
        const {state, message} = await auditEventReport({
          id: this.fileInfo.id,
          opinion: this.auditForm.opinion
        })
        if (state) {
          this.$message.success('审核成功')
          this.auditDialogVisible = false
          this.getDetailData()
        } else {
          this.$message.error(message || '审核失败')
        }
      } finally {
        this.auditLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';
::v-deep .el-dialog__body {
  overflow: hidden;
}
::v-deep .super-dialog-content {
  height: 80vh;
}

// 审核弹窗样式覆盖
::v-deep .audit-dialog .super-dialog-content {
  height: 200px !important;
}
.rescueInfo-dialog {
  overflow: auto;
  padding: 20px;
  box-sizing: border-box;
  height: 100%;
}
.btn-box {
  margin-bottom: 15px;
  text-align: right;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.el-input,
.el-textarea {
  width: 100% !important;
}

.el-input__inner,
.el-textarea__inner {
  width: 100% !important;
  box-sizing: border-box;
}

.th-title {
  color: #f0f0f0;
  font-size: 16px;
  font-weight: bold;
}

.title {
  color: #f0f0f0;
  font-size: 14px;
  font-weight: bold;
}

th,
td {
  border: 1px solid rgba(67, 161, 255, 0.5);
  padding: 12px 15px;
  text-align: center;
  background-color: #103b5e;
  color: #c3cad0;
  font-size: 14px;
}

.field-cell {
  &.editable {
    cursor: pointer;
  }

  &.textarea-field {
    text-align: left;
  }
}

.input-number-wrapper {
  display: flex;
  align-items: center;

  .el-input-number {
    flex: 1;
  }
}

.field-unit {
  margin: 0 5px;
  font-size: 14px;
  color: #c3cad0;
}

.field-content {
  font-size: 14px;

  &.textarea-content {
    white-space: pre-line;
    margin-bottom: 4px;
    margin-top: -12px;
    display: inline-block;
  }
}
</style>
