<template>
  <div class="edit-add-detail detail show-scrollbar">
    <div v-loading="formLoading" class="form-content" element-loading-background="rgba(10 ,38 ,61, 0.9)"
         element-loading-text="详情加载中...">
      <el-form ref="formInfo" :model="detailForm" 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>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="班次">
                  <span :title="dictionaryEscape('bc-xjrw', detailForm.workclass)" class="text">
                    {{ dictionaryEscape('bc-xjrw', detailForm.workclass) || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="巡检类型">
                  <span :title="dictionaryEscape('xjlx-xjrw', detailForm.planType)" class="text">
                    {{ dictionaryEscape('xjlx-xjrw', detailForm.planType) || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="往返类型">
                  <span :title="dictionaryEscape('wflx-xjrw', detailForm.inspectType)" class="text">
                    {{ dictionaryEscape('wflx-xjrw', detailForm.inspectType) || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="巡检队伍">
                  <span :title="detailForm.teamName" class="text">
                    {{ detailForm.teamName || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="所属路段">
                  <template v-slot:default>
                    <div class="tag-box">
                      <el-tag effect="dark">
                        {{ detailForm.roadCode }} {{ detailForm.roadName }}
                      </el-tag>
                    </div>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="开始巡检站">
                  <span :title="detailForm.startPatrolName" class="text">
                    {{ detailForm.startPatrolName || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="结束巡检站">
                  <span :title="detailForm.endPatrolName" class="text">
                    {{ detailForm.endPatrolName || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="计划创建时间">
                  <span :title="detailForm.createTime" class="text">
                    {{ detailForm.createTime || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="24">
                <el-form-item label="巡检任务待办频率">
                  <span :title="dictionaryEscape('jhlx', detailForm.frequency)" class="text">
                    {{ dictionaryEscape('jhlx', detailForm.frequency) || '-' }}
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="定时任务执行类">
              <span :title="dictionaryEscape('rwzxl-xjjh', detailForm.planClass)" class="text">
                {{ dictionaryEscape('rwzxl-xjjh', detailForm.planClass) || '-' }}
              </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="任务运行状态">
              <span :title="dictionaryEscape('rwyxzt', detailForm.taskStatus)" class="text">
                {{ dictionaryEscape('rwyxzt', detailForm.taskStatus) || '-' }}
              </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item :title="detailForm.planStartEndDate || '-'" label="任务生成时间段">
              <span class="text">
                {{ detailForm.planStartEndDate || '-' }}
              </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="detailForm.frequency === '3'" :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="任务生成时间">
                <span :title="detailForm.planInterval" class="text">
                  {{ detailForm.planInterval || '-' }}
                </span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="detailForm.frequency === '4'" :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="时间间隔（每周）">
                <span :title="dictionaryEscape('xqtyzd', detailForm.time)" class="text">
                  {{ dictionaryEscape('xqtyzd', detailForm.time) }}
                </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="detailForm.frequency === '4'" :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="任务生成时间">
                <span :title="detailForm.planInterval" class="text">
                  {{ detailForm.planInterval || '-' }}
                </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="detailForm.frequency === '5'" :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="24">
                <el-form-item label="执行日期（每月）">
                  <template v-slot:default>
                    <div class="tag-box">
                      <el-tag v-for="(item, index) in detailForm.time" :key="index" effect="dark">
                        {{ item }}
                      </el-tag>
                    </div>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="detailForm.frequency === '5'" :gutter="24" style="margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="任务生成时间">
                <span :title="detailForm.planInterval" class="text">
                  {{ detailForm.planInterval || '-' }}
                </span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="24" type="flex">
              <el-col :span="24">
                <el-form-item class="plan-details" label="巡检内容">
                  <el-scrollbar>
                    <el-tree ref="detailTree" :data="inspectionPointsData" :expand-on-click-node="false"
                             :props="detailTreeProps" check-strictly node-key="code" show-checkbox>
                      <template v-slot="{ data, node }">
                        <div class="tree-label">
                          <template v-if="data.level === '4'">
                            <div class="point">
                              {{
                                getValByJson(data.expandInfo, 'roadCode') ? `【${getValByJson(data.expandInfo, 'roadCode')}】` :
                                  ''
                              }}
                              {{
                                getValByJson(data.expandInfo, 'pegVal') ? `${getValByJson(data.expandInfo, 'pegVal')}:` : ''
                              }}
                              {{ data.name }}
                            </div>
                          </template>
                          <template v-else>
                            {{ data.name }}
                          </template>
                        </div>
                      </template>
                    </el-tree>
                  </el-scrollbar>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>

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

<script>
import {tableDetail} from '@/api/patrolAndRescue/roadWatch/inspectionPlan'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'
import {pointTreeData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/inspectionPointMgmt'

export default {
  name: 'DetailPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  components: {},
  data() {
    return {
      detailForm: {},
      formLoading: true,
      inspectionPointsData: [], // 巡查内容（树形点位）数据
      detailTreeProps: {
        children: 'children',
        label: 'name',
        disabled: _ => false
      },
      pubSub: null
    }
  },
  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.getDetail(data.id)
      }
    })
  },
  methods: {
    dictionaryEscape,

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

    // 关闭页面执行
    closePage() {
      const {alongRouteInfoData, pubSub} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {alongRouteInfoData, pubSub})
      this.$nextTick(_ => {
        this.$refs.formInfo.$el.scrollTop = 0
      })
    },

    // 获取详情
    async getDetail(id) {
      try {
        let {
            roadId = '',
            roadCode = '',
            frequency = '',
            planPatrolDetails = [],
            planStartDate = '',
            planEndDate = '',
            planInterval = '',
            ...detailForm
          } = await tableDetail(id),
          planIntervalArr = planInterval.split('|').filter(i => i),
          time = '',
          planDetails = planPatrolDetails.flatMap(i => i.id ? i.id : [])


        roadId = roadId.split(',') || []

        if (planIntervalArr.length === 2) {
          if (frequency === '5') {
            time = planIntervalArr[0].split(',') || []
          } else {
            time = planIntervalArr[0] || ''
          }
        }

        this.detailForm = {
          ...detailForm,
          roadId,
          roadCode,
          planStartEndDate: planStartDate && planEndDate ? `${planStartDate} 至 ${planEndDate}` : '',
          time,
          planDetails,
          planInterval: planIntervalArr[planIntervalArr.length - 1] || '',
          frequency
        }

        //  通过路段信息获取树形点位、初始化树勾选
        await this.getInspectionPointsData(roadId, () => {
          setTimeout(() => this.initializeTree(planDetails), 0)
        })

      } finally {
        this.formLoading = false
      }
    },

    // 获取点位树数据
    async getInspectionPointsData(roadId = [], callback) {
      try {
        const {value = []} = await pointTreeData({
          roadId: Array.isArray(roadId) ? roadId.join() : ''
        }, 'detail')
        callback && callback(value)
        this.inspectionPointsData = value
      } catch (error) {
        // 不为请求过快结束的情况下，重置
        if (error.message !== 'canceled') callback && callback([])
      }
    },

    // 通过JSON对象获取属性值
    getValByJson(json, key) {
      return JSON.parse(json)?.[key]
    },

    // 展开勾选层级点位
    initializeTree(select = []) {
      if (!(Array.isArray(select) && select.length)) return

      const tree = this.$refs.detailTree
      // 设置勾选的节点
      tree.setCheckedKeys(select)

      // 获取所有勾选的节点并展开其父节点
      select.forEach(key => {
        const node = tree?.getNode(key)
        if (node) {
          let parent = node.parent
          while (parent) {
            parent.expand()
            parent = parent.parent
          }
        }
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";

::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.edit-add-detail {

  ::v-deep .plan-details {
    .el-form-item__label {
      width: 100%;
      display: flex;

      .label {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;

        .el-icon-close {
          cursor: pointer;
          transition: color .25s;
          user-select: none;

          &:hover {
            color: $--color-error;
          }
        }
      }
    }

    .el-scrollbar {
      width: 100%;
      border: 1px solid $--system-border-color3;
      border-radius: 4px;
      transition: border-color .25s;

      &:hover {
        border-color: $--system-border-color1 !important;
      }

      .el-tree {
        background: transparent;
        height: 600px;
        border: 0;
        padding: 5px 0 5px 5px;

        .el-tree-node {
          .el-tree-node__content {
            &:hover {
              background-color: $--system-box-color5;
            }

            .el-checkbox {
              display: none;
            }

            .el-checkbox.is-checked ~ .tree-label {
              .point {
                color: $--color-warning;
              }
            }

            .tree-label {
              font-size: 14px;

              .point {
                font-size: 14px;
              }
            }

            .el-icon-caret-right {
              pointer-events: none;
              user-select: none;
            }
          }

          &:focus > .el-tree-node__content {
            background: $--system-box-color3;
          }
        }
      }
    }
  }
}
</style>
