<template>
  <div class="cont">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="tabChange">
      <el-tab-pane label="布控对象" name="second">
        <a-button type="primary" style="margin-left: 20px" @click="sendBk()">新增对象</a-button>
        <a-button type="primary" style="margin-left: 20px" @click="openGroupDialog()">分组管理</a-button>
        <div style="padding: 10px; height: calc(100% - 85px); overflow: auto">
          <el-table :data="tableData2" border style="width: 100%">
            <el-table-column type="index" width="60" label="序号" align="center" :index="indexMethod1" />
            <el-table-column label="布控对象属性类型" align="center">
              <template #default="scope">
                {{ scope.row.targetType == 'face' ? '人脸' : '车牌号' }}
              </template>
            </el-table-column>
            <el-table-column prop="targetName" label="布控对象名称" align="center" />
            <el-table-column prop="targetValue" label="布控对象属性值" align="center" show-overflow-tooltip />
            <el-table-column prop="groupName" label="布控对象分组" align="center" />
            <!-- <el-table-column prop="groupLevel" label="分组等级" align="center" /> -->
            <el-table-column prop="targetLevel" label="布控对象等级" align="center" />
            <el-table-column prop="imageData" label="布控对象数据" align="center" />
            <el-table-column prop="controlstatus" label="布控状态" align="center" />
            <el-table-column label="布控对象照片" align="center">
              <template #default="scope">
                <!-- <a-image :width="100" :height="100" :src="scope.row.imageUrl" /> -->
                <el-button @click="handleClick(scope.row.imageUrl)" type="primary" primary size="small">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template #default="scope">
                <a-button type="primary" @click="handleTableChange(scope.row)" size="small">修改</a-button>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template #default="scope">
                <el-popconfirm @confirm="handleTableDelete(scope.row.targetId)" title="确定要删除该布控对象么?">
                  <template #reference>
                    <a-button type="primary" danger size="small">删除</a-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="position: absolute; right: 60px" @current-change="handleCurrentChange2" :page-size="15" layout="total, prev, pager, next" :total="total2"> </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="布控任务" name="first">
        <a-button type="primary" style="margin-left: 20px" @click="sendbkrw">申请布控任务</a-button>
        <div style="padding: 10px; height: calc(100% - 52px); overflow: auto">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="index" width="60" label="序号" align="center" :index="indexMethod2" />
            <el-table-column prop="targetValue" label="布控对象号码" align="center" show-overflow-tooltip />
            <el-table-column label="布控对象类型" align="center">
              <template #default="scope">
                {{ scope.row.targetType == 'face' ? '人脸' : '车牌号' }}
              </template>
            </el-table-column>
            <el-table-column prop="searchCity" label="比对城市" align="center" />
            <el-table-column prop="searchDistrict" label="比对区县" align="center" />
            <el-table-column prop="level" label="任务等级" align="center" />
            <el-table-column prop="alarmType" label="预警类型" align="center" />
            <el-table-column prop="state" label="状态" align="center" />
            <el-table-column prop="timestamp" label="申请时间" align="center" show-overflow-tooltip />
            <el-table-column prop="startTime" label="开始时间" align="center" show-overflow-tooltip />
            <el-table-column prop="endTime" label="结束时间" align="center" show-overflow-tooltip />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <!-- <a-button type="link" @click="chekong(scope.row)">撤控</a-button> -->
                <a-button style="margin-right: 10px" type="primary" @click="xkong(scope.row)" size="small">续控</a-button>
                <el-popconfirm title="确定撤控吗？" @confirm="chekong(scope.row)">
                  <template #reference>
                    <!-- <el-button>撤控</el-button> -->
                    <a-button type="primary" danger size="small">撤控</a-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="position: absolute; right: 60px" @current-change="handleCurrentChange1" :page-size="15" layout="total, prev, pager, next" :total="total1"> </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="分组管理" v-model="groupVisible" width="50%" :before-close="handleClose">
      <a-button type="primary" style="margin-left: 20px; margin-bottom: 10px" @click="addGroup()">新增分组</a-button>
      <div style="overflow-y: auto; height: 500px">
        <el-table :data="tableGroupData" border style="width: 100%">
          <el-table-column class="el_table_column" prop="groupName" label="分组名称" align="center" />
          <el-table-column prop="groupLevel" label="分组等级" align="center" />
          <el-table-column prop="comment" label="分组说明" align="center" />
          <el-table-column align="center">
            <template #default="scope">
              <a-button type="primary" @click="handleTableGroupChange(scope.row)" size="small">修改分组</a-button>
              <el-popconfirm @confirm="handleTableGroupDelete(scope.row.groupId)" title="确定要删除该分组么?">
                <template #reference>
                  <a-button style="margin-left: 10px" type="primary" danger size="small">删除分组</a-button>
                </template>
              </el-popconfirm>
              <!-- <a-button style="margin-left: 10px" type="primary" danger @click="handleTableGroupChange(scope.row)" size="small">删除分组</a-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!-- 新增分组弹窗 -->
    <el-dialog :title="dialogTitle" v-model="addGroupVisible" width="40%" :before-close="closeAddGroup">
      <el-form ref="ruleFormRef_Group" :rules="rulesGroup" :model="formGroup" label-width="120px" style="max-height: 500px; overflow-y: scroll; padding: 10px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input required v-model="formGroup.groupName"></el-input>
        </el-form-item>
        <el-form-item label="分组等级" prop="groupLevel">
          <el-input required v-model="formGroup.groupLevel"></el-input>
        </el-form-item>
        <el-form-item label="分组说明">
          <el-input v-model="formGroup.comment"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addGroupVisible = false" style="color: #0cd6fe">取 消</el-button>
          <el-button type="primary" @click="addGroupFn(ruleFormRef_Group)" style="color: #0cd6fe">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog opened="openDialog" :title="dialogTargrtTitle" v-model="dialogVisible" width="40%" :before-close="handleClose">
      <!-- 不能加这个ref，否则就不是响应式 ref="form" -->
      <el-form ref="ruleFormRef" :rules="rules" :model="form" label-width="120px" style="max-height: 500px; overflow-y: scroll; padding: 10px">
        <el-form-item label="选择地区">
          <el-cascader placeholder="请选择地区" size="default" :options="cascaderOptions" v-model="selectedOptions" @change="handleChange"> </el-cascader>
        </el-form-item>
        <el-form-item label="布控对象名称" prop="targetName">
          <el-input required v-model="form.targetName"></el-input>
        </el-form-item>
        <el-form-item label="布控对象类型">
          <el-select v-model="form.targetType" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布控对象分组">
          <el-select v-model="form.groupName" placeholder="请选择分组" style="width: 100%" @change="selectChange">
            <el-option v-for="item in tableGroupData" :key="item.groupId" :label="item.groupName" :value="item.groupId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布控对象属性值">
          <el-input v-model="form.targetValue"></el-input>
        </el-form-item>

        <el-form-item label="布控对象等级">
          <el-input v-model="form.targetLevel"></el-input>
        </el-form-item>
        <el-form-item label="布控对象数据">
          <el-input v-model="form.imageData"></el-input>
        </el-form-item>

        <el-form-item label="人脸">
          <el-upload
            ref="uploadrefss"
            method="put"
            :before-upload="beforeAvatarUpload"
            :on-error="handleError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            on-success="handlePictureCardSuccess"
            action="#"
            list-type="picture-card"
            :http-request="handleUpload"
            :file-list="fileList"
          >
            <el-icon>
              <plus />
            </el-icon>
          </el-upload>
          <!-- <el-progress :percentage="uploadPercentage" /> -->
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" style="color: #0cd6fe">取 消</el-button>
          <el-button type="primary" @click="RTCSender(ruleFormRef)" style="color: #0cd6fe">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="申请布控任务" v-model="dialogVisiblea1" width="450" :before-close="handleClose">
      <el-form :model="form2" label-width="120px">
        <el-form-item label="布控对象">
          <!-- {{tableData2}} -->
          <el-select v-model="form2.target" :disabled="isxKOng" placeholder="请选择" style="width: 100%" @change="setyd">
            <el-option v-for="item in tableData2" :key="item.targetValue + '&' + item.targetId" :label="item.targetName" :value="item.targetValue + '&' + item.targetId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布控对象类型">
          <el-select v-model="form2.targetType" :disabled="isxKOng" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="布控地区">
          <el-cascader placeholder="请选择地区" :disabled="isxKOng" size="default" :options="cascaderOptions1" v-model="selectedOptions1" @change="handleChange1" style="width: 100%"> </el-cascader>
        </el-form-item>
        <el-form-item label="任务等级">
          <el-input v-model="form2.level" :disabled="isxKOng"></el-input>
        </el-form-item>
        <el-form-item label="预警类型">
          <el-input v-model="form2.alarmType" :disabled="isxKOng"></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="form2.startTime" type="datetime" placeholder="选择日期时间" style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="form2.endTime" type="datetime" placeholder="选择日期时间" style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisiblea1 = false" style="color: #0cd6fe">取 消</el-button>
          <el-button v-if="isxKOng" type="primary" @click="sendxk" style="color: #0cd6fe">确 定</el-button>
          <el-button v-else type="primary" @click="RTCRtpSender" style="color: #0cd6fe">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="布控对象照片" v-model="dialogVisiblea" width="30%" :before-close="handleClose1">
      <!-- <img style="width: 100%; height: 100%" :src="opkierimg" alt="" /> -->
      <div class="dialog-img-container">
        <img :src="opkierimg" alt="" />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import api from '@/axios'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'

