<template>
  <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>
        <el-row :gutter="24" type="flex">
          <el-col :span="12">
            <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="所属路段" prop="roadId">
                  <el-input v-model="addEditForm.roadName" disabled></el-input>
                  <!--              <el-select v-model="addEditForm.roadId" clearable filterable placeholder="请选择所属路段" style="width: 100%"-->
                  <!--                         @change="roadChange">-->
                  <!--                <el-option v-for="item in roadData" :key="item.id" :label="item.roadName" :value="item.id">-->
                  <!--                </el-option>-->
                  <!--              </el-select>-->
                </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="班次" prop="workclass">
                  <el-radio-group v-model="addEditForm.workclass" size="medium">
                    <el-radio v-for="(item, index) in getDictionaryByCode(
                  'bc-xjrw'
                )" :key="index" :label="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" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="巡检类型" prop="planType">
                  <el-radio-group v-model="addEditForm.planType">
                    <el-radio v-for="(item, index) in getDictionaryByCode(
                  'xjlx-xjrw'
                )" :key="index" :label="item.value" :value="Number(item.value)">{{ item.name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="往返类型" prop="inspectType">
                  <el-radio-group v-model="addEditForm.inspectType" size="medium">
                    <el-radio v-for="(item, index) in getDictionaryByCode(
                  'wflx-xjrw'
                )" :key="index" :label="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" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="巡检队伍" prop="teamId">
                  <el-select v-model="addEditForm.teamId" filterable placeholder="请选择巡检队伍" @change="teamChange">
                    <el-option v-for="item in treeData" :key="item.value" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="开始巡检站" prop="startPatrolId">
                  <el-select v-model="addEditForm.startPatrolId" filterable placeholder="请选择开始巡检站"
                             style="width: 100%">
                    <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" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="结束巡检站" prop="endPatrolId">
                  <el-select v-model="addEditForm.endPatrolId" filterable placeholder="请选择结束巡检站"
                             style="width: 100%">
                    <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" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="24">
                <el-form-item label="任务派发频率" prop="frequency">
                  <el-radio-group v-model="addEditForm.frequency">
                    <el-radio v-for="(item, index) in getDictionaryByCode(
                  'xjzq'
                )" :key="index" :label="item.value" :value="item.value">{{ item.name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
              <el-col :span="16">
                <el-form-item label="任务有效期" prop="planStartEndDate">
                  <el-date-picker v-model="addEditForm.planStartEndDate" :picker-options="pickerOptions"
                                  end-placeholder="计划结束时间" range-separator="至" start-placeholder="计划开始时间"
                                  style="width: 100%;"
                                  type="daterange" value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="addEditForm.frequency === '3'" :gutter="24" style="flex-wrap: wrap;margin-left: 80px"
                    type="flex">
              <el-col :span="16">
                <el-form-item :rules="[{ required: true, message: '任务生成时间不能为空', trigger: 'change' }]"
                              label="任务生成时间"
                              prop="planInterval">
                  <el-time-picker v-model="addEditForm.planInterval" placeholder="请选择时间" style="width: 100%;"
                                  value-format="HH:mm:ss">
                  </el-time-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="addEditForm.frequency === '4'" :gutter="24" style="flex-wrap: wrap;margin-left: 80px"
                    type="flex">
              <el-col :span="16">
                <el-form-item :rules="[{ required: true, message: '任务生成时间不能为空', trigger: 'change' }]"
                              label="任务生成时间"
                              prop="planInterval">
                  <el-time-picker v-model="addEditForm.planInterval" placeholder="请选择时间" style="width: 100%;"
                                  value-format="HH:mm:ss">
                  </el-time-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="addEditForm.frequency === '4'" :gutter="24" style="flex-wrap: wrap;margin-left: 80px"
                    type="flex">
              <el-col :span="16">
                <el-form-item :rules="[{ required: true, message: '执行日期不能为空', trigger: 'change' }]"
                              label="执行日期"
                              prop="time">
                  <el-select v-model="addEditForm.time" placeholder="请选择执行日期" style="width: 100%">
                    <el-option v-for="item in getDictionaryByCode('xqtyzd')" :key="item.value" :label="item.name"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="addEditForm.frequency === '5'" :gutter="24" style="flex-wrap: wrap;margin-left: 80px"
                    type="flex">
              <el-col :span="16">
                <el-form-item :rules="[{ required: true, message: '任务生成时间不能为空', trigger: 'change' }]"
                              label="任务生成时间"
                              prop="planInterval">
                  <el-time-picker v-model="addEditForm.planInterval" placeholder="请选择时间" style="width: 100%;"
                                  value-format="HH:mm:ss">
                  </el-time-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="addEditForm.frequency === '5'" :gutter="24" style="flex-wrap: wrap;margin-left: 80px"
                    type="flex">
              <el-col :span="24">
                <el-form-item :rules="[{ required: true, message: '执行日期不能为空', trigger: 'change' }]"
                              label="执行日期"
                              prop="time">
                  <el-checkbox-group v-model="addEditForm.time">
                    <el-checkbox v-for="item in getDictionaryByCode('yftyzd')" :key="item.value" :label="item.value">
                      {{ item.name }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="24" style="flex-wrap: wrap;margin-left: -50px" type="flex">
              <el-col v-loading="treeLoading" :span="24" element-loading-background="rgba(10 ,38 ,61, 0.65)"
                      element-loading-text="数据加载中...">
                <el-form-item class="plan-details" prop="planDetails">
                  <template v-slot:label>
                    <div class="label">
                      巡检内容
                      <el-tooltip class="item" content="清空所选巡检内容" effect="dark" placement="top-start">
                        <i v-show="addEditForm.planDetails.length" class="el-icon-close" @click="clearTreeSelect"></i>
                      </el-tooltip>
                      <el-select
                        v-if="!id"
                        v-model="pointLevel"
                        clearable
                        placeholder="点位级别"
                        style="width: 100px; margin-left: 10px"
                        @change="handlePointLevelChange"
                      >
                        <el-option
                          v-for="item in getDictionaryByCode('dwjb')"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                      <!-- 添加天数选择下拉框 -->
                      <el-select
                        v-if="dayOptions.length > 0"
                        v-model="selectedDay"
                        clearable
                        placeholder="选择天数"
                        style="width: 100px; margin-left: 10px;margin-top: 5px"
                        @change="filterInspectionPointsByDay"
                      >
                        <el-option
                          v-for="item in dayOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </div>
                  </template>
                  <template>
                    <el-scrollbar>
                      <el-tree ref="addEditTree" :data="inspectionPointsData" :default-expand-all="true"
                               :expand-on-click-node="false" :props="addEditTreeProps" check-on-click-node
                               check-strictly
                               node-key="code" show-checkbox @check-change="checkChange">
                        <template v-slot="{ data }">
                          <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>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div slot="footer" class="footer">
      <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 {refineRequestBody} from '@/utils/requestWrappers'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {tableAddEdit, tableDetail} from '@/api/patrolAndRescue/roadWatch/inspectionPlan'
import {tableData as alongRouteInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/alongRouteInfo'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {pointTreeData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/inspectionPointMgmt'
import {orgTree} from '@/api/systemInterface'

export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    const validatePlanDetails = (_, value, callback) => {
      const arr = this.$refs.addEditTree?.getCheckedKeys() || []
      if (Array.isArray(arr) && arr.length) {
        callback()
      } else {
        callback(new Error('巡检内容不能为空'))
      }
    }

    return {
      dayOptions: [], // 天数选项（第一天、第二天...）
      selectedDay: '', // 当前选中的天数
      currentInspectionCycle: '', // 当前选中的巡检周期
      pointLevel: '', // 当前选中的点位级别
      addEditForm: {
        workclass: '1',
        frequency: '',
        roadId: '',
        startPatrolId: '',
        endPatrolId: '',
        planDetails: [],
        planType: '1',
        inspectType: '1',
        planClass: 'com.artfess.rescue.patrol.job.InspectionPlanJob',
        planInterval: '01:00:00',
        time: []
      },
      addEditRules: {
        workclass: [
          {required: true, message: '班次不能为空', trigger: 'change'}
        ],
        planType: [
          {required: true, message: '巡检类型不能为空', trigger: 'change'}
        ],
        inspectType: [
          {required: true, message: '往返类型不能为空', trigger: 'change'}
        ],
        roadId: [
          {required: true, message: '所属路段不能为空', trigger: 'change'}
        ],
        startPatrolId: [
          {required: true, message: '开始巡检站不能为空', trigger: 'change'}
        ],
        endPatrolId: [
          {required: true, message: '结束巡检站不能为空', trigger: 'change'}
        ],
        teamId: [
          {required: true, message: '巡检队伍不能为空', trigger: 'change'}
        ],
        planDetails: [
          {required: true, validator: validatePlanDetails, trigger: 'change'}
        ],
        frequency: [
          {required: true, message: '任务频率不能为空', trigger: 'change'}
        ],
        planStartEndDate: [
          {required: true, message: '生成任务时间段不能为空', trigger: 'change'}
        ],
        planClass: [
          {required: true, message: '定时任务执行类不能为空', trigger: 'change'}
        ]
      },
      pickerOptions: {
        // 时间选择器时间范围
        disabledDate: time => moment(time).isBefore(moment().subtract(1, 'days'))
      },
      saveLoading: false, // 上传loading
      formLoading: true, // 上传loading
      roadChoiceDialog: false, // 是否展示选择路段弹层
      treeData: [], // 组织树
      roadData: [], // 路段数据
      alongRouteInfoData: [], // 沿线设备数据
      inspectionPointsData: [], // 巡查内容（树形点位）数据
      addEditTreeProps: {
        children: 'children',
        label: 'name',
        disabled: data => data.level !== '4'
      },
      id: '', // id标识符
      pubSub: null,
      treeLoading: false
    }
  },
  watch: {
    // 监听频率变化
    'addEditForm.frequency': {
      handler(newVal) {
        this.currentInspectionCycle = newVal
        // 如果roadId存在，则重新获取巡检点数据
        if (this.addEditForm.roadId) {
          this.getInspectionPointsData(this.addEditForm.roadId)
        }
        // 重置天数选择
        this.selectedDay = ''
        this.dayOptions = []
      },
      immediate: true
    },
    //pointLevel的监听
    pointLevel(newVal) {
      // 如果roadId存在，则重新获取巡检点数据
      if (this.addEditForm.roadId) {
        this.getInspectionPointsData(this.addEditForm.roadId)
      }
    },
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
    // this.getOrgTreeData()
    // this.getRoadData()

  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.orgName) {
        this.addEditForm.roadName = data.orgName
        this.addEditForm.roadId = data.catalogId
        this.addEditForm.roadCode = data.code
        this.roadChange(data.catalogId)
      }
      // 新增或修改
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
      // this.getRoadData()
    })
  },
  methods: {
    // 点位级别变化处理
    handlePointLevelChange(value) {
      this.pointLevel = value
      // 清空已选内容
      this.clearTreeSelect()
    },
    teamChange(value) {
      this.addEditForm.teamName = this.treeData.filter(item => item.id === value)[0].name
    },

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

        roadId = roadId || ''

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

        this.addEditForm = {
          ...addEditForm,
          roadId,
          planDetails,
          planStartEndDate: planStartDate && planEndDate ? [planStartDate, planEndDate] : [],
          time,
          planInterval: planIntervalArr[planIntervalArr.length - 1] || '',
          frequency
        }
        this.roadChange(roadId)

        //  通过路段信息获取树形点位、初始化树勾选
        await this.getInspectionPointsData(roadId, () => {
          setTimeout(() => {
            // 只初始化已勾选的节点，不获取新数据
            this.initializeTree(planDetails)

            // 根据频率分组已勾选的数据
            if (planDetails.length > 0) {
              this.groupSelectedPoints(planDetails)
            }
          }, 0)
        })
      } finally {
        this.formLoading = false
      }
    },
