<template>
  <div class="page-content corporate-customers">
    <transition-group appear class="transition-group" tag="div">
      <div key="EditAddPage" class="edit-add-detail">
        <div class="sceoll-content">
          <div class="tab-nav" @click="tabChange">
            <div id="activeBar" class="active-bar"></div>
            <div
              id="basicsNav"
              :class="[`nav-item`, activeName === 'basics' ? 'active-nav' : '']"
              @click="tabChange('basics')"
            >
              基本情况
            </div>
            <div
              id="controlNav"
              :class="[
                `nav-item`,
                activeName === 'control' ? 'active-nav' : ''
              ]"
              @click="tabChange('control')"
            >
              交通管制
            </div>
            <div
              id="jamNav"
              :class="[`nav-item`, activeName === 'jam' ? 'active-nav' : '']"
              @click="tabChange('jam')"
            >
              交通拥堵
            </div>
          </div>
          <div class="content-box">
            <BasicsInfo
              ref="basicsContent"
              :roadOptions="roadOptions"
              @basicInfoChange="handleMemoChange"
              @roadChange="roadChange"
            ></BasicsInfo>
            <TrafficControl
              ref="controlContent"
              :roadOptions="roadOptions"
              @sendTrafficData="getTrafficData"
            >
            </TrafficControl>
            <TrafficJam
              ref="jamContent"
              :roadOptions="roadOptions"
              @sendJamData="getJamData"
            ></TrafficJam>
          </div>
        </div>
        <div slot="footer" class="footer" style="padding-bottom: 20px">
          <div class="form-row">
            <el-form
              ref="addEditForm"
              :model="addEditForm"
              :rules="addEditRules"
              label-position="right"
              label-suffix="："
              label-width="100px"
            >
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="事件描述" prop="memo">
                    <el-input
                      v-model="addEditForm.memo"
                      :autosize="{minRows: 3, maxRows: 3}"
                      placeholder="请输入事件描述"
                      type="textarea"
                      @change="handleUserChangeMemo"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="处理措施">
                    <el-input
                      v-model="addEditForm.disposition"
                      :autosize="{minRows: 3, maxRows: 3}"
                      placeholder="请输入处理措施"
                      type="textarea"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="登记人" prop="createBy">
                    <div class="user-select">
                      <el-select
                        v-model="addEditForm.createBy"
                        clearable
                        placeholder="请选择登记人"
                        @focus="registrationChange"
                        @change="changeCreateBy"
                      >
                        <el-option
                          v-for="item in userOptions"
                          :key="item.userId"
                          :label="item.userName"
                          :value="item.userId"
                        ></el-option>
                      </el-select>
                      <el-button
                        v-if="!userOptions.length"
                        icon="el-icon-date"
                        type="primary"
                        @click="handlePage"
                      >排班
                      </el-button
                      >
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div>
            <el-button
              :loading="saveLoading"
              type="primary"
              @click.prevent="handleSave"
            >
              登记
            </el-button>
            <el-button
              v-if="isShowAppoint"
              :loading="saveLoading"
              type="primary"
              @click="showAppointDialog('appoint')"
            >
              委派
            </el-button>
          </div>
          <!-- <el-button @click="changePage('TablePage')">
            {{ $t('domestic.cancel') }}
          </el-button> -->
        </div>
        <!--  救援委派弹层  -->
        <AppointDialog
          :baseInfo="baseInfo"
          :eventInfo="addEditForm"
          :inspectOptions="inspectOptions"
          :is-show.sync="appointDialog"
          :roadOptions="roadOptions"
          :teamOptions="teamOptions"
          @offPage="offPage"
        />

        <!--  排班  -->
        <SchedulingDialog
          :isShowDetail.sync="schedulingDialog"
        />
      </div>
    </transition-group>
  </div>
</template>