const ruleFormRef_Group = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const uploadUrl = ref('')
const isUpdate = ref(false)
const isTargetUpdate = ref(false)
const cascaderOptions = ref([])
const cascaderOptions1 = ref([])
const selectedOptions = ref([])
const selectedOptions1 = ref([])
let uploadrefss = ref()
const uploadPercentage = ref(0)
const fileList = ref([])
const dialogVisiblea = ref(false)
const dialogVisiblea1 = ref(false)
const isxKOng = ref(false)
const opkierimg = ref('')
const activeName = ref('second')
const dialogVisible = ref(false)
const groupVisible = ref(false)
const addGroupVisible = ref(false)

const value1 = ref('')

const tableData = ref<any[]>([])
const tableData2 = ref<any[]>([])
const tableGroupData = ref<any[]>([])
const total1 = ref()
const pageNum2 = ref(1)
const value2 = ref('')

const currentPageIndex = ref(0)
const tabChange = (e: any) => {
  console.log('🚀 ~ tabChange ~ e:', e)
  currentPageIndex.value = 0
}
const total2 = ref()
const pageNum1 = ref(1)
const dialogTitle = ref('新增分组')
const dialogTargrtTitle = ref('新增对象')

interface anyObject {
  [key: string]: string
}
interface formGroupFace {
  groupName: string
  groupId: string
  groupLevel: string
  parentId: string
  comment: string
}

