<template>
  <super-dialog
    v-model="isShowDialog"
    :modal="false"
    :title="'救援单信息'"
    :top="top"
    :width="width"
    v-bind="$attrs"
    @closed="closed"
    @open="open"
  >
    <div :style="{height}" class="rescueInfo-dialog">
      <div class="form-module">
        <el-form
          ref="rescueInfo"
          :model="rescueInfo"
          :rules="rescueInfoRules"
          label-position="top"
          label-suffix="："
          label-width="100px"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="报案时间" prop="rescueTime">
                <el-date-picker
                  v-model="rescueInfo.rescueTime"
                  default-time="12:00:00"
                  disabled
                  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="teamId">
                <!-- <el-cascader ref="rescueTeamIdCascader" v-model="rescueInfo.teamId"
                                    :options="teamOptions"
                                    :props="{ emitPath: false, checkStrictly: true, label: 'name', value: 'id' }"
                                    clearable filterable style="width: 100%" @change="teamIdChange"
                                    :show-all-levels="false"></el-cascader> -->
                <el-select
                  v-model="rescueInfo.teamId"
                  filterable
                  placeholder="请选择巡查救援队伍"
                  style="width: 100%"
                  @change="teamIdChange"
                >
                  <el-option
                    v-for="item in teamOptions"
                    :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="rescueType">
                <el-select
                  v-model="rescueInfo.rescueType"
                  clearable
                  placeholder="救援类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('jylx')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="派遣人员" prop="person">
                <!-- <el-input clearable v-model="rescueInfo.person" placeholder="点击选择派遣人员" readonly
                                    class="el-click-input" @click.native="showDialog('userChoice')"
                                    suffix-icon="el-icon-search">
                                </el-input> -->
                <el-select
                  v-model="rescueInfo.person"
                  filterable
                  placeholder="请选择巡查救援队伍"
                  style="width: 100%"
                  @change="handleUserSelect"
                >
                  <el-option
                    v-for="item in personOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="派遣车辆" prop="dispatchCarCode">
                <el-input
                  v-model="rescueInfo.dispatchCarCode"
                  class="el-click-input"
                  clearable
                  placeholder="点击选择派遣车辆"
                  readonly
                  suffix-icon="el-icon-search"
                  @click.native="showDialog('carChoice')"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="派遣车型">
                <el-select
                  v-model="rescueInfo.dispatchCarType"
                  clearable
                  disabled
                  placeholder="派遣车型"
                  style="width: 100%"
                >
                  <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-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="故障车牌">
                <el-input
                  v-model="rescueInfo.carCode"
                  clearable
                  placeholder="故障车牌"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="故障车类" prop="carCalss">
                <el-select
                  v-model="rescueInfo.carCalss"
                  clearable
                  placeholder="故障车类"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('gzcl')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="故障车型" prop="carType">
                <el-select
                  v-model="rescueInfo.carType"
                  clearable
                  placeholder="故障车类"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('gzcx')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="车主姓名">
                <el-input
                  v-model="rescueInfo.carUser"
                  clearable
                  placeholder="车主姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车主电话">
                <el-input
                  v-model="rescueInfo.carUserTel"
                  clearable
                  placeholder="车主电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车载重量（吨）" prop="carWeight">
                <el-input
                  v-model="rescueInfo.carWeight"
                  class="number-input"
                  placeholder="请输入内容"
                  type="number"
                >
                  <template slot="append">吨</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="派遣时间" prop="dispatchTime">
                <el-date-picker
                  v-model="rescueInfo.dispatchTime"
                  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="sceneInfo">
                <el-select
                  v-model="rescueInfo.sceneInfo"
                  clearable
                  placeholder="现场情况"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('xcqk')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="占道情况" prop="occupy">
                <el-select
                  v-model="rescueInfo.occupy"
                  clearable
                  placeholder="占道情况"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in getDictionaryByCode('zdqk')"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="事发天气" prop="weather">
                <el-input
                  v-model="rescueInfo.weather"
                  clearable
                  placeholder="事发天气"
                ></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"
            size="small"
            type="primary"
            @click="handleAppoint"
          >
            确 定
          </el-button>
        </div>
      </div>
    </div>

    <!-- 车辆选择 -->
    <CarChoiceDialog
      :carData="carData"
      :is-show.sync="carChoiceDialog"
      :selected-content.sync="rescueInfo.car"
      @confirm="handleCarSelect"
    />
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import CarChoiceDialog from '../CarChoiceDialog'
import UserChoiceDialog from '../UserChoiceDialog'
import {getDictionaryByCode} from '@/utils/dictionary'
import {personAndCarInfo} from '@/api/patrolAndRescue/commandDispatch/eventManagement'

