<template>
  <div class="edit-add-detail detail">
    <div class="edit-add-detail-new-content">
      <div class="form-content" style="flex: 4">
        <el-form
          ref="formInfo"
          :model="detailForm"
          :rules="addEditRules"
          class="detail-form"
          label-position="right"
          label-suffix="："
        >
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">救援登记信息</div>
              <div class="actions">
                <el-link
                  v-if="pageType === 'edit'"
                  :underline="false"
                  icon="el-icon-edit"
                  type="primary"
                  @click="clickEdit"
                >编辑
                </el-link>
                <template v-else>
                  <el-link
                    :underline="false"
                    icon="el-icon-document-checked"
                    type="primary"
                    @click="clickSave"
                  >保存
                  </el-link>
                  <el-link
                    :underline="false"
                    icon="el-icon-close"
                    type="info"
                    @click="clickCancal"
                  >取消
                  </el-link>
                </template>
              </div>
            </div>
          </div>
          <div v-if="pageType === 'edit'">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="救援单号">
                <span :title="detailForm.rescueNo" class="text">
                  {{ detailForm.rescueNo || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报案电话">
                <span :title="detailForm.rescueTel" class="text">
                  {{ detailForm.rescueTel || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报案时间">
                <span :title="detailForm.rescueTime" class="text">
                  {{ detailForm.rescueTime || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="救援类型">
                <span :title="detailForm.rescueType" class="text">
                  {{
                    dictionaryEscape('jylx', detailForm.rescueType + '') || '-'
                  }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属路段">
                <span :title="detailForm.roadName" class="text">
                  {{ detailForm.roadName || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开始站">
                <span :title="detailForm.startPatrolId" class="text">
                  {{ detailForm.startPatrolName || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束站">
                <span :title="detailForm.endPatrolId" class="text">
                  {{ detailForm.endPatrolName || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="行驶方向">
                <span :title="detailForm.direction" class="text">
                  {{
                    dictionaryEscape('xsfx', detailForm.direction + '') || '-'
                  }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="救援点位桩号全值">
                <span :title="detailForm.pegVal" class="text">
                  {{ detailForm.pegVal || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报案来源">
                <span :title="detailForm.rescueSrc" class="text">
                  {{
                    dictionaryEscape('baly', detailForm.rescueSrc + '') || '-'
                  }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="事发天气">
                <span :title="detailForm.weather" class="text">
                  {{ detailForm.weather || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="故障车牌">
                <span :title="detailForm.carCode" class="text">
                  {{ detailForm.carCode || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="故障车类">
                <span :title="detailForm.carClass" class="text">
                  {{
                    dictionaryEscape('gzcl', detailForm.carClass + '') || '-'
                  }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="故障车型">
                <span :title="detailForm.carType" class="text">
                  {{ dictionaryEscape('gzcx', detailForm.carType + '') || '-' }}
                </span>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="车载重量（吨）">
                <span :title="detailForm.carWeight" class="text">
                  {{ detailForm.carWeight ? detailForm.carWeight + '吨' : '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="车主姓名">
                <span :title="detailForm.carUser" class="text">
                  {{ detailForm.carUser || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="车主电话">
                <span :title="detailForm.carUserTel" class="text">
                  {{ detailForm.carUserTel || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="派遣队伍">
                <span :title="detailForm.teamName" class="text">
                  {{ detailForm.teamName || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="登记人">
                <span :title="detailForm.createName" class="text">
                  {{ detailForm.createName || '-' }}
                </span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="占道情况">
                  <!-- <div v-for="(item,index) in detailForm.occupy" :key="index" :title="item" class="text">
                    {{ dictionaryEscape('zdqk', item + '') || '-' }}；
                  </div> -->
                  <el-tag
                    v-for="(item, index) in detailForm.occupy"
                    :key="index"
                    :type="item < 1 ? 'success' : 'danger'"
                    style="margin-right: 5px"
                  >
                    {{ dictionaryEscape('zdqk', item + '') || '-' }}
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="pageType !== 'edit'">
            <div
              v-loading="saveLoading"
              element-loading-background="rgba(17, 64, 102, 0.95)"
              element-loading-spinner="el-icon-loading"
              element-loading-text="数据保存修改中..."
            >
              <el-row
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="报案电话" prop="rescueTel">
                    <el-input
                      v-model="detailForm.rescueTel"
                      clearable
                      placeholder="报案电话"
                      type="number"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="报案时间" prop="rescueTime">
                    <el-date-picker
                      v-model="detailForm.rescueTime"
                      default-time="12:00:00"
                      placeholder="选择日期时间"
                      style="width: 100%"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="救援类型" prop="rescueType">
                    <el-radio-group v-model="detailForm.rescueType" size="medium">
                      <el-radio
                        v-for="(item, index) in getDictionaryByCode('jylx')"
                        :key="index"
                        :label="Number(item.value)"
                        :value="Number(item.value)"
                        border
                      >{{ item.name }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="所属路段" prop="roadId">
                    <el-select
                      v-model="detailForm.roadId"
                      filterable
                      placeholder="请选择所属路段"
                      style="width: 100%"
                      @change="roadChange"
                    >
                      <el-option
                        v-for="item in roadOptions"
                        :key="item.id"
                        :label="item.roadName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="开始站" prop="startPatrolId">
                    <el-select
                      v-model="detailForm.startPatrolId"
                      filterable
                      placeholder="请选择开始站"
                      style="width: 100%"
                      @change="siteChange($event, 'startPatrol')"
                    >
                      <el-option
                        v-for="item in alongRouteInfoData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="结束站" prop="endPatrolId">
                    <el-select
                      v-model="detailForm.endPatrolId"
                      filterable
                      placeholder="请选择结束站"
                      style="width: 100%"
                      @change="siteChange($event, 'endPatrol')"
                    >
                      <el-option
                        v-for="item in alongRouteInfoData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="路段桩号范围">
                    <span style="
                      margin-right: 20px;
                      color: #fff;
                      font-size: 14px;
                      font-weight: 100;
                    ">{{ pileNumberRange }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item class="stake-mark" label="救援点位桩号全值" prop="startPeg">
                    <div class="pegVal-text1">K</div>
                    <el-input
                      v-model="detailForm.startPeg"
                      oninput="value=value.replace(/[^0-9]/g,'')"
                      type="number"
                    ></el-input>
                    <div class="pegVal-text2">+</div>
                    <el-input
                      v-model="detailForm.startPegAdd"
                      oninput="value=value.replace(/[^0-9]/g,'')"
                      type="number"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="24">
                  <el-form-item label="行驶方向" prop="direction">
                    <el-radio-group v-model="detailForm.direction" size="medium">
                      <el-radio
                        v-for="(item, index) in getDictionaryByCode('xsfx')"
                        :key="index"
                        :label="item.value"
                        :value="item.value"
                        border
                      >{{ item.name }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="报案来源" prop="rescueSrc">
                    <el-select
                      v-model="detailForm.rescueSrc"
                      clearable
                      placeholder="报案来源"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in getDictionaryByCode('baly')"
                        :key="index"
                        :label="item.name"
                        :value="Number(item.value)"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="事发天气" prop="weather">
                    <!--                    <el-input-->
                    <!--                      v-model="detailForm.weather"-->
                    <!--                      clearable-->
                    <!--                      placeholder="事发天气"-->
                    <!--                    ></el-input>-->
                    <el-select
                      v-model="detailForm.weather"
                      allow-create
                      clearable
                      default-first-option
                      filterable
                      placeholder="事发天气"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(item, index) in getDictionaryByCode('tq')"
                        :key="index"
                        :label="item.name"
                        :value="item.name"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="故障车牌" prop="carCode">
                    <el-input
                      v-model="detailForm.carCode"
                      clearable
                      placeholder="故障车牌"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="24">
                  <el-form-item label="占道情况" prop="occupy">
                    <el-checkbox-group v-model="detailForm.occupy" size="medium">
                      <el-checkbox
                        v-for="(item, index) in getDictionaryByCode('zdqk')"
                        :key="index"
                        :disabled="item.value > '0' && checkDisabled()"
                        :label="item.value"
                        :value="item.value"
                        @change="checkChange"
                      >{{ item.name }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="24">
                  <el-form-item label="故障车类" prop="carClass">
                    <el-radio-group
                      v-model="detailForm.carClass"
                      size="medium"
                      @change="clearCarType"
                    >
                      <el-radio
                        v-for="(item, index) in getDictionaryByCode('gzcl')"
                        :key="index"
                        :label="Number(item.value)"
                        :value="Number(item.value)"
                        border
                      >{{ item.name }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="24">
                  <el-form-item label="故障车型" prop="carType">
                    <el-radio-group v-model="detailForm.carType" size="medium">
                      <el-radio
                        v-for="(item, index) in getCarClassify(
                      detailForm.carClass
                    )"
                        :key="index"
                        :label="Number(item.value)"
                        :value="Number(item.value)"
                      >{{ item.name }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="车载重量（吨）" prop="carWeight">
                    <el-input
                      v-model="detailForm.carWeight"
                      class="number-input"
                      placeholder="请输入内容"
                      type="number"
                    >
                      <template slot="append">吨</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车主姓名" prop="carUser">
                    <el-input
                      v-model="detailForm.carUser"
                      clearable
                      placeholder="车主姓名"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车主电话" prop="carUserTel">
                    <el-input
                      v-model="detailForm.carUserTel"
                      clearable
                      placeholder="车主电话"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <template v-if="detailForm.rescueStatus > 0">
            <div class="rows">
              <div class="rows-left">
                <div class="rows-hr"></div>
              </div>
              <div class="rows-title">
                <div class="text-overflow">救援派遣人员信息</div>
              </div>
            </div>
            <template
              v-if="detailForm.dispatches && detailForm.dispatches.length > 0"
            >
              <el-row
                v-for="item in detailForm.dispatches"
                :key="item.id"
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="派遣人员">
                    <span :title="item.dispatchUserName" class="text">
                      {{ item.dispatchUserName || '-' }}
                    </span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="派遣人员电话">
                    <span :title="item.dispatchUserTel" class="text">
                      {{ item.dispatchUserTel || '-' }}
                    </span>
                  </el-form-item>
                </el-col
                >
                <el-col :span="8">
                  <el-form-item label="派遣时间">
                    <span :title="item.dispatchTime" class="text">
                      {{ item.dispatchTime || '-' }}
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else>
              <div style="text-align: center; color: #c0c4cc; padding: 10px 0">
                暂无救援派遣人员信息...
              </div>
            </template>
            <div class="rows">
              <div class="rows-left">
                <div class="rows-hr"></div>
              </div>
              <div class="rows-title">
                <div class="text-overflow">救援派遣车辆信息</div>
              </div>
            </div>
            <template
              v-if="detailForm.car"
            >
              <el-row
                :gutter="24"
              >
                <el-col :span="8">
                  <el-form-item label="派遣车辆">
                    <span :title="detailForm.car.dispatchCarCode" class="text">
                      {{ detailForm.car.dispatchCarCode || '-' }}
                    </span>
                  </el-form-item>
                </el-col
                >
                <el-col :span="8">
                  <el-form-item label="派遣车辆类型">
                    <span :title="detailForm.car.dispatchCarType" class="text">
                      {{
                        dictionaryEscape(
                          'jycl-cllx',
                          detailForm.car.dispatchCarType + ''
                        ) || '-'
                      }}
                    </span>
                  </el-form-item>
                </el-col
                >
                <el-col :span="8">
                  <el-form-item label="派遣时间">
                    <span :title="detailForm.car.dispatchTime" class="text">
                      {{ detailForm.car.dispatchTime || '-' }}
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-else>
              <div style="text-align: center; color: #c0c4cc; padding: 10px 0">
                暂无救援派遣车辆信息...
              </div>
            </template>

            <template>
              <div class="rows">
                <div class="rows-left">
                  <div class="rows-hr"></div>
                </div>
                <div class="rows-title">
                  <div class="text-overflow">救援费用信息</div>
                </div>
              </div>
              <el-table :data="detailForm.costs" style="width: 100%">
                <el-table-column
                  align="center"
                  label="序号"
                  type="index"
                  width="70"
                />
                <el-table-column
                  align="center"
                  label="发票单号"
                  prop="invoiceNo"
                  width="180"
                ></el-table-column>
                <el-table-column
                  align="center"
                  label="应收金额"
                  prop="shouldMoney"
                  width="80"
                ></el-table-column>
                <el-table-column
                  align="center"
                  label="实收金额"
                  prop="actualMoney"
                  width="80"
                ></el-table-column>
                <el-table-column
                  align="center"
                  label="收费类型"
                  prop="costType"
                  width="100"
                >
                  <template v-slot="{row}">
                    {{ dictionaryEscape('sflx', row.costType + '') || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="支付方式"
                  prop="payType"
                  width="100"
                >
                  <template v-slot="{row}">
                    {{ dictionaryEscape('zffs', row.payType + '') || '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="支付时间"
                  min-width="180"
                  prop="costTime"
                ></el-table-column>
              </el-table>
            </template>
          </template>
        </el-form>
      </div>
      <div class="form-content" style="flex: 3">
        <el-form
          ref="formInfos"
          :model="detailForm"
          class="detail-form"
          label-position="right"
          label-suffix="："
        >
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">处置流程记录</div>
            </div>
          </div>
          <el-timeline class="flow-box">
            <el-timeline-item
              v-for="item in detailForm.handles"
              :key="item.id"
              :timestamp="item.createTime"
              placement="top"
            >
              <el-card>
                <el-button 
                  round 
                  class="btn-opinion" 
                  v-if="BtnAuth('reviewComments') && item.status === 1" 
                  size="mini" type="warning" 
                  icon="el-icon-edit" 
                  @click="handleComment(item)">
                  复核意见
                </el-button>
                <div class="header">
                  <div class="title">
                    事件处置耗时：{{ formatMinite(item.timeConsuming) }}
                  </div>
                  <div class="title ">
                    事件处置状态：
                    <span :class="`status status-${item.status}`">
                      {{ dictionaryEscape('sjczzt', String(item.status)) || '-'}}
                    </span>
                  </div>
                </div>
                <div class="header">
                  <div class="title">
                    事件处置环节：{{
                      dictionaryEscape('jy_czlc', item.rescueNode + '') || '-'
                    }}
                  </div>
                  <div class="title">事件处置人：{{ item.handleUserName }}</div>
                </div>
                <div class="header">
                  <div class="title">
                    事件处置人所属队伍：{{ item.handleTeamName }}
                  </div>
                  <div class="title">事件处置时间：{{ item.handleTime }}</div>
                </div>
                <div class="event-detail">
                  事件处置情况：{{ item.handleInfo }}
                </div>
                <div class="event-detail" v-if="item.status === 1">
                  复核意见：{{ item.opinion || '-'  }}
                </div>
                <div class="dispose-img">
                  <el-image
                    v-for="file in item.files"
                    :key="file.id"
                    :preview-src-list="getFilePreviewUrlList(item.files)"
                    :src="file.filePreviewUrl"
                    style="width: 100px; height: 100px"
                  >
                  </el-image>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-form>
        <el-button
          v-if="detailForm.rescueStatus === 1 || detailForm.rescueStatus === 2
          || detailForm.rescueStatus === 4"
          :disabled="disableShow"
          circle
          class="add-btn-fixed"
          icon="el-icon-plus"
          title="添加处置环节"
          type="warning"
          @click="handleAddDisposal"
        ></el-button>
        <super-dialog
          v-model="commentDialog"
          title="复核意见"
          width="400"
          top="30vh"
        >
          <el-form
            ref="commentForm"
            :model="commentForm"
            label-position="left"
            label-width="100px"
          >
            <el-form-item label="复核意见">
              <el-input type="textarea" rows="6" v-model="commentForm.opinion" />
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="saveComment">确定</el-button>
            <el-button @click="commentDialog = false">取消</el-button>
          </span>
        </super-dialog>
      </div>
    </div>
    <disposalProcess
      :eventInfo="detailForm"
      :is-show.sync="disposalProcess"
      @updataHandles="handleUpdataHandles"
    >
    </disposalProcess>
  </div>
</template>

<script>
import {refineRequestBody} from '@/utils/requestWrappers'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {tableDetail, tableEdit, updateRescueStep} from '@/api/patrolAndRescue/obstacleClearingRescue/rescueRegistration'
import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {tableData as alongRouteInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'
import PubSub from 'pubsub-js'
import moment from 'moment'
import disposalProcess from './components/disposalProcess.vue'
import SuperDialog from '@/components/SuperDialog/index.vue'
import utils from '@/utils/utils.js'
export default {
  name: 'DetailPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  components: {disposalProcess,SuperDialog},
  data() {
    // 自定义验证规则：有值时必须在范围内
    const validateRange1 = () => {
      return (rule, value, callback) => {
        if (this.detailForm.startPeg === undefined || this.detailForm.startPegAdd === undefined) {
          callback(new Error('请输入救援点位桩号全值'))
        } else if (!this.isValueInRange(this.combinedValue1, this.startValue, this.endValue)) {
          this.detailForm.startPeg = undefined
          this.detailForm.startPegAdd = undefined
          callback(new Error(`所填写的桩号不在${this.startValue}-${this.endValue}范围内`))
        } else {
          callback()
        }
      }
    }
    return {
      pileNumberRange: '',
      startValue: 0,
      endValue: 0,
      saveLoading: false,
      detailForm: {
        startPeg: undefined,
        startPegAdd: undefined
      },
      detailFormBack: {},
      pubSub: null,
      pageType: 'edit',
      roadOptions: [],
      alongRouteInfoData: [],
      addEditRules: {
        rescueTel: [
          {
            required: true,
            message: '报案电话不能为空',
            trigger: ['change', 'blur']
          }
        ],
        rescueTime: [
          {
            required: true,
            message: '报案时间不能为空',
            trigger: ['change', 'blur']
          }
        ],
        eventType: [
          {
            required: true,
            message: '请选择事件类型',
            trigger: ['change']
          }
        ],
        rescueType: [
          {
            required: true,
            message: '救援类型不能为空',
            trigger: ['change']
          }
        ],
        roadId: [
          {
            required: true,
            message: '路段信息不能为空',
            trigger: ['change']
          }
        ],
        eventTime: [
          {
            required: true,
            message: '事件发生时间不能为空',
            trigger: ['change']
          }
        ],
        startPeg: [
          {required: true, validator: validateRange1(), trigger: 'blur'}
        ],
        carUser: [
          {
            required: true,
            message: '车主姓名不能为空',
            trigger: ['change', 'blur']
          }
        ],
        carUserTel: [
          {
            required: true,
            message: '车主电话不能为空',
            trigger: ['change', 'blur']
          }
        ]
      },
      disableShow: true,
      disposalProcess: false,
      commentDialog: false,
      commentForm: {
        opinion: ''
      },
      commentloading: false,
      id: ''
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  mounted() {
    this.pubSub = PubSub.subscribe('DetailPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
  },
  computed: {
    combinedValue1() {
      return parseFloat(`${this.detailForm.startPeg}.${String(this.detailForm.startPegAdd).padStart(3, '0')}`) || 0
    }
  },
  methods: {
    async saveComment(){
      if(!this.commentForm.opinion){
        this.$message.warning('请输入复核意见')
        return
      }
      try{
        this.commentloading = true
        const {state, message} = await updateRescueStep(this.commentForm)
        // 此处调用保存接口
        if(state){
          this.$message.success('保存成功')
          this.commentDialog = false  
          this.getDetail(this.id)
        }else{
          this.$message.error(message || '保存失败')
        }
      }catch(err){
        this.$message.error(err.message || '保存失败')
      }finally{
        this.commentloading = false
      }
    },
    handleComment(item){
      console.log(item)
      this.commentForm = item
      this.commentDialog = true
    },
    BtnAuth(btnCode) {
      return utils.BtnAuth(btnCode)
    },
    formatMinite(minite) {
      if (minite === undefined  || minite === null) return '-'
      if(minite === 0){
        return '小于1分钟'
      } else if (minite < 60) {
        return minite + '分钟'
      } else {
        let hours = Math.floor(minite / 60)
        let minutes = minite % 60
        return hours + '小时' + (minutes > 0 ? minutes + '分钟' : '')
      }
    },
    dictionaryEscape,
    getDictionaryByCode,
    parseString() {
      if (this.pileNumberRange) {
        const match = this.pileNumberRange.match(/^[kK](\d+)(?:\+(\d{1,3}))?~[kK](\d+)(?:\+(\d{1,3}))?$/)
        this.startValue = parseFloat(`${match[1]}.${String(match[2]).padStart(3, '0')}`) || 0
        this.endValue = parseFloat(`${match[3]}.${String(match[4]).padStart(3, '0')}`) || 0
      } else {
        this.startValue = 0
      }
    },
    isValueInRange(value, bound1, bound2) {
      if (typeof value !== 'number' || isNaN(value)) return false
      if (!String(value).includes('.')) return true
      const [min, max] = [Math.min(bound1, bound2), Math.max(bound1, bound2)]
      return value >= min && value <= max
    },
    // 通过路段信息获取沿线设备信息
    async getAlongRouteInfo(value, callback) {
      const _wipeData = () => {
        this.alongRouteInfoData = []
        callback && callback(this.alongRouteInfoData)
      }

      try {
        // 获取沿线设施
        const {rows = []} = await alongRouteInfoInter(
          refineRequestBody({
            querys: [{operation: 'IN', property: 'road_segment_id_', value}]
          }),
          'addEdit'
        )

        callback && callback(rows)
        this.alongRouteInfoData = rows
      } catch (error) {
        // 不为请求过快结束的情况下，重置
        if (error.message !== 'canceled') _wipeData()
      }
    },
    clearCarType() {
      this.$set(this.detailForm, 'carType', '')
    },
    getCarClassify(value) {
      const dict_arr = getDictionaryByCode('gzcl')
      const dict = dict_arr.filter((item) => item.value == value)
      return dict.length ? dict[0]?.lowerDic?.['gzcx'] : []
    },
    // 占到情况禁用
    checkDisabled() {
      return this.detailForm.occupy.includes('0')
    },
    checkChange() {
      if (this.detailForm.occupy.includes('0')) {
        this.detailForm.occupy = ['0']
      }
      this.$forceUpdate()
    },
    clickEdit() {
      this.pageType = this.pageType === 'edit' ? 'detail' : 'edit'
      this.detailFormBack = JSON.parse(JSON.stringify(this.detailForm))
      this.getRoadData()
    },
    clickCancal() {
      this.pageType = 'edit'
      this.detailForm = this.detailFormBack
    },
    async clickSave() {
      this.$refs.formInfo.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          let data = JSON.parse(JSON.stringify(this.detailForm))
          if (typeof data.occupy !== 'string') {
            data.occupy = data.occupy.join(',')
          }
          if (data.startPeg && data.startPegAdd) {
            data.pegVal =
              'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          }
          data.rescueTime = moment(data.rescueTime).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          let roadInfo = this.roadOptions.find(
            (item) => item.id === data.roadId
          )
          data.roadName = roadInfo.name
          data.roadCode = roadInfo.code
          try {
            let {state} = await tableEdit({...data})
            if (state) {
              this.$message.success(`编辑保存成功`)
              this.pageType = 'edit'
              this.detailForm = {...this.detailForm, ...data}
              this.detailForm.occupy = this.detailForm.occupy.split(',')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },
    siteChange(e, type) {
      let siteInfo = this.alongRouteInfoData.find((item) => item.id === e)
      this.detailForm[`${type}Name`] = siteInfo.name
    },
    //获取所在路段列表数据
    async getRoadData() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map((item) => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      this.roadChange(this.detailForm.roadId, true)
    },
    roadChange(value, show = false) {
      let roadInfo = this.roadOptions.find((item) => item.id === value)
      if (roadInfo.startPegK && roadInfo.endPegK) {
        this.pileNumberRange = roadInfo.startPegK + '~' + roadInfo.endPegK
      } else {
        this.pileNumberRange = ''
      }
      if (!show) {
        this.detailForm.startPeg = undefined
        this.detailForm.startPegAdd = undefined
      }
      this.parseString()
      // 通过路段信息获取沿线设备信息
      this.getAlongRouteInfo(value, (data) => {
        const {startPatrolId, endPatrolId} = this.detailForm
        /*
         * 巡检开始，结束站
         * */
        if (startPatrolId) {
          if (!data.some((i) => i.id === startPatrolId)) {
            this.detailForm.startPatrolId = ''
            setTimeout((_) => this.$message.warning('请重新选择开始站..'))
          }
        }
        if (endPatrolId) {
          if (!data.some((i) => i.id === endPatrolId)) {
            this.detailForm.endPatrolId = ''
            setTimeout((_) => this.$message.warning('请重新选择结束站..'))
          }
        }
      })
    },
    // 附件预览list
    getFilePreviewUrlList(files) {
      return files.map((item) => {
        return item.filePreviewUrl
      })
    },
    // 打开页面执行
    openPage() {
    },
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, (_) => {
        PubSub.publish(pageName, {type})
      })
    },
    // 关闭页面执行
    closePage() {
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub: this.pubSub
      })
      this.$nextTick((_) => {
        this.$refs.formInfo.$el.scrollTop = 0
      })
    },
    // 获取详情
    async getDetail(id) {
      const {occupy = '', ...detailForm} = await tableDetail(id)
      this.detailForm = {
        ...detailForm
      }
      this.detailForm.occupy = occupy.split(',')
      if (this.detailForm.pegVal) {
        let startPegArr = this.detailForm.pegVal.split('+')
        this.$set(this.detailForm, 'startPeg', startPegArr[0].slice(1))
        this.$set(this.detailForm, 'startPegAdd', startPegArr[1])
      } else {
        this.$set(this.detailForm, 'startPeg', '')
        this.$set(this.detailForm, 'startPegAdd', '')
      }
      this.disableShow = false
    },
    // 添加处置环节
    handleAddDisposal() {
      this.disposalProcess = true
    },
    handleUpdataHandles() {
      this.getDetail(this.detailForm.id)
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.add-btn-fixed {
  position: fixed;
  bottom: 160px;
  right: 40px;
  z-index: 999;
}

.corporate-customers {
  .edit-add-detail {
    .form-content {
      .el-form {
        .rows {
          ::v-deep.rows-title {
            flex: 1;
            display: flex;
            justify-content: space-between;

            .text-overflow {
              width: auto;
            }

            .actions {
              display: flex;
              text-align: right;

              // gap: 10px;
              .el-link {
                display: initial !important;
              }
            }
          }
        }
      }
    }
  }
}

.edit-add-detail-new-content {
  width: 100%;
  display: flex;
  height: 0;
  flex: 1;
  //column-gap: 20px;

  .form-content {
    flex: 4;
  }

  .map-content {
    flex: 3;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: $--system-border-color3 0.5px 0.5px 5px 1px;

    ::v-deep.marker-tip {
      position: relative;
      background-image: url('~@/assets/img/patrolAndRescue/inspection-points-icon.png');
      background-size: cover;
      width: 48px !important;
      height: 48px !important;
      z-index: 999;

      &::after {
        position: absolute;
        content: '救援点位置';
        left: 100%;
        top: 8px;
        width: 80px;
        height: 25px;
        font-size: 16px;
        color: $--color-warning;
        text-align: center;
        line-height: 25px;
        padding: 5px 10px;
        background-color: rgba(darken($--color-warning, 70%), 0.9);
        border-radius: 3px;
        box-shadow: 0 0 6px rgba($--color-warning, 0.8);
        border: none;
        z-index: 999;
      }
    }
  }

  .stake-mark {
    ::v-deep .el-form-item__content {
      display: flex;
      justify-content: space-between;

      .pegVal-text2,
      .pegVal-text1 {
        padding-right: 10px;
        font-size: 16px;
        width: fit-content;
      }

      .pegVal-text2 {
        padding-left: 10px;
        font-size: 24px;
      }
    }
  }
}

.flow-box {
  ::v-deep.el-timeline-item__timestamp {
    font-size: 16px;
    color: #fff;
  }

  .el-card {
    background-color: #144871;
    border-radius: 5px;
    position: relative;
  }
  .btn-opinion{
    position: absolute;
    right: 20px;
    top: 20px;
  }

  .header {
    display: flex;

    .title {
      width: 50%;
    }
    .status{
      display: inline-block;
      padding: 2px 8px;
    }
    .status-0 {
      background-color: $--color-success;
    }
    .status-1 {
      background-color: $--color-warning;
      margin-right: 12px;
    }

    margin-bottom: 10px;
  }

  .event-detail {
    // padding: 10px 0;
    margin-bottom: 10px;
  }

  .dispose-img {
    display: flex;
    gap: 10px;

    .el-image {
      border-radius: 5px;
      box-sizing: border-box;
    }
  }

}

::v-deep.el-backtop {
  background: transparent;
}

::v-deep.top-box {
  background: rgba(10, 38, 61, .5);
}

.corporate-customers {
  .edit-add-detail-new-content {
    ::v-deep .form-content {
      border-radius: 0 !important;
      box-shadow: none !important;
    }
  }
}
</style>