let formGroup = reactive<formGroupFace>({
  groupName: '',
  groupId: '',
  groupLevel: '',
  parentId: '',
  comment: '',
})
const form2 = reactive<anyObject>({
  target: '',
  targetType: '',
  searchCity: '',
  searchDistrict: '',
  level: '',
  alarmType: '',
  startTime: '',
  endTime: '',
})

interface formFace {
  targetType: string
  targetName: string
  targetLevel: string
  imageUrl: string
  imageData: string
  targetId: string
  targetValue: string
  groupId: string
  groupName: string
  controlStatus: string
  district: string
  city: string
  town: string
  imageName: string
  path: string
}
let form = reactive<formFace>({
  targetType: '', //类型
  targetName: '', //对象名字
  targetLevel: '', //布控对象等级
  imageUrl: '', //人脸图片地址
  imageData: '', //布控对象数据
  targetId: '',
  targetValue: '', //属性值
  groupId: '',
  groupName: '',
  controlStatus: '',
  district: '',
  city: '',
  town: '',
  imageName: '',
  path: '',
})

const resetData = () => {
  const keys = Object.keys(form)
  let obj: { [name: string]: string } = {}
  keys.forEach((item) => {
    obj[item] = ''
  })
  Object.assign(form, obj)
}
const options = reactive([
  {
    value: 'face',
    label: '人脸',
  },
  {
    value: 'vehicle',
    label: '车牌',
  },
])
watch(addGroupVisible, (newValue, oldValue) => {
  console.log(`addGroupVisible ${oldValue} to ${newValue}`)
  if (!newValue) {
    isUpdate.value = false
  }
})