import moment from 'moment'

export default {
  name: 'RescueInfoDialog',
  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
    },
    rescueInfoDetail: {
      default: () => {
      },
      type: Object
    },
    teamOptions: {
      default: () => [],
      type: Array
    }
  },
  components: {
    SuperDialog,
    CarChoiceDialog,
    UserChoiceDialog
  },
  data() {
    return {
      // 车辆弹层
      carData: {},
      carChoiceDialog: false,
      // 人员弹层
      userChoiceDialog: false,
      initializeRendering: false, // 弹层内容初始化渲染
      tableMaxHeight: '600px',
      enhancedTableData: [], // 增强的表格数据（增加额外特性）
      rescueInfo: {
        car: {},
        // person: '',
        rescueTime: new Date()
      },
      rescueInfoRules: {
        person: [
          {
            required: true,
            message: '派遣人员不能为空',
            trigger: ['change']
          }
        ],
        rescueType: [
          {
            required: true,
            message: '请选择救援状态',
            trigger: ['change']
          }
        ],
        teamId: [
          {
            required: true,
            message: '派遣队伍不能为空',
            trigger: ['change']
          }
        ],
        rescueTime: [
          {
            required: true,
            message: '报案时间不能为空',
            trigger: ['change']
          }
        ]
      },
      tableLoading: false,
      dispatches: [],
      personOptions: [],
      carData: []
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  watch: {
    rescueInfoDetail: {
      handler(newVal, oldVal) {
        this.rescueInfo =
          newVal.type === 'add'
            ? {
              rescueTime: new Date()
            }
            : newVal
        if (newVal.type === 'add') {
          this.$set(this.rescueInfo, 'teamId', '')
          this.$set(this.rescueInfo, 'teamFullId', '')
          this.$set(this.rescueInfo, 'teamName', '')
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getDictionaryByCode,
    // 打开弹层时触发
    open() {
      this.rescueInfoDetail.type === 'add'
        ? this.$set(this, 'rescueInfo', {
          rescueTime: new Date()
        })
        : this.$set(
          this,
          'rescueInfo',
          JSON.parse(JSON.stringify(this.rescueInfoDetail))
        )

      if (this.rescueInfo.teamId) {
        this.getPersonAndCarInfo(this.rescueInfo.teamId)
      }
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      if (dialogName === 'userChoice') {
        if (!this.rescueInfo.teamId) {
          this.$message.error('请先选择救援派遣队伍')
        } else {
          this[dialogName + 'Dialog'] = true
        }
      } else {
        this[dialogName + 'Dialog'] = true
      }
    },
    teamIdChange(value) {
      // this.rescueInfo.teamFullId = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.data?.path || ''
      // this.rescueInfo.teamId = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.value || ''
      // this.rescueInfo.teamName = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.data?.name || ''
      // this.rescueInfo.person = ''
      // this.rescueInfo.user = {}
      // this.dispatches = []
      this.getPersonAndCarInfo(value)

      let teamInfo = this.teamOptions.filter(
        (item) => item.id === this.rescueInfo.teamId
      )[0]
      this.rescueInfo.teamName = teamInfo.name
      this.$set(this.rescueInfo, 'person', '')
      this.dispatches = []
    },

    // 根据队伍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
      })
    },

    handleCarSelect({carNumber, carClass}) {
      this.$set(this.rescueInfo, 'dispatchCarCode', carNumber)
      this.$set(this.rescueInfo, 'dispatchCarType', carClass)
      this.dispatches.forEach((item) => {
        item.dispatchCarCode = carNumber
        item.dispatchCarType = carClass
      })
    },
    handleUserSelect(id) {
      const {dispatchCarCode = '', dispatchCarType = ''} = this.rescueInfo
      const user = this.personOptions.find((item) => item.id === id)
      this.rescueInfo.userName = user.name
      this.dispatches = [
        {
          dispatchCarCode,
          dispatchCarType,
          dispatchUserId: user.userId,
          dispatchUserName: user.name,
          dispatchUserTel: user.tel
        }
      ]
    },
    handleAppoint() {
      this.$refs.rescueInfo.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          let data = JSON.parse(JSON.stringify(this.rescueInfo))
          data.rescueTime = moment(data.rescueTime).format(
            'YYYY-MM-DD HH:mm:ss'
          )

          data.dispatches = JSON.parse(JSON.stringify(this.dispatches))
          this.$confirm('确认保存救援单信息吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            this.$emit('confirm', data)
            this.closed()
          })
        }
      })
    },
    // 关闭弹层触发
    closed() {
      const {orgData} = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), {orgData})
      this.$nextTick(() => {
        this.$refs.rescueInfo?.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;
}

.rescueInfo-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>