<template>
  <super-dialog v-bind="$attrs" v-model="isShowDialog" :width="width" :modal="false" :top="top" @open="open"
                @closed="closed" :title="'救援单信息'">
    <div class="eventInfo-dialog" :style="{ height }">
      <div class="form-module">
        <el-form ref="eventInfo" :model="eventInfo" :rules="rescueInfoRules" label-width="100px"
                 label-position="top" label-suffix="：">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="派遣队伍" prop="teamId">
                <el-select v-model="eventInfo.teamId" placeholder="请选择巡查救援队伍" filterable
                           style="width: 100%" @change="teamIdChange">
                  <el-option v-for="item in teamData" :key="item.value" :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="派遣人员" prop="person">
                <el-input clearable v-model="eventInfo.person" placeholder="点击选择派遣人员" readonly
                          class="el-click-input" @click.native="showDialog('userChoice')"
                          suffix-icon="el-icon-search">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="派遣车辆" prop="dispatchCarCode">
                <el-input clearable v-model="eventInfo.dispatchCarCode" placeholder="点击选择派遣车辆" readonly
                          class="el-click-input" @click.native="showDialog('carChoice')"
                          suffix-icon="el-icon-search">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="派遣车型">
                <el-select disabled v-model="eventInfo.dispatchCarType" style="width: 100%" clearable
                           placeholder="派遣车型">
                  <el-option v-for="(item, index) in getDictionaryByCode(
                                        'jycl-cllx'
                                    )" :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="carWeight">
                <!-- <el-input clearable v-model="eventInfo.eventTel" placeholder="点击选择关联事件" readonly
                    class="el-click-input" @click.native="showDialog('eventChoice')"
                    suffix-icon="el-icon-search">
                </el-input> -->
                <el-input clearable v-model="eventInfo.eventNo" placeholder="点击选择关联事件" readonly
                          class="el-click-input" @click.native="showDialog('eventChoice')"
                          suffix-icon="el-icon-search">
                  <template v-if="eventInfo.eventNo" v-slot:prepend>
                    NO.
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="content-bottom">
          <el-button size="small" @click="isShowDialog = false">
            取 消
          </el-button>
          <el-button :disabled="tableLoading" :loading="saveLoading" size="small" type="primary"
                     @click="handleAppoint">
            确 定
          </el-button>
        </div>
      </div>
    </div>

    <!-- 车辆选择 -->
    <CarChoiceDialog :is-show.sync="carChoiceDialog" :selected-content.sync="eventInfo.car" :carData="carData"
                     @confirm="handleCarSelect" />
    <!-- 人员选择 -->
    <UserChoiceDialog :is-show.sync="userChoiceDialog" :selected-content.sync="eventInfo.user"
                      @confirm="handleUserSelect" :personOptions="personOptions" />
    <!-- 事件选择 -->
    <EventChoiceDialog :is-show.sync="eventChoiceDialog" :selected-content.sync="eventInfo.event"
                       @confirm="handleEventSelect" :roadId="roadId" />
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import CarChoiceDialog from './components/CarChoiceDialog'
import UserChoiceDialog from './components/UserChoiceDialog'
import EventChoiceDialog from './components/EventChoiceDialog'
import { getDictionaryByCode } from '@/utils/dictionary'
import { appoint } from '@/api/patrolAndRescue/obstacleClearingRescue/rescueRegistration'
import { orgTree } from '@/api/systemInterface'