const validateTargetName = (rule: any, value: any, callback: any) => {
  console.log('🚀 ~ validateTargetName ~ value:', value)
  if (value.trim().length === 0) {
    callback(new Error('请输入布控对象名称'))
  } else {
    callback()
  }
}
const validateGroupName = (rule: any, value: any, callback: any) => {
  if (value.trim().length === 0) {
    callback(new Error('请输入分组名称'))
  } else {
    callback()
  }
}
const validateGroupLevel = (rule: any, value: any, callback: any) => {
  if (value.trim().length === 0) {
    callback(new Error('请输入分组等级'))
  } else {
    callback()
  }
}
const validateTown = (rule: any, value: any, callback: any) => {
  if (value.trim().length === 0) {
    callback(new Error('请输入街道'))
  } else {
    callback()
  }
}
const validateTargetType = (rule: any, value: any, callback: any) => {
  if (value.trim().length === 0) {
    callback(new Error('请选择布控对象类型'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof form>>({
  targetName: [{ validator: validateTargetName, trigger: 'blur' }],
  // town: [{ validator: validateTown, trigger: 'blur' }],
  // targetType: [{ validator: validateTargetType, trigger: 'change' }],
})

const rulesGroup = reactive<FormRules<typeof formGroup>>({
  groupName: [{ validator: validateGroupName, trigger: 'blur' }],
  groupLevel: [{ validator: validateGroupLevel, trigger: 'blur' }],
})

const addGroupFn = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      if (isUpdate.value) {
        api.post('/multialarm/ai/target/group/update', { ...formGroup }).then((res) => {
          if (res.code == 0) {
            ElMessage.success({
              message: '修改成功',
              type: 'success',
            })
            getGroupList()
            addGroupVisible.value = false
          } else {
            ElMessage.error(`${res.msg}`)
          }
        })
      } else {
        api.post('/multialarm/ai/target/group/add', { ...formGroup }).then((res) => {
          if (res.code == 0) {
            ElMessage.success({
              message: '新增成功',
              type: 'success',
            })
            getGroupList()
            addGroupVisible.value = false
          } else {
            ElMessage.error(`${res.msg}`)
          }
        })
      }
    } else {
      console.log('error submit!')
    }
  })
}

//取消上传，清空上传文件
function doClear() {
  uploadrefss.value.clearFiles()
}

onMounted(() => {
  seachA()
  seachB()
  getGroupList()
  gettree()
})

const gettree = () => {
  api.post('/common/client/user/org/tree').then((res) => {
    console.log('🚀 tree:', res)
    if (res.code == 0) {
      const rawData = res.data as any[]
      interface DataItem {
        label: string
        title: string
        children?: DataItem[]
      }
      function convertDataToOptions(data: DataItem[]): { label: string; value: string; children: any[] }[] {
        return data.map((item) => ({
          label: item.title,
          value: item.title,
          children: item.children ? convertDataToOptions(item.children) : [],
        }))
      }

      function filterCascadeData(data: any, filterFn: any) {
        return data.filter((item: any) => {
          ;(item.label = item.title),
            (item.value = item.title),
            // 递归过滤子项
            (item.children = item.children ? filterCascadeData(item.children, filterFn) : [])
          // 如果当前项或子项通过过滤条件，则保留
          return filterFn(item) || item.children.length > 0
        })
      }
      const filterFn = (item: any) => item.level == '1' || item.level == '2'
      const options = convertDataToOptions(rawData)
      const options1 = filterCascadeData(res.data, filterFn)
      console.log('options', options, options1)
      cascaderOptions.value = options
      cascaderOptions1.value = options1
    } else {
    }
  })
}
const setyd = (e: any) => {}
const chekong = (e: any) => {
  console.log('e', e.taskId)
  // return ;
  api.post('multialarm/ai/task/delete', { taskId: e.taskId }).then((res) => {
    if (res.code == 0) {
      // console.log('新增', res)
      ElMessage.success({
        message: '撤控成功',
        type: 'success',
      })
      dialogVisiblea1.value = false
      api
        .post('/multialarm/ai/task/getlist', {
          pagesize: 15,
          pageindex: 0,
        })
        .then((res) => {
          if (res.code == 0) {
            tableData.value = res.data as any[]
          } else {
            ElMessage.error('请求失败')
          }
        })
    } else {
      ElMessage.error('请求失败')
    }
  })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (form.targetName.trim().length === 0) {
    ElMessage.error('上传图片必须输入布控对象名称')
    return false
  }
  console.log(11111)
}