<script>
import moment from 'moment'
import PubSub from 'pubsub-js'
import {refineRequestBody} from '@/utils/requestWrappers'
import {
  getSchedulingPerson,
  tableAdd,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/commandDispatch/eventRegistration'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import AppointDialog from './components/AppointDialog'
import TrafficControl from './components/TrafficControl'
import SchedulingDialog from './components/SchedulingDialog'
import TrafficJam from './components/TrafficJam'
import BasicsInfo from './components/BasicsInfo'
import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'

export default {
  name: 'EventRegistration',
  components: {
    SchedulingDialog,
    AppointDialog,
    TrafficControl,
    BasicsInfo,
    TrafficJam
  },
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    return {
      activeName: 'basics',
      formLoading: true,
      appointDialog: false,
      schedulingDialog: false,
      addEditForm: {
        trafficControls: [],
        trafficCongestions: [],
        createBy: '', // 登记人id
        createName: '' // 登记人姓名
      },
      addEditRules: {
        memo: [
          {
            required: true,
            message: '事件描述不能为空',
            trigger: ['change', 'blur']
          }
        ],
        createBy: [
          {
            required: true,
            message: '登记人不能为空',
            trigger: ['change', 'blur']
          }
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      roadChoiceDialog: false, // 是否展示选择路段弹层
      routerData: [], // 路线数据
      pubSub: null,
      mapLoading: true, // 地图加载loading
      map: null,
      mapDefaultOptions: {
        center: [106.5507, 29.5647] /*地图中心点*/,
        zoom: 9 /*地图默认缩放等级*/
      },
      markers: [],
      teamTreeData: [], // 救援队伍组织树
      eventGradeOptions: [
        //事件等级
        {label: '1级', value: 1},
        {label: '2级', value: 2},
        {label: '3级', value: 3},
        {label: '4级', value: 4}
      ],
      tableData: [],
      roadOptions: [],
      alongRouteInfoData: [],
      teamOptions: [],
      inspectOptions: [],
      options: [
        {label: '否', value: 0},
        {label: '是', value: 1}
      ],
      generatedOrNot: 0,
      teamInfo: {
        teamId: '',
        teamFullId: ''
      },
      baseInfo: {},
      userChanged: false, // 用户是否编辑memo
      basic: '', // 基本情况
      measure: '', // 交通管制
      casualties: '', // 受伤情况
      userOptions: [],
      isShowAppoint: true,
      roadInfo: {}
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
    // this.getOrgTreeData()
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
    this.getRoadOptions()
    this.setNavBarWidth()
    this.scrollToNavStyle()

    this.$bus.$on('synchronousData', data => {
      this.tabChange('control')
    })
  },
  methods: {
    handleMemoChange(data) {
      console.log(data, '-----')
      if (data.isAppoint) {
        this.isShowAppoint = false
      } else {
        this.isShowAppoint = true
      }
      // return
      const {basic, measure, casualties} = data
      basic ? (this.basic = basic) : ''
      measure ? (this.measure = measure) : ''
      casualties ? (this.casualties = casualties) : ''
      if (!this.userChanged) {
        const memoParts = []
        if (this.basic) memoParts.push(this.basic)
        if (this.measure && this.measure !== '无') memoParts.push(this.measure)
        if (this.casualties) memoParts.push(this.casualties)
        const memo = memoParts.join(',') + '。'
        this.$set(this.addEditForm, 'memo', memo)
      }
    },
    handleUserChangeMemo() {
      this.userChanged = true
    },

    // 获取tabitem的宽度
    setNavBarWidth(type = 'basics') {
      this.$nextTick(() => {
        const activeNav = document.getElementById(`${type}Nav`)
        const activeBar = document.getElementById('activeBar')
        activeBar.style.width = activeNav.offsetWidth + 'px'
        activeBar.style.transform = `translateX(${activeNav.offsetLeft}px)`
      })
    },
    tabChange(type) {
      this.setNavBarWidth(type)
      const target = this.$refs[`${type}Content`].$refs.targetSection
      target.scrollIntoView({behavior: 'smooth'})
      event.stopPropagation()
    },

    // 滚动设置nav样式
    scrollToNavStyle() {
      const target = this.$refs[`basicsContent`].$refs.targetSection
      const target1 = this.$refs[`controlContent`].$refs.targetSection
      const target2 = this.$refs[`jamContent`].$refs.targetSection
      let arr = [target, target1, target2]
      const observer = new IntersectionObserver(
        entries => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              this.activeName = entry.target.dataset.name
              this.setNavBarWidth(entry.target.dataset.name)
            }
          })
        },
        {
          root: null, // 默认为视口
          rootMargin: '0px', // 根元素的边距
          threshold: 0.3 // 当 50% 的元素进入视口时触发
        }
      )

      observer.observe(target)
      observer.observe(target1)
      observer.observe(target2)
    },

    dictionaryEscape,
    sendRescueInfo(data) {
      console.log(data)
      this.tableData.push(data)
    },
    getDictionaryByCode,

    // 路段数据查询
    async getRoadOptions() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      console.log(rows, 'rows')
      this.roadOptions = rows.map(item => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      if (!this.id) {
        this.$set(this.addEditForm, 'roadId', this.roadOptions[0].id)
        this.roadChange(this.roadOptions[0].id)
        // this.getUserData(this.roadOptions[0].orgId)
      }
    },

    // 路段选择变化
    async roadChange(value) {
      this.getTeamData(value)
      this.getInspectData(value)
      this.roadInfo = this.roadOptions.find(item => item.id === value)
      this.addEditForm.createBy = ''
      this.addEditForm.createName = ''
      // target && target.orgId && this.getUserData(target.orgId) //  获取排班信息
    },
    registrationChange() {
      if (this.roadInfo && this.roadInfo.orgId) {
        this.getUserData(this.roadInfo.orgId)
      }
    },
    changeCreateBy(){
      this.addEditForm.createName = this.userOptions.find(item => item.userId === this.addEditForm.createBy)?.userName || ''
    },
    async getUserData(orgId) {
      const query = {
        orgId: orgId
      }
      const {state, value = []} = await getSchedulingPerson(query)
      if (state) {
        this.userOptions = value
      } else {
        this.userOptions = []
      }
      if (!this.userOptions.length) {
        this.$message.warning('当前区域下没有排班人员，请为当前区域排班！')
      }
    },
    // 通过路段信息获取巡查救援队伍信息
    async getTeamData(value) {
      const {rows = []} = await teamData(
        refineRequestBody({
          querys: [
            {operation: 'IN', property: 'r.id_', value},
            {operation: 'EQUAL', property: 't.type_', value: '2'}
          ]
        }),
        'addEdit'
      )
      this.teamOptions = rows
    },
    // 通过路段信息获取巡查救援队伍信息
    async getInspectData(value) {
      const {rows = []} = await teamData(
        refineRequestBody({
          querys: [
            {operation: 'IN', property: 'r.id_', value},
            {operation: 'EQUAL', property: 't.type_', value: '1'}
          ]
        }),
        'addEdit'
      )
      this.inspectOptions = rows
    },
    // 队伍选择
    teamIdChange(type) {
      this[type].teamFullId =
        this.$refs[`${type}Cascader`]?.getCheckedNodes()[0]?.data?.path || ''
      this[type].teamId =
        this.$refs[`${type}Cascader`]?.getCheckedNodes()[0]?.value || ''
    },
    // 打开页面执行
    openPage() {
      this.getRoadOptions()
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    showAppointDialog() {
      this.baseInfo = this.$refs.basicsContent.sendBaseData()
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${Object.keys(object).length +
            (this.baseInfo.fieldNum ||
              0)}个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          if (this.baseInfo.fieldNum) {
            this.$message.warning(
              `有${this.baseInfo.fieldNum}个字段未通过校验，请正确填写表单内容。`
            )
          } else {
            this.appointDialog = true
          }
        }
      })
    },
    offPage() {
      this.changePage('TablePage', 'edit')
    },
    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules, roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules,
        roadOptions
      })
      // this.$refs.mineMap?.resetMap(_ => this.mapLoading = false) // 重置地图
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      try {
        this.addEditForm = await tableDetail(id)
        const {roadId = '', pegSVal = '', pegEVal = ''} = this.addEditForm
        if (pegSVal) {
          let startPegArr = pegSVal.split('+')
          this.addEditForm.startPeg = startPegArr[0].slice(1)
          this.addEditForm.startPegAdd = startPegArr[1]
        }
        if (pegEVal) {
          let endPegArr = pegEVal.split('+')
          this.addEditForm.endPeg = endPegArr[0].slice(1)
          this.addEditForm.endPegAdd = endPegArr[1]
        }
        this.roadChange(roadId)
      } finally {
        this.formLoading = false
      }
    },

    // 保存
    handleSave() {
      let basiceData = this.$refs.basicsContent.sendBaseData()

      console.log(basiceData, 'basiceData')

      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${Object.keys(object).length +
            (basiceData.fieldNum || 0)}个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          if (basiceData.fieldNum) {
            this.$message.warning(
              `有${basiceData.fieldNum}个字段未通过校验，请正确填写表单内容。`
            )
          } else {
            if (this.saveLoading) return
            this.saveLoading = true
            let data = JSON.parse(JSON.stringify(this.addEditForm))
            const myInterFace = this.id ? tableEdit : tableAdd
            try {
              let {state, message, value} = await myInterFace({
                ...data,
                ...basiceData
              })
              if (state) {
                message = this.id ? '编辑' : '新增'
                this.$message.success(`保存成功`)
                this.$router.push({
                  path:
                    '/platLayout/patrolAndRescue/commandDispatch/EventManagement'
                })
              }
            } finally {
              this.saveLoading = false
            }
          }
        }
      })
    },
    getTrafficData(data) {
      let measure
      if (data.length > 0) {
        console.log(data, '交通管制数据')
        this.addEditForm.trafficControls = data
        let controlTime = null,
          typeList = []
        const singleType = ['1', '3', '5']
        const gzcs = this.getDictionaryByCode('gzcs')
        data.forEach(item => {
          if (item.controlTime) {
            if (controlTime) {
              const tempTime = moment(item.controlTime)
              if (controlTime.isBefore(tempTime)) {
                controlTime = tempTime
              }
            } else {
              controlTime = moment(item.controlTime)
            }
          }

          if (item.measureType) {
            if (singleType.includes(item.measureType)) {
              const tempType = dictionaryEscape('gzcs', item.measureType)
              if (!typeList.includes(tempType)) {
                typeList.push(tempType)
              }
            } else if (item.measureContent) {
              const targetSubDict = gzcs.find(
                dict => dict.value === item.measureType
              )
              const gzcsxqOptions =
                targetSubDict && targetSubDict.lowerDic
                  ? targetSubDict.lowerDic.gzcsxq
                  : []

              item.measureContent.split(',').forEach(content => {
                const tempType = gzcsxqOptions.find(
                  dict => dict.value === content
                )
                if (tempType && !typeList.includes(tempType.name)) {
                  typeList.push(tempType.name)
                }
              })
            }
          }
        })
        const formattedControlTime = controlTime
          ? `，预计${controlTime.format('M月D日HH时mm分')}恢复正常`
          : ''
        measure =
          (typeList.length ? typeList.join('、') : '') + formattedControlTime
      } else {
        measure = '无'
      }
      this.handleMemoChange({measure})
    },
    getJamData(data) {
      let measure
      if (data.length > 0) {
        console.log(data, '交通拥堵')
        this.addEditForm.trafficCongestions = data
        let controlTime = null,
          typeList = []
        data.forEach(item => {
          if (item.controlTime) {
            if (controlTime) {
              const tempTime = moment(item.controlTime)
              if (controlTime.isBefore(tempTime)) {
                controlTime = tempTime
              }
            } else {
              controlTime = moment(item.controlTime)
            }
          }

          if (item.measure) {
            const tempType = dictionaryEscape('czcs', item.measure)
            if (!typeList.includes(tempType)) {
              typeList.push(tempType)
            }
          }
        })
        const formattedControlTime = controlTime
          ? `，预计${controlTime.format('M月D日HH时mm分')}恢复正常`
          : ''
        measure =
          (typeList.length ? typeList.join('、') : '') + formattedControlTime
      } else {
        measure = '无'
      }
      this.handleMemoChange({measure})
    },
    handlePage() {
      // this.$router.push({
      //   name: 'shiftInformationManagement'
      // })
      this.schedulingDialog = true
    },
    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

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