import { personAndCarInfo } from '@/api/patrolAndRescue/commandDispatch/eventRegistration'
import moment from 'moment'
export default {
  name: 'AppointDialog',
  inheritAttrs: false,
  //   mixins: [TableMixin],
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    selectedContent: {
      default: () => [],
      type: [Array, Object]
    },
    top: {
      default: '14vh',
      type: String
    },
    width: {
      default: '60%',
      type: String
    },
    height: {
      default: '65vh',
      type: String
    },
    confirmCloseDialog: {
      default: true,
      type: Boolean
    },
    baseInfo: {
      default: () => { },
      type: Object
    },
    roadOptions: {
      default: () => [],
      type: Array
    },
    teamOptions: {
      default: () => [],
      type: Array
    },
    roadId: {
      default: '',
      type: String
    }
  },
  components: {
    SuperDialog,
    CarChoiceDialog,
    UserChoiceDialog,
    EventChoiceDialog
  },
  data() {
    return {
      // 车辆弹层
      carData: {},
      carChoiceDialog: false,
      // 人员弹层
      userChoiceDialog: false,
      initializeRendering: false, // 弹层内容初始化渲染
      tableMaxHeight: '600px',
      enhancedTableData: [], // 增强的表格数据（增加额外特性）
      eventInfo: {
        car: {},
        person: '',
        rescueTime: new Date()
      },
      rescueInfoRules: {
        person: [
          {
            required: true,
            message: '派遣人员不能为空',
            trigger: ['change']
          }
        ],
        rescueStatus: [
          {
            required: true,
            message: '请选择救援状态',
            trigger: ['change']
          }
        ],
        teamId: [
          {
            required: true,
            message: '派遣队伍不能为空',
            trigger: ['change']
          }
        ],
        rescueTime: [
          {
            required: true,
            message: '报案时间不能为空',
            trigger: ['change']
          }
        ]
      },
      tableLoading: false,
      dispatches: [],
      eventChoiceDialog: false,
      saveLoading: false,
      personOptions: [],
      carData: []
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    },
    teamData: {
      get() {
        return this.teamOptions.filter(item => item.type === '3')
      },
    }
  },
  created() {
  },
  methods: {
    getDictionaryByCode,
    // 打开弹层时触发
    open() {
      if (this.eventInfo.teamId) {
        this.getPersonAndCarInfo(this.eventInfo.teamId)
      }
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      if (dialogName === 'userChoice') {
        if (!this.eventInfo.teamId) {
          this.$message.error('请先选择救援派遣队伍')
        } else {
          this[dialogName + 'Dialog'] = true
        }
      } else {
        this[dialogName + 'Dialog'] = true
      }
    },
    teamIdChange(value) {
      this.getPersonAndCarInfo(value)
      let teamInfo = this.teamOptions.find(item => item.id === value)
      this.eventInfo.teamName = teamInfo.name
      this.$set(this.eventInfo, 'person', '')
      this.eventInfo.user = {}
      this.dispatches = []

      // this.eventInfo.teamFullId = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.data?.path || ''
      // this.eventInfo.teamId = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.value || ''
      // this.eventInfo.teamName = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.data?.name || ''
      // this.eventInfo.person = ''
      // this.eventInfo.user = {}
      // this.dispatches = []
    },
    handleCarSelect({ carNumber, carClass }) {
      console.log({ carNumber, carClass });

      this.$set(this.eventInfo, 'dispatchCarCode', carNumber)
      this.$set(this.eventInfo, 'dispatchCarType', carClass)
      this.dispatches.forEach(item => {
        item.dispatchCarCode = carNumber
        item.dispatchCarType = carClass
      })
    },
    handleUserSelect(user) {
      const { dispatchCarCode = '', dispatchCarType = '' } = this.eventInfo
      this.eventInfo.person = user.name
      this.dispatches = [
        {
          dispatchCarCode,
          dispatchCarType,
          dispatchUserId: user.id,
          dispatchUserName: user.name,
          dispatchUserTel: user.tel,
        }
      ]
    },

    // 根据队伍id查询人员信息及车辆信息
    getPersonAndCarInfo(id) {
      personAndCarInfo(id).then(res => {
        const { members = [], cars = [] } = res.value
        this.personOptions = members.map(person => {
          person.label = person.tel + ' ' + person.name
          return person
        })
        this.carData = cars
      })
    },

    // 事件
    handleEventSelect({ id, eventTel, eventNo }) {
      this.eventInfo.eventTel = eventTel
      this.eventInfo.uploadId = id
      this.eventInfo.eventNo = eventNo
    },
    handleAppoint() {
      this.$refs.eventInfo.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          let data = JSON.parse(JSON.stringify(this.baseInfo))
          data.occupy = JSON.stringify(data.occupy)
          if (data.startPeg && data.startPegAdd) {
            data.pegVal = 'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
          }
          let roadInfo = this.roadOptions.find(item => item.id === data.roadId)
          data.roadName = roadInfo.name
          data.roadCode = roadInfo.code
          data.dispatches = JSON.parse(JSON.stringify(this.dispatches))
          data.eventInfo = JSON.parse(JSON.stringify(this.eventInfo))
          data.teamId = data.eventInfo.teamId
          data.teamName = data.eventInfo.teamName
          data.rescueTime = moment(data.rescueTime).format('YYYY-MM-DD HH:mm:ss')
          this.$confirm('确认委派救援单吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              let { state, message, value } = await appoint({ ...data, ...data.road })
              if (state) {
                this.$message.success(`委派成功`)
                this.closed()
                this.$emit('offPage')
              }
            } finally {
              this.saveLoading = false
            }
          })
        }
      })
    },
    // 关闭弹层触发
    closed() {
      const { orgData } = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), { orgData })
      this.$nextTick(() => {
        this.$refs.eventInfo?.clearValidate()
      })
      if (this.confirmCloseDialog) this.isShowDialog = false
    },
  }
}
</script>

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

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

.eventInfo-dialog {
  width: 100%;
  display: flex;
  flex-direction: column;
  column-gap: 16px;
  min-height: 50vh;

  .form-module {
    width: 100%;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    row-gap: 16px;
    background-color: $--system-module-color1;
    padding: 16px;
    box-sizing: border-box;
    border-radius: 8px;

    .el-form {
      height: calc(100% - 40px);
      overflow-y: scroll;

    }

    .content-bottom {
      display: flex;
      justify-content: flex-end;
      height: 40px;
    }

  }
}

::v-deep::-webkit-scrollbar-thumb,
::v-deep::-webkit-scrollbar {
  display: none;
}
</style>