const handleUpload = async ({ file, onProgress, onSuccess, onError }: { file: File; onProgress: Function; onSuccess: Function; onError: Function }) => {
  console.log('🚀 ~ handleUpload ~ file:', file)
  form.imageName = file.name
  try {
    if (form.targetName.trim().length === 0) {
      ElMessage.error('上传图片必须输入布控对象名称')
      return
    }
    console.log(22222)

    // 1. 获取上传地址
    const uploadUrlResponse = await api.post('/multialarm/ai/target/image/geturl', { ...form })
    const uploadUrl = uploadUrlResponse.data as string
    // 2. 创建 FormData 对象并添加文件
    const formData = new FormData()
    formData.append('file', file)
    // 3. 使用 axios 上传文件
    const response = await axios.put(uploadUrl, file, {
    })
    console.log('🚀 ~ handleUpload ~ response:', response)
    if (response.status === 200) {
      console.log('form.path,form.imageUrl', form.path, form.imageUrl)

      if (form.path.length > 0) {
        let lastSlashIndex = form.path.lastIndexOf('/')
        if (lastSlashIndex !== -1) {
          // 获取斜杠之前的所有字符串
          let prefix = form.path.substring(0, lastSlashIndex)
          console.log('获取斜杠之前的所有字符串', prefix)
          let newPath = `${prefix}/${file.name}`
          form.path = newPath
        } else {
          console.log('未检索到/')
        }
      }
      if (form.imageUrl.length > 0) {
        let lastSlashIndex = form.imageUrl.lastIndexOf('/')
        if (lastSlashIndex !== -1) {
          // 获取斜杠之前的所有字符串
          let prefix = form.imageUrl.substring(0, lastSlashIndex)
          console.log('获取斜杠之前的所有字符串', prefix)
          let newPath = `${prefix}/${file.name}`
          form.imageUrl = newPath
        } else {
          console.log('未检索到/')
        }
      }
      ElMessage.success({
        message: '上传成功',
        type: 'success',
      })
      // 添加文件到 fileList 以便预览
      fileList.value.push({
        name: file.name,
        url: URL.createObjectURL(file),
      })
      console.log('最后检查form', form)

      // if (onSuccess) {
      //   onSuccess(response.data) // 上传成功时的回调
      // }
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    // 上传失败后的回调
    // if (onError) {
    //   onError(error)
    // }
  }
}

const handleChange = (value: string[]) => {
  console.log('🚀 ~ handleChange ~ value:', value)
  if (value[0]) {
    form.city = value[0]
  } else {
    form.city = ''
  }
  if (value[1]) {
    form.district = value[1]
  } else {
    form.district = ''
  }
  if (value[2]) {
    form.town = value[2]
  } else {
    form.town = ''
  }
  // console.log('🚀 ~ handleChange ~ form:', form)
}
const selectChange = (value: any) => {
  console.log('🚀 ~ selectChange ~ value:', value)
  form.groupId = value
}
const RTCSender = (formEl: FormInstance | undefined) => {
  if (selectedOptions.value.length === 0) {
    ElMessage.error('请选择地区')
    return
  }
  if (form.targetType.length === 0) {
    ElMessage.error('请选择布控对象类型')
    return
  }
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      if (isTargetUpdate.value) {
        console.log(form.imageName)
        api.post('/multialarm/ai/target/update', { ...form }).then((res) => {
          if (res.code == 0) {
            ElMessage.success({
              message: '修改成功',
              type: 'success',
            })
            dialogVisible.value = false
            seachB() //刷新总条数和列表

            Object.keys(form).forEach((key) => (form[key as keyof formFace] = ''))
            doClear()
            selectedOptions.value = []
          } else {
            ElMessage.error(res.msg)
          }
        })
      } else {
        api.post('/multialarm/ai/target/add', { ...form }).then((res) => {
          if (res.code == 0) {
            ElMessage.success({
              message: '新增成功',
              type: 'success',
            })
            dialogVisible.value = false
            seachB() //刷新总条数和列表
            Object.keys(form).forEach((key) => (form[key as keyof formFace] = ''))
            doClear()
            selectedOptions.value = []
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    } else {
      console.log('error submit!')
    }
  })
}

const handleTableGroupChange = (row: any) => {
  dialogTitle.value = '修改分组'
  console.log('🚀 ~ handleTableGroupChange ~ row:', row)
  isUpdate.value = true
  addGroupVisible.value = true
  const clonedData = JSON.parse(JSON.stringify(row))
  formGroup = reactive(clonedData)
}
const sendBk = () => {
  isTargetUpdate.value = false
  selectedOptions.value = []
  fileList.value = []
  dialogTargrtTitle.value = '新增对象'
  // Object.keys(form).forEach((key) => (form[key] = ''))
  resetData()
  dialogVisible.value = true
}

const handleTableChange = (row: any) => {
  fileList.value = []
  isTargetUpdate.value = true
  console.log('🚀 ~ handleTableChange ~ row:', row)
  dialogTargrtTitle.value = '修改布控对象'
  dialogVisible.value = true

  // selectedOptions.value.push(row.city, row.district, row.town)
  if (row.city.length > 0 && row.district.length > 0 && row.town.length > 0) {
    selectedOptions.value = [row.city, row.district, row.town]
  }
  if (row.city.length > 0 && row.district.length > 0 && row.town.length === 0) {
    selectedOptions.value = [row.city, row.district]
  }
  if (row.city.length > 0 && row.district.length === 0 && row.town.length === 0) {
    selectedOptions.value = [row.city]
  }
  const clonedData = JSON.parse(JSON.stringify(row))
  form = reactive(clonedData)

  fileList.value.push({
    url: form.imageUrl,
  })
}

const handleTableGroupDelete = (id: string) => {
  console.log('🚀 ~ handleTableGroupDelete ~ id:', id)
  api.post('/multialarm/ai/target/group/delete', { groupId: id }).then((res) => {
    if (res.code == 0) {
      ElMessage.success({
        message: '删除成功',
        type: 'success',
      })
      getGroupList()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleTableDelete = (id: string) => {
  console.log('🚀 ~ handleTableDelete ~ id:', id)
  api.post('/multialarm/ai/target/delete', { targetId: id }).then((res) => {
    if (res.code == 0) {
      ElMessage.success({
        message: '删除成功',
        type: 'success',
      })
      seachB()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const openDialog = (e: any) => {
  console.log('🚀 ~ openDialog ~ e:', e)
}
//续控
const taskId = ref('')
const xkong = (row: any) => {
  if (row.searchCity != '' && row.searchDistrict != '') {
    selectedOptions1.value = [row.searchCity, row.searchDistrict]
  }
  console.log('row', row, tableData2)
  taskId.value = row.taskId
  dialogVisiblea1.value = true
  isxKOng.value = true
  form2.target = row.targetValue + '&' + row.targetId
  form2.targetType = row.targetType
  form2.searchCity = row.searchCity
  form2.searchDistrict = row.searchDistrict
  form2.level = row.level
  form2.alarmType = row.alarmType
  form2.startTime = row.startTime
  form2.endTime = row.endTime
}
//提交续控
const sendxk = () => {
  let data = {
    targetId: '',
    targetValue: '',
    targetType: form2.targetType,
    searchCity: form2.searchCity,
    searchDistrict: form2.searchDistrict,
    level: form2.level,
    alarmType: form2.alarmType,
    startTime: form2.startTime,
    endTime: form2.endTime,
    taskId: taskId.value,
  }
  if (form2.target != '') {
    data.targetId = form2.target.split('&')[1]
    data.targetValue = form2.target.split('&')[0]
  }
  api.post('multialarm/ai/task/update', data).then((res) => {
    if (res.code == 0) {
      // console.log('新增', res)
      ElMessage.success({
        message: '续控成功',
        type: 'success',
      })
      dialogVisiblea1.value = false
      api
        .post('/multialarm/ai/task/getlist', {
          pagesize: 15,
          pageindex: 0,
        })
        .then((res) => {
          if (res.code == 0) {
            tableData.value = res.data as any[]
          } else {
            ElMessage.error('请求失败')
          }
        })
    } else {
      ElMessage.error('请求失败')
    }
  })
}
const handleChange1 = (value: string[]) => {
  console.log('🚀 ~ handleChange1 ~ value:', value)
  if (value[0]) {
    form2.searchCity = value[0]
  } else {
    form2.searchCity = ''
  }
  if (value[1]) {
    form2.searchDistrict = value[1]
  } else {
    form2.searchDistrict = ''
  }
  if (value[2]) {
    form2.searchTown = value[2]
  } else {
    form2.searchTown = ''
  }
}
const RTCRtpSender = () => {
  console.log('form2', form2)
  if (form2.target === '') {
    ElMessage.error('请选择布控对象')
    return
  }
  if (form2.targetType === '') {
    ElMessage.error('请选择布控对象类型')
    return
  }
  if (form2.searchCity === '') {
    ElMessage.error('请选择布控城市')
    return
  }
  if (form2.searchDistrict === '') {
    ElMessage.error('请选择布控区县')
    return
  }
  if (form2.startTime === '') {
    ElMessage.error('请选择开始时间')
    return
  }
  if (form2.endTime === '') {
    ElMessage.error('请选择结束时间')
    return
  }
  let data = {
    targetId: '',
    targetValue: '',
    targetType: form2.targetType,
    searchCity: form2.searchCity,
    searchDistrict: form2.searchDistrict,
    level: form2.level,
    alarmType: form2.alarmType,
    startTime: form2.startTime,
    endTime: form2.endTime,
  }
  if (form2.target != '') {
    data.targetId = form2.target.split('&')[1]
    data.targetValue = form2.target.split('&')[0]
  }
  api.post('/multialarm/ai/task/add', data).then((res) => {
    if (res.code == 0) {
      // console.log('新增', res)
      ElMessage.success({
        message: '新增成功',
        type: 'success',
      })
      dialogVisiblea1.value = false
      api
        .post('/multialarm/ai/task/getlist', {
          pagesize: 15,
          pageindex: 0,
        })
        .then((res) => {
          if (res.code == 0) {
            tableData.value = res.data as any[]
          } else {
            ElMessage.error('请求失败')
          }
        })
    } else {
      ElMessage.error('请求失败')
    }
  })
}

const sendbkrw = () => {
  selectedOptions1.value = []
  isxKOng.value = false
  form2.target = ''
  form2.targetType = ''
  form2.searchCity = ''
  form2.searchDistrict = ''
  form2.level = ''
  form2.alarmType = ''
  form2.startTime = ''
  form2.endTime = ''
  dialogVisiblea1.value = true
}

const handleClick = (data: any) => {
  opkierimg.value = data
  dialogVisiblea.value = true
}
const handleClose1 = () => {
  dialogVisiblea.value = false
}

const handlePictureCardPreview = (file: any) => {
  console.log('🚀 ~ handlePictureCardPreview ~ file:', file)
}
const handleError = (response: any) => {
  console.log('🚀 ~ handleError ~ response:', response)
  return ElMessage({
    message: '文件上传失败',
    type: 'error',
    offset: 60,
  })
}

const handleRemove = () => {
  console.log('🚀 ~ handleRemove ~ handleRemove:')
}

const handleClose = () => {
  dialogVisible.value = false
  dialogVisiblea1.value = false
  groupVisible.value = false
}
//布控任务

const seachA = () => {
  api.post('/multialarm/ai/task/count', {}).then((res) => {
    if (res.code == 0) {
      total1.value = res.data as { count: number }
    }
  })
  api
    .post('/multialarm/ai/task/getlist', {
      pagesize: 15,
      pageindex: 0,
    })
    .then((res) => {
      if (res.code == 0) {
        tableData.value = res.data as any[]
      } else {
        ElMessage.error('请求失败')
      }
    })
}

const handleCurrentChange1 = (data: any) => {
  console.log('🚀 ~ handleCurrentChange1 ~ data:', data)
  pageNum2.value = data
  api
    .post('/multialarm/ai/task/getlist', {
      pagesize: 15,
      pageindex: data - 1,
    })
    .then((res) => {
      if (res.code == 0) {
        tableData2.value = res.data as any[]
      } else {
        ElMessage.error('请求失败')
      }
    })
}
const indexMethod2 = (index: number) => {
  return (pageNum2.value - 1) * 15 + index + 1
}
//布控对象

//刷新总条数和列表
const getGroupList = () => {
  api.post('/multialarm/ai/target/group/getlist', {}).then((res) => {
    console.log('🚀 ~ api.post ~ res:', res)
    if (res.code == 0) {
      tableGroupData.value = res.data as any[]
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const seachB = () => {
  api.post('/multialarm/ai/target/count', {}).then((res) => {
    console.log('🚀 ~ seachB ~ res:', res)
    if (res.code == 0) {
      total2.value = res.data as { count: number }
    }
  })
  api
    .post('/multialarm/ai/target/getlist', {
      pagesize: 15,
      pageindex: currentPageIndex.value,
    })
    .then((res) => {
      if (res.code == 0) {
        tableData2.value = res.data as any[]
      } else {
        ElMessage.error('请求失败')
      }
    })
}

// 布控对象的分页
const handleCurrentChange2 = (data: number) => {
  console.log('🚀 ~ handleCurrentChange2 ~ data:', data)
  currentPageIndex.value = data - 1
  pageNum1.value = data
  api
    .post('/multialarm/ai/target/getlist', {
      pagesize: 15,
      // pageindex: data - 1,
      pageindex: currentPageIndex.value,
    })
    .then((res) => {
      if (res.code == 0) {
        tableData2.value = res.data as any[]
      } else {
        ElMessage.error('请求失败')
      }
    })
}
const indexMethod1 = (index: number) => {
  return (pageNum1.value - 1) * 15 + index + 1
}
const openGroupDialog = () => {
  groupVisible.value = true
}
const addGroup = () => {
  dialogTitle.value = '新增分组'
  Object.keys(formGroup).forEach((key) => (formGroup[key as keyof formGroupFace] = ''))
  addGroupVisible.value = true
}
const closeAddGroup = () => {
  addGroupVisible.value = false
}
</script>

<style scoped lang="scss">
.dialog-img-container {
  overflow: visible; //让图片放大到外面，内容不能被裁减并且可能渲染到边距盒（padding）的外部。
}

.dialog-img-container img {
  transition: transform 0.3s ease;
  width: 100%;
  height: 100%;
}

.dialog-img-container img:hover {
  transform: scale(2.3);
}

.cont {
  width: 100%;
  height: 100%;
  background-color: #fff;
  // background:rgba(9, 45, 84, 1)
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

:deep(.el-upload--picture-card) {
  background-color: transparent;
}

:deep(.el-select__wrapper) {
  background-color: transparent;
  box-shadow: 0 0 0 1px #1f9bd9;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: transparent;
  box-shadow: 0 0 0 1px #1f9bd9;
}

:deep(.el-textarea) {
  --el-input-bg-color: #071d4d;
  // --el-input-border-color: #071D4D;
}

:deep(.el-dialog__body) {
  position: relative;
  padding: 10px;
  color: #fff;
}

:deep(.el-dialog) {
  --el-dialog-bg-color: #071d4d;
  border: 3px solid #387dbf;
}

:deep(.el-dialog__header) {
  padding: 13px;
  border-bottom: 1px solid #3374b4 !important;
  margin-right: 0px;
}

:deep(.el-dialog__title) {
  color: #067bc1 !important;
  font-weight: 500;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
  font-weight: 500;
  font-size: 18px;
}

:deep(.el-tabs__nav-wrap::after) {
  background-color: #d9d9d95e;
  height: 4px;
}

:deep(.el-tabs__item) {
  color: #00000070;
  font-weight: 700;
}

:deep(.el-tabs) {
  --el-tabs-header-height: 50px;
}

:deep(.el-tabs__item.is-active) {
  color: #000;
}

:deep(.el-tabs__active-bar) {
  height: 4px;
  background-color: #000;
}

:deep(.el-tabs__nav-wrap) {
  padding-left: 23px;
}

:deep(.el-input__wrapper) {
  background-color: transparent;
  box-shadow: 0 0 0 1px #1f9bd9;
}

:deep(.el-select__wrapper) {
  background-color: transparent;
  box-shadow: 0 0 0 1px #1f9bd9;
}

:deep(.el-input__inner) {
  color: #fff;
}

:deep(.el-input__prefix) {
  color: #fff;
}

.el_button_ {

}

:deep(.el-button) {
  background-color: transparent;
  border-color: #0cd6fe;
  color: #000;
}

:deep(.el-table) {
  --el-table-border-color: #1677ff40;
}

:deep(.el-select__placeholder) {
  color: #fff;
}

:deep(.el-table th.el-table__cell) {
  // background-color: #5C9AD5;
}

:deep(.el-table thead) {
  // color: #fff;
}

:deep(.el-table tr) {
  // background-color: #E9F0F8;
}

:deep(.el-table__body tr.current-row > td) {
  // background: #2cabff !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  // background-color:  #13306A !important;
}

:deep(.el-table th.el-table__cell) {
  // background-color:#13306A;
}

:deep(.el-date-editor .el-range-input) {
  color: #fff;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  // background: #D1DEEE !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  // background-color: transparent;
}

:deep(.el-tabs) {
  height: 100%;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
}

:deep(.el-tabs__content) {
  height: calc(100% - 53px);
}

:deep(.el-tab-pane) {
  height: 100%;
}

::-webkit-scrollbar {
  background-color: #071d4d;
}
</style>