::v-deep .footer {
  display: block !important;
  height: 240px !important;
  text-align: center;
  padding: 0 20px;
  box-sizing: border-box;

  .form-row {
    margin-top: 40px;
  }
}

.sceoll-content {
  height: calc(100% - 93px);
  background: #114066;
  border-radius: 5px;
  overflow: hidden;

  .tab-nav {
    display: flex;
    gap: 20px;
    position: relative;
    height: 54px;
    line-height: 54px;
    padding: 0 20px;
    font-size: 20px;
    font-weight: 600;

    .active-bar {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 3px;
      background-color: #409eff;
      z-index: 2;
      // transition: transform .3scubic-bezier(.645, .045, .355, 1);
      transition: all 0.3s;
      list-style: none;
    }

    .nav-item {
      color: #fff;
      width: fit-content;
      color: #fff;
      cursor: pointer;
      font-size: 16px;
      padding: 0 10px;
    }

    &::after {
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 3px;
      background-color: #2e5778;
      z-index: 1;
    }

    .active-nav {
      color: #409eff;
    }
  }

  .content-box {
    height: calc(100% - 54px);
    overflow-y: scroll;

    .edit-add-detail-new-content {
      height: auto;
      overflow: auto;
    }
  }

  ::-webkit-scrollbar {
    width: 0 !important;
  }
}

.el-icon-plus {
  cursor: pointer;
  display: block;
  height: 100%;
  font-size: 16px !important;
  font-weight: 900;
  color: #43a1ff;
}

.number-input {
  ::v-deep .el-input__inner {
    font-size: 14px;
  }
}

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

  .form-content {
    flex: 3;
  }

  .map-content {
    flex: 4;
    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;
      }
    }
  }
}

.user-select {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
}
</style>