// 根据已勾选的数据进行分组
    groupSelectedPoints(selectedCodes) {
      const frequency = Number(this.addEditForm.frequency) || 1
      let groupCount = frequency

      // 特殊处理每周和每月的情况
      if (this.addEditForm.frequency === '6') { // 每周一次
        groupCount = 7
      } else if (this.addEditForm.frequency === '7') { // 每月一次
        groupCount = 30
      }

      // 重置分组数据
      this.groupedInspectionPoints = []
      this.dayOptions = []

      if (groupCount <= 1) {
        // 频率为1天或不分组
        this.groupedInspectionPoints = [selectedCodes] // 确保即使不分组也保留数据
        return
      }

      // 创建分组
      const groupSize = Math.ceil(selectedCodes.length / groupCount)

      // 将已勾选的节点分组
      for (let i = 0; i < groupCount; i++) {
        const start = i * groupSize
        const end = start + groupSize
        const groupNodes = selectedCodes.slice(start, end)
        this.groupedInspectionPoints.push(groupNodes)

        // 添加天数选项
        this.dayOptions.push({
          value: i + 1,
          label: `第${i + 1}天`
        })
      }

      // 默认选中第一天
      this.selectedDay = this.dayOptions[0]?.value || ''
    },
    // 获取公司树
    async getOrgTreeData() {
      this.treeData = await orgTree()
    },

    //获取所在路段列表数据
    // async getRoadData() {
    //   const { rows = [] } = await roadSectionInfoInter({ pageBean: { pageSize: -1 } })
    //   this.roadData = rows.map(item => {
    //     item.roadName = item.name + ' ' + item.code
    //     return item
    //   })
    //   if (!this.id) {
    //     this.addEditForm.roadId = this.roadData[0].id
    //     this.roadChange(this.roadData[0].id)
    //   }
    // },

    // 获取点位树数据
    async getInspectionPointsData(roadId = '', callback) {
      try {
        this.treeLoading = true
        // let inspectionCycle = this.currentInspectionCycle
        //
        // // 特殊处理每周和每月的情况
        // if (this.addEditForm.frequency === '6') { // 每周一次
        //   inspectionCycle = 7 // 传7给后端
        // } else if (this.addEditForm.frequency === '7') { // 每月一次
        //   inspectionCycle = 30 // 传30给后端
        // }
        // 如果是编辑模式且已经有planDetails数据，则不重新获取数据
        if (this.id && this.addEditForm.planDetails && this.addEditForm.planDetails.length > 0) {
          // 直接使用已有的planDetails进行分组
          this.groupSelectedPoints(this.addEditForm.planDetails)
          callback && callback([])
          return
        }
        const {value = []} = await pointTreeData({
          roadId,
          inspectionCycle: this.currentInspectionCycle, // 添加巡检周期参数
          pointLevel: this.pointLevel // 点位级别参数
        }, 'addEdit')
        // 保存原始数据
        this.originalInspectionPoints = JSON.parse(JSON.stringify(value))

        // 根据频率分组数据
        this.groupInspectionPoints(value)
        callback && callback(value)
        // this.inspectionPointsData = value
        // 数据加载完成后默认选中所有level=4的节点
        this.$nextTick(() => {
          if (value.length > 0) {
            const allLeafNodes = this.getAllLeafNodes(value)
            this.$refs.addEditTree.setCheckedKeys(allLeafNodes.map(node => node.code))
            this.addEditForm.planDetails = allLeafNodes.map(node => node.code)
          }
        })
      } catch (error) {
        // 不为请求过快结束的情况下，重置
        if (error.message !== 'canceled') callback && callback([])
      } finally {
        this.treeLoading = false
      }
    },
    // 根据频率分组巡检点数据
    groupInspectionPoints(data) {
      let frequency = Number(this.addEditForm.frequency) || 1
      // 特殊处理每周和每月的情况
      if (this.addEditForm.frequency === '6') { // 每周一次
        frequency = 7 // 分成7组
      } else if (this.addEditForm.frequency === '7') { // 每月一次
        frequency = 30 // 分成30组
      }
      // 重置分组数据
      this.groupedInspectionPoints = []
      this.dayOptions = []

      if (frequency <= 1) {
        // 频率为1天或不分组
        this.inspectionPointsData = data
        return
      }

      // 创建分组
      const leafNodes = this.getAllLeafNodes(data)
      const groupSize = Math.ceil(leafNodes.length / frequency)

      // 将叶子节点分组
      for (let i = 0; i < frequency; i++) {
        const start = i * groupSize
        const end = start + groupSize
        const groupNodes = leafNodes.slice(start, end)
        this.groupedInspectionPoints.push(groupNodes.map(node => node.code))

        // 添加天数选项
        this.dayOptions.push({
          value: i + 1,
          label: `第${i + 1}天`
        })
      }

      // 默认选中第一天
      this.selectedDay = this.dayOptions[0]?.value || ''
      this.filterInspectionPointsByDay()
    },
    // 根据选择的天数过滤巡检点
    filterInspectionPointsByDay() {
      if (!this.selectedDay || this.groupedInspectionPoints.length === 0) {
        // 编辑模式下只显示已勾选的节点
        if (this.id && this.addEditForm.planDetails && this.addEditForm.planDetails.length > 0) {
          this.filterOnlySelectedNodes()
        } else {
          this.inspectionPointsData = this.originalInspectionPoints
        }
        return
      }

      const dayIndex = Number(this.selectedDay) - 1
      const checkedCodes = this.groupedInspectionPoints[dayIndex] || []

      // 编辑模式下只显示已勾选的节点
      if (this.id && this.addEditForm.planDetails && this.addEditForm.planDetails.length > 0) {
        this.filterOnlySelectedNodes(checkedCodes)
      } else {
        // 新增模式下按正常逻辑过滤
        const filteredData = JSON.parse(JSON.stringify(this.originalInspectionPoints))
        this.markAndFilterNodes(filteredData, checkedCodes)
        this.inspectionPointsData = this.filterNodes(filteredData)
      }

      this.updateTreeSelection(checkedCodes)
      // 深度复制原始数据
      const filteredData = JSON.parse(JSON.stringify(this.originalInspectionPoints))

      // 标记哪些节点应该显示
      const markVisibleNodes = (nodes) => {
        nodes.forEach(node => {
          if (node.level === '4') {
            // 叶子节点 - 根据是否在选中分组中决定是否显示
            node.visible = checkedCodes.includes(node.code)
          } else {
            // 非叶子节点 - 递归处理子节点
            if (node.children) {
              markVisibleNodes(node.children)
              // 如果子节点有可见的，则当前节点也可见
              node.visible = node.children.some(child => child.visible)
            } else {
              node.visible = false
            }
          }
        })
      }

      markVisibleNodes(filteredData)

      // 过滤掉不可见的节点
      const filterNodes = (nodes) => {
        return nodes.filter(node => {
          if (node.children) {
            node.children = filterNodes(node.children)
            return node.visible && node.children.length > 0
          }
          return node.visible
        })
      }

      this.inspectionPointsData = filterNodes(filteredData)

      // 更新树组件
      this.$nextTick(() => {
        if (this.$refs.addEditTree) {
          // 默认选中当前分组的节点
          this.$refs.addEditTree.setCheckedKeys(checkedCodes)
          this.addEditForm.planDetails = checkedCodes

          // 展开所有可见节点
          const allNodes = this.$refs.addEditTree.store._getAllNodes()
          allNodes.forEach(node => {
            if (node.data.visible) {
              node.expanded = true
            }
          })
        }
      })
    },
    // 只过滤已选中的节点
    filterOnlySelectedNodes(checkedCodes = []) {
      if (!this.originalInspectionPoints) return

      // 深度复制原始数据
      const filteredData = JSON.parse(JSON.stringify(this.originalInspectionPoints))

      // 标记哪些节点应该显示（只显示已勾选的节点）
      const markVisibleNodes = (nodes) => {
        nodes.forEach(node => {
          if (node.level === '4') {
            // 叶子节点 - 只显示在planDetails中的节点
            node.visible = this.addEditForm.planDetails.includes(node.code) &&
              (checkedCodes.length === 0 || checkedCodes.includes(node.code))
          } else {
            // 非叶子节点 - 递归处理子节点
            if (node.children) {
              markVisibleNodes(node.children)
              // 如果子节点有可见的，则当前节点也可见
              node.visible = node.children.some(child => child.visible)
            } else {
              node.visible = false
            }
          }
        })
      }

      markVisibleNodes(filteredData)
      this.inspectionPointsData = this.filterNodes(filteredData)
    },

