<template>
  <super-dialog v-model="isShowDialog" :modal="false" :title="'事件委派'" :top="top" :width="width" v-bind="$attrs"
                @closed="closed" @open="open">
    <div :style="{ height }" class="appoint-dialog">
      <div class="team-moudle">
        <el-row :gutter="24" style="display: flex; align-items: baseline;">
          <el-col :span="24">
            <span>*</span>事件处置队伍：
            <el-select v-model="teamInfo.teamId" filterable placeholder="请选择事件处置队伍" style="width: 60%">
              <el-option v-for="item in inspectOptions" :key="item.value" :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="display: flex; align-items: baseline;margin-top: 15px">
          <el-col :span="24">
            是否生成救援单：
            <el-radio-group v-model="generatedOrNot" size="medium">
              <el-radio-button v-for="(item, index) in options" :key="index" :label="item.value">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
      </div>
      <div class="table-module">
        <template>
          <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-table v-if="generatedOrNot" :cell-style="{ 'text-align': 'center' }" :data="rescueInfos"
                    :header-cell-style="{ 'text-align': 'center' }"
                    :max-height="tableMaxHeight" border
                    style="width: 100%">
            <el-table-column type="index" width="80">
              <template #header>
                <i class="el-icon-plus" @click="showDialog('rescueInfo')"></i>
              </template>
            </el-table-column>
            <el-table-column label="救援处置队伍" prop="teamName" width="180">
            </el-table-column>
            <el-table-column label="报案时间" prop="rescueTime" width="180">
            </el-table-column>
            <el-table-column label="派遣人员" prop="userName">
            </el-table-column>
            <el-table-column label="救援类型" prop="rescueType">
              <template v-slot="{ row }">
                {{ dictionaryEscape('jylx', row.rescueType + '') || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="dispatchTime">
              <template v-slot="{ row, $index }">
                <el-link :underline="false" type="primary"
                         @click="showDialog('rescueInfo', row, $index)">
                  编辑
                </el-link>
                <el-link :underline="false" type="danger" @click="deleteTableData($index)">
                  删除
                </el-link>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!generatedOrNot"
               style="width: 100%;height: 30px; line-height: 30px; text-align: center; font-size: 13px; color: #c0c4cc;">
            暂无救援单信息
          </div>
          <div class="content-bottom">
            <el-button size="small" @click="isShowDialog = false">
              取 消
            </el-button>
            <el-button :loading="appointLoading" size="small" type="primary" @click="handleAppoint">
              确 定
            </el-button>
          </div>
        </template>
      </div>
    </div>
    <RescueInfoDialog :baseInfo="baseInfo" :is-show.sync="rescueInfoDialog"
                      :rescueInfoDetail="rescueInfoDetail" :selected-content.sync="rescueInfos"
                      :teamOptions="teamOptions" v-bind="$attrs" @confirm="handleRescueSelect" />
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import RescueInfoDialog from './components/RescueInfoDialog'
import {dictionaryEscape} from '@/utils/dictionary'
import {eventAppoint} from '@/api/patrolAndRescue/commandDispatch/eventInquiry'
import PubSub from 'pubsub-js'

export default {
  name: 'SuperTableSelectorDialog',
  inheritAttrs: false,
  //   mixins: [TableMixin],
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    top: {
      default: '14vh',
      type: String
    },
    width: {
      default: '60%',
      type: String
    },
    height: {
      default: '65vh',
      type: String
    },
    eventInfo: {
      default: () => {
      },
      type: Object
    },
    baseInfo: {
      default: () => {
      },
      type: Object
    },
    teamOptions: {
      default: () => [],
      type: Array
    },
    inspectOptions: {
      default: () => [],
      type: Array
    },
    roadOptions: {
      default: () => [],
      type: Array
    }
  },
  components: {
    SuperDialog,
    RescueInfoDialog
  },
  data() {
    return {
      rescueInfoDialog: false,
      initializeRendering: false, // 弹层内容初始化渲染
      tableMaxHeight: '600px',
      enhancedTableData: [], // 增强的表格数据（增加额外特性）
      teamTreeData: [],
      teamInfo: {
        teamId: '',
        teamFullId: ''
      },
      appointLoading: false,
      rescueInfos: [],
      rescueInfoDetail: {},
      options: [
        {label: '否', value: 0},
        {label: '是', value: 1}
      ],
      generatedOrNot: 0
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  watch: {},
  methods: {
    dictionaryEscape,
    // 打开弹层时触发
    open() {
      // this.getTableData()
      // this.getOrgTreeData()
    },

    // 展示弹层
    showDialog(dialogName, row, index) {
      if (!dialogName) return
      if (row) {
        this.rescueInfoDetail = row
        this.rescueInfoDetail.type = 'edit'
        this.rescueInfoDetail.index = index
      } else {
        this.rescueInfoDetail = {}
        this.rescueInfoDetail.type = 'add'
      }
      this[dialogName + 'Dialog'] = true
    },
    handleAppoint() {
      if (this.teamInfo.teamId) {
        this.$confirm('确认委派吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.appointLoading = true
          let data = JSON.parse(JSON.stringify(this.eventInfo))
          data = {...data, ...this.teamInfo, ...this.baseInfo}
          data.rescueInfos = JSON.parse(JSON.stringify(this.rescueInfos))
          data.rescueInfos = data.rescueInfos.map(item => {
            return {
              ...item,
              createName: this.eventInfo.createName,
              createBy: this.eventInfo.createBy,
              occupy: Array.isArray(item.occupy) ? item.occupy.join(',') : item.occupy
            }
          })
          try {
            let {state, message, value} = await eventAppoint(data)
            if (state) {
              this.isShowDialog = false
              this.$message.success(`委派成功`)
              this.$emit('offPage')
              // this.$router.push({
              //   path: '/platLayout/patrolAndRescue/commandDispatch/EventManagement'
              // })
            }
          } finally {
            this.appointLoading = false
          }
        })
      }

      // this.$refs.addEditForm.validate(async (valid, object) => {
      //   if (!valid) {
      //     this.$message.warning(
      //       `有${Object.keys(object).length
      //       }个字段未通过校验，请正确填写表单内容。`
      //     )
      //   } else {
      //     this.$refs.rescueInfoDialog.open(this.addEditForm)
      //   }
      // })
    },
    handleRescueSelect(data) {
      if (data.type === 'edit') {
        this.rescueInfos.splice(data.index, 1, data)
      } else {
        let arrData = [...this.rescueInfos, data]
        this.$set(this, 'rescueInfos', arrData)
      }
    },
    deleteTableData(index) {
      this.$confirm('确认删除此条救援信息吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.rescueInfos.splice(index, 1)
      })
    },
    // 关闭弹层触发
    closed() {
      const {orgData} = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), {orgData})
    }
  },
}
</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;
}

.appoint-dialog {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  row-gap: 16px;
  min-height: 50vh;

  .team-moudle {
    padding: 16px;
    background-color: $--system-module-color1;
    box-sizing: border-box;
    border-radius: 8px;
    color: #fff;

    span {
      color: #f56c6c;
      margin-right: 5px;
    }
  }

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

    .content-bottom {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }

    .rows {
      display: flex;
      align-items: center;
      border-bottom: 1px solid $--system-border-color2;
      padding: 10px 0;

      .rows-left {
        margin-right: 10px;

        .rows-hr {
          width: 3px;
          height: 18px;
          background-color: $--system-border-color1;
          border-radius: 2px;
        }
      }

      .rows-title {
        .text-overflow {
          width: 100%;
          font-size: 16px;
          color: $--color-white;
        }
      }
    }
  }
}
</style>