// 标记和过滤节点
    markAndFilterNodes(data, checkedCodes) {
      const markVisibleNodes = (nodes) => {
        nodes.forEach(node => {
          if (node.level === '4') {
            node.visible = checkedCodes.includes(node.code)
          } else {
            if (node.children) {
              markVisibleNodes(node.children)
              node.visible = node.children.some(child => child.visible)
            } else {
              node.visible = false
            }
          }
        })
      }
      markVisibleNodes(data)
    },

// 过滤节点
    filterNodes(nodes) {
      return nodes.filter(node => {
        if (node.children) {
          node.children = this.filterNodes(node.children)
          return node.visible && node.children.length > 0
        }
        return node.visible
      })
    },

// 更新树选择状态
    updateTreeSelection(checkedCodes) {
      this.$nextTick(() => {
        if (this.$refs.addEditTree) {
          // 设置勾选状态
          this.$refs.addEditTree.setCheckedKeys(checkedCodes)
          this.addEditForm.planDetails = checkedCodes

          // 展开可见节点
          const allNodes = this.$refs.addEditTree.store._getAllNodes()
          allNodes.forEach(node => {
            if (node.data.visible) {
              node.expanded = true
            }
          })
        }
      })
    },
    // 获取所有level=4的叶子节点---默认选中
    getAllLeafNodes(treeData) {
      const result = []
      const traverse = (nodes) => {
        nodes.forEach(node => {
          if (node.level === '4') {
            result.push(node)
          }
          if (node.children && node.children.length) {
            traverse(node.children)
          }
        })
      }
      traverse(treeData)
      return result
    },
    // 通过路段信息获取沿线设备信息
    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()
      }

    },

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

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

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

      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },

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

    // 路段改变后触发
    async roadChange(value) {
      try {
        // 根据id查询数据索引
        const _findIndex = (arr = [], id) => arr?.findIndex(item => item.id === id)
        // 更新排序
        // value.sort((a, b) => _findIndex(this.roadData, a) - _findIndex(this.roadData, b))

        // 通过路段信息获取巡查队伍信息
        this.getTeamData(value)

        // 通过路段信息获取沿线设备信息
        this.getAlongRouteInfo(value, data => {
          const {startPatrolId, endPatrolId} = this.addEditForm

          /*
          * 巡检开始，结束站
          * */
          if (startPatrolId) {
            if (!data.some(i => i.id === startPatrolId)) {
              this.addEditForm.startPatrolId = ''
              setTimeout(_ => this.$message.warning('请重新选择巡检开始站..'))
            }
          }

          if (endPatrolId) {
            if (!data.some(i => i.id === endPatrolId)) {
              this.addEditForm.endPatrolId = ''
              setTimeout(_ => this.$message.warning('请重新选择巡检结束站..'))
            }
          }
        })

        // 通过路段信息获取巡检内容点位
        this.getInspectionPointsData(value, () => {
          if (value.length === 0) return this.addEditForm.planDetails = []
          const {planDetails = []} = this.addEditForm

          // 避免切换路段导致的点位数据不合法
          setTimeout(_ => {
            this.initializeTree(planDetails)
            const checkNode = this.$refs.addEditTree?.getCheckedNodes() || []
            this.addEditForm.planDetails = planDetails.filter(patrolId => {
              return checkNode.find(i => i.code === patrolId)
            })
          }, 0)
        })
      } finally {
        this.formLoading = false
      }
    },

    // 通过路段信息获取巡查队伍信息
    async getTeamData(value) {
      const {rows = []} = await teamData(refineRequestBody({
        querys: [{operation: 'IN', property: 'r.id_', value}, {operation: 'EQUAL', property: 't.type_', value: '1'}]
      }), 'addEdit')
      this.treeData = rows
    },

    // 树节点选中
    checkChange() {
      this.addEditForm.planDetails = this.$refs.addEditTree?.getCheckedKeys() || []
    },

    // 清空树选中
    clearTreeSelect() {
      this.$refs.addEditTree.setCheckedKeys([])
      this.addEditForm.planDetails = []
    },

    // 重置树状态
    resetTree() {
      this.clearTreeSelect()
      this.collapseAllNodes(false)
    },

    // 收起或展开树所有层级
    collapseAllNodes(state = true) {
      const nodes = this.$refs.addEditTree.store._getAllNodes()
      nodes.forEach(item => item.expanded = state)
    },

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

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

      // 获取所有勾选的节点并展开其父节点
      select.forEach(key => {
        const node = tree?.getNode(key)
        if (node) {
          let parent = node.parent
          while (parent) {
            parent.expand()
            parent = parent.parent
          }
        }
      })
    },

    // 任务类型切换
    frequencyChange() {
      this.addEditForm.planInterval = ''
      this.addEditForm.time = []
      this.$nextTick(_ => {
        this.$refs.addEditForm.clearValidate(['planInterval', 'time', 'taskType'])
      })
    },

    // 保存
    handleSave() {
      // 获取所有分组的选中节点
      let allCheckedNodes = []
      let groupedDetails = []

      // 如果是多天巡检频率（每两天、每周、每月等）
      if (['2', '3', '4', '5', '6', '7'].includes(this.addEditForm.frequency)) {
        // 遍历分组数据，为每个分组添加patrolBatch
        this.groupedInspectionPoints.forEach((group, index) => {
          group.forEach(patrolId => {
            groupedDetails.push({
              patrolId,
              patrolBatch: index + 1 // 批次从1开始
            })
          })
        })
        allCheckedNodes = groupedDetails.map(item => item.patrolId)
      } else {
        // 单天频率，批次为1
        const checkedKeys = this.$refs.addEditTree?.getCheckedKeys() || []
        groupedDetails = checkedKeys.map(patrolId => ({
          patrolId,
          patrolBatch: 1
        }))
        allCheckedNodes = checkedKeys
      }
      // 如果是每周或每月，需要合并所有分组的选中节点
      // if (['2', '3', '4', '5', '6', '7'].includes(this.addEditForm.frequency)) {
      //   allCheckedNodes = this.groupedInspectionPoints.flat()
      // } else {
      //   allCheckedNodes = this.$refs.addEditTree?.getCheckedKeys() || []
      // }
      // 获取所有分组的选中节点
      // const allCheckedNode = this.groupedInspectionPoints.flat() || this.$refs.addEditTree?.getCheckedKeys() || []

      // 在验证前更新planDetails
      this.addEditForm.planDetails = allCheckedNodes
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          this.saveLoading = true

          let {
            startPatrolId = '',
            endPatrolId = '',
            roadId = '',
            startPatrolName = '',
            endPatrolName = '',
            // planDetails = [],
            planStartEndDate: [planStartDate = '', planEndDate = ''] = [],
            time = [],
            planInterval = '',
            ...addEditForm
          } = this.addEditForm

          // 结构出路段及沿路设施数据
          const {roadData, alongRouteInfoData} = this

          /*
          * 处理数据
          * dictionaryEscape为转义函数
          * */
          try {
            // let roadInfo = this.roadData.filter(item => item.id === roadId)[0]
            let {state, message} = await tableAddEdit({
              ...addEditForm,
              startPatrolId,
              endPatrolId,
              roadId,
              // roadName: roadInfo.name,
              // roadCode: roadInfo.code,
              startPatrolName: dictionaryEscape(alongRouteInfoData, startPatrolId, {valueKey: 'id'}),
              endPatrolName: dictionaryEscape(alongRouteInfoData, endPatrolId, {valueKey: 'id'}),
              // teamFullId,
              // teamName,
              // planDetails: planDetails.map(patrolId => ({patrolId})),
              planDetails: groupedDetails,
              planStartDate,
              planEndDate,
              planInterval: time.length ? `${time}|${planInterval}` : planInterval
            })

            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`巡检计划${message}成功`)
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

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

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    },

    moment,
    getDictionaryByCode
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>


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

.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;
        flex-direction: column;
        font-size: 14px;

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

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

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

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

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

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

            .el-checkbox {
              &.is-disabled {
                //display: none;
              }
            }

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

              .point {
                font-size: 14px;
                color: $--color-warning;
              }
            }
          }

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

    &.is-error {
      .el-scrollbar {
        border-color: $--color-error;
      }
    }
  }
}

.plan-details .label {
  display: flex;
  align-items: center;
}

.plan-details .el-icon-close {
  margin-left: 10px;
  cursor: pointer;
  color: #f56c6c;
}

.plan-details .el-icon-close:hover {
  color: #ff0000;
}
</style>
