<template>

  <!-- 状态 -->
  <div class="head">
    <n-steps size="small" :current="current" :status="'process'">
      <n-step v-for="(it, i) in TASK_STATUS" :key="i + it.label" :title="it.label" />
    </n-steps>
  </div>

  <!-- 基本信息 -->
  <div class="cont">
    <n-descriptions label-placement="left" label-align="right" :column="4" title="任务基本信息">
      <template v-for="(it, i) in (basicInfo.slice(0, -1))" :key="i + it.label">
        <n-descriptions-item v-if="!it.isShow" :label="it.label">
          {{ it.value }}
        </n-descriptions-item>
      </template>
    </n-descriptions>
    <!-- 为了格式，折腾 -->
    <n-descriptions label-placement="left" label-align="right" class="note">
      <n-descriptions-item :key="basicInfo[basicInfo.length -1].label" :label="basicInfo[basicInfo.length -1].label">
        {{ basicInfo[basicInfo.length -1].value }}
      </n-descriptions-item>
    </n-descriptions>
  </div>

  <!-- 飞行信息 - 待分配飞手：状态为5 -->
  <div v-if="current === 1 && roleType === 1" class="cont">
    <div class="title">飞行信息</div>
    <n-form
      ref="formRef"
      :model="form.userForm"
      :rules="form.userRules"
      :label-width="85"
      label-placement="left"
      require-mark-placement="left"
    >
      <template v-for="it in form.formItem" :key="it.key">
        <n-form-item v-if="it?.isLive !== data.isLive" :label="it.label" :path="it.key">
          <n-select v-model:value="form.userForm[it.key]" v-bind="it.props" />
        </n-form-item>
      </template>
    </n-form>
    <n-button type="info" class="btn" @click="submitClick">提交</n-button>
  </div>

  <!-- 飞行信息 - 状态不为5 -->
  <div v-if="current !== 1" class="cont">
    <n-descriptions label-placement="left" label-align="right" :column="4" title="飞行信息">
      <template v-for="(it, i) in flyInfo" :key="i + it.label">
        <n-descriptions-item v-if="!it?.current || current >= it?.current" :label="it.label">
          {{ it.value }}
        </n-descriptions-item>
      </template>
    </n-descriptions>
  </div>

  <!-- 设备/影响基本信息 - 飞手接单: 管理员 -->
  <div v-if="current == 2 && roleId !== data.flightHandId" class="cont">
    <n-descriptions label-placement="left" label-align="right" :column="4" title="设备/影像基本信息">
      <template v-for="(it, i) in equipmentInfo" :key="i + it.label">
        <n-descriptions-item v-if="it?.isLive !== data.isLive" :label="it.label">
          {{ it.value }}
        </n-descriptions-item>
      </template>
    </n-descriptions>
  </div>

  <!-- 飞手接单: 飞手 -->
  <div v-if="current === 2 && roleId === data.flightHandId" class="cont">
    <div class="title">飞行信息</div>
    <n-form
      ref="formRefOrder"
      :model="form.userForm"
      :rules="form.userRulesOrder"
      :label-width="85"
      label-placement="left"
      require-mark-placement="left"
    >
      <template v-for="it in form.formItemOrder" :key="it.key">
        <n-form-item v-if="it?.isLive !== data.isLive" :label="it.label" :path="it.key">
          <n-select v-model:value="form.userForm[it.key]" v-bind="it.props" />
        </n-form-item>
      </template>
    </n-form>
    <n-button type="info" class="btn" @click="flyClick">接单</n-button>
  </div>

  <!-- 设备/影响基本信息 - 已接单 -->
  <div v-if="current === 3" class="cont">
    <n-descriptions label-placement="left" label-align="right" :column="4" title="设备/影像基本信息">
      <template v-for="(it, i) in executionInfo" :key="i + it.label">
        <n-descriptions-item v-if="it?.isLive !== data.isLive" :label="it.label">
          {{ it.value }}
        </n-descriptions-item>
      </template>
    </n-descriptions>
    <n-button v-if="roleId === data.flightHandId" type="info" class="btn" @click="startFly">开始飞行</n-button>
  </div>

  <!-- 设备/影响基本信息 - 执行中: 管理员 -->
  <div v-if="current === 4" class="cont">
    <n-descriptions label-placement="left" label-align="right" :column="4" title="设备/影像基本信息">
      <template v-for="(it, i) in executionInfo" :key="i + it.label">
        <n-descriptions-item v-if="it?.isLive !== data.isLive" :label="it.label">
          {{ it.value }}
        </n-descriptions-item>
      </template>
    </n-descriptions>
    <n-button v-if="roleId === data.flightHandId" type="Error" class="btn" @click="endFly">结束飞行</n-button>
  </div>

  <!-- 设备/影响基本信息 - 执行中: 管理员 -->
  <div v-if="current === 5" class="cont">
    <n-descriptions label-placement="left" label-align="right" :column="4" title="设备/影像基本信息">
      <template v-for="(it, i) in executionInfo" :key="i + it.label">
        <n-descriptions-item v-if="it?.isLive !== data.isLive" :label="it.label">
          {{ it.value }}
        </n-descriptions-item>
      </template>
    </n-descriptions>
  </div>

  <div v-if="current === 5" class="cont">
    <div class="title">飞行文件</div>

    <UploadVod
      v-if="data.photographyWay === 1 && (roleId === data.flightHandId || roleType === 1) && !data.videoUrl"
      ref="videoRefs"
      :upload-name="'视频'"
      :limit="1"
      :class="{'uploads': remBtn}"
      @upload-status="vodStatusVideo"
    />
    <fileOss
      v-if="data.photographyWay === 1 && (roleId === data.flightHandId || roleType === 1) && data.videoUrl"
      :file-type="'video'"
      :btn-name="'视频'"
      :limit="1"
      :default-list="data.videoUrl"
      @upload-status="vodStatusVideo"
    />

    <fileOss
      v-if="data.photographyWay === 1 && (roleId === data.flightHandId || roleType === 1)"
      ref="srtRefs"
      :file-type="'srt'"
      :key-name="'srtUrl'"
      :btn-name="'轨迹'"
      :limit="1"
      :default-list="data.srtUrl"
      :class="{'uploads': remBtn}"
    />
    <fileOss
      v-if="data.photographyWay === 2 && (roleId === data.flightHandId || roleType === 1)"
      :file-type="'tif'"
      :key-name="'orthoUrl'"
      :btn-name="'正射影像'"
      :show-upload-btn="true"
      :limit="9"
      :default-list="data.orthoUrl"
      @upload-status="statusfile"
    />
    <fileOss
      v-if="data.photographyWay === 3 && (roleId === data.flightHandId || roleType === 1)"
      :file-type="'tif'"
      :key-name="'inclinedUrl'"
      :show-upload-btn="true"
      :btn-name="'倾斜影像'"
      :limit="9"
      :default-list="data.inclinedUrl"
      @upload-status="statusfile"
    />

    <n-button
      v-if="data.photographyWay === 1 && (roleId === data.flightHandId || roleType === 1) && !data.videoUrl"
      type="primary"
      class="btn"
      :loading="loading"
      :disabled="remBtn"
      @click="submitFile"
    >
      <n-icon>
        <UploadOutlined />
      </n-icon>
      开始上传
    </n-button>
  </div>

</template>

<script setup name="DrawComp">
import { ref, defineProps, reactive, defineEmits, watch } from 'vue'
import { TASK_STATUS } from '@/utils/dictionary'
import { distributionPilot, pilotOrder, pilotStart, pilotEnd, uploadFlightUrl } from '@/api/task/index.js'
import { form, getPilotList, getEquipment, getEquipmentMount, getCloudMount } from '../tools/drawForm'
import { basic, fly, equipment, execution } from '../hook/index'
import UploadVod from '@/components/UploadVod/index.vue'
import fileOss from '@/components/UploadOss/fileUploadOss.vue'
import { UploadOutlined } from '@vicons/antd'
import { useUserStore } from '@/store/modules/user'
import { useDialog } from 'naive-ui'

getPilotList() // 获取飞手列表
getEquipment() // 无人机列表
getEquipmentMount() // 挂载设备列表
getCloudMount() // 挂载盒子列表

const props = defineProps({
  detail: {
    type: Object,
    required: true
  }
})
const dialog = useDialog()

const { detail: { data }} = props // 传来的详情数据
form.userForm = data

const current = data.pilotStatus / 5 // 当前状态

const roleId = useUserStore().userInfo.id || '00a5a13322fc088cc1c4ba4c40d22fcs' // 默认为管理员id
const roleType = useUserStore().userInfo.type || 1 // 默认为管理员id
// const roleId = '00a5a13322fc088cc1c4ba4c40d22fcs' // 调试id
// console.log(roleId, data.flightHandId, roleType) // 调试id

const formRef = ref() // 表格refs - 分配飞手
const formRefOrder = ref() // 表格refs - 飞手接单

const basicInfo = basic(data) // 基础信息
const flyInfo = fly(data) // 飞行信息
const equipmentInfo = equipment(data) // 设备/影响基本信息
const executionInfo = execution(data) // 执行中信息

const videoRefs = ref(null) // video refs
const srtRefs = ref(null) // srt refs

const loading = ref(false)

const emit = defineEmits(['close'])

// 分配飞手
const submitClick = () => {
  formRef.value?.validate().then(() => {
    const { userForm } = form
    distributionPilot({
      ...userForm,
      id: data.id
    }).then(({ code }) => {
      if (code === 0) {
        emit('close')
      }
    })
  }).catch(e => {
    $message.error('请完善必填信息')
  })
}
// 飞手接单
const flyClick = () => {
  formRefOrder.value?.validate().then(() => {
    const { userForm } = form
    pilotOrder({
      ...userForm,
      flightHandId: data.flightHandId,
      id: data.id
    }).then(({ code }) => {
      if (code === 0) {
        emit('close')
      }
    })
  }).catch(e => {
    $message.error('请完善必填信息')
  })
}

// 开始飞行
const startFly = () => {
  dialog.warning({
    title: '',
    content: '确定开始飞行吗？',
    positiveText: '确定',
    onPositiveClick: () => {
      pilotStart({ id: data.id }).then(({ code, msg }) => {
        if (code === 0) {
          emit('close')
        }
      })
    }
  })
}

// 结束飞行
const endFly = () => {
  dialog.warning({
    title: '',
    content: '确定结束飞行吗？',
    positiveText: '确定',
    onPositiveClick: () => {
      pilotEnd({ id: data.id }).then(({ code, msg }) => {
        if (code === 0) {
          emit('close')
        }
      })
    }
  })
}

// 只视频上传
const vodStatusVideo = async({ status, list, videoIds }) => {
  // console.log(status, list, videoIds)
  // const arr = []
  // for (var key in list) {
  //   arr.push(list[key].url)
  // }
  // if (status === 'success') {
  //   const params = {
  //     id: data.id,
  //     videoUrl: arr.join(','),
  //     videoId: videoIds
  //   }
  //   console.log('params', params)
  //   await uploadFlightUrl(params)
  // }
}

// 只文件上传
const statusfile = async(status, list) => {
  if (status === 'success') {
    const params = {
      id: data.id,
      ...list
    }
    await uploadFlightUrl(params)
  }
}

// 上传中取消
// watch(() => [videoRefs.value?.data?.fileList, srtRefs.value?.fileList], ([val1, val2]) => {
//   if (data.flightHandId === roleId) {
//     if (Object.keys(val1).length === 0 && Object.keys(val2).length === 0) {
//       loading.value = false
//     }
//   }
// })
const videoVal = ref({})
const srtVal = ref({})
const remBtn = ref(false)

watch(() => [videoVal.value.videoId, srtVal.value], ([val1, val2]) => {
  if (val1 && Object.keys(val2).length !== 0) {
    loading.value = false
    const params = {
      id: data.id,
      ...videoVal.value,
      ...srtVal.value
    }
    console.log(params)
    uploadFlightUrl(params).then(({ code }) => {
      if (code !== 0) {
        remBtn.value = false
      }
    })
  }
})

// 视频和文件上传
const submitFile = async() => {
  if (Object.keys(videoRefs.value.data.fileList).length === 0 ||
    Object.keys(srtRefs.value.fileList).length === 0) {
    $message.warning('请选择视频和轨迹后再上传')
    return
  }

  loading.value = true
  remBtn.value = true
  videoVal.value = videoRefs.value.handleUploadStart()
  srtVal.value = await srtRefs.value?.startUpload()
}

</script>

<style lang="scss" scoped>
.head {
  margin: 20px;
  padding: 50px 10px 50px 30px;
  background-color: #fff;
}

.cont {
  margin: 20px;
  background-color: #fff;

  .title {
    margin: 20px;
    padding: 20px;
    font-size: 18px;
    font-weight: bold;
  }

  .btn {
    width: 110px;
    margin-left: calc(50% - 55px);
    margin-top: 10px;
    margin-bottom: 30px;
  }
}

:deep(.n-descriptions-header) {
  font-weight: bold;
  margin: 10px;
  padding: 20px 0;
  border-bottom: 1px solid rgba(240, 242, 245, 0.8);
}

:deep(.n-descriptions-table) {
  margin: 10px;
  padding: 10px;
}

:deep(.n-drawer-body-content-wrapper) {
  background-color: rgba(240, 242, 245, 1);
}

:deep(.n-form) {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  padding: 0 20px;
}

:deep(.n-form-item) {
  width: 230px;
  margin-right: 15px;
}

.note {
  :deep(.n-descriptions-table-wrapper), :deep(.n-descriptions-table) {
    margin-top: 0;
    padding-bottom: 10px;
    padding-top: 0;
  }
  :deep(.n-descriptions-table-content__content) {
    padding-right: 10px;
    text-indent: 2em;
  }
}

.uploads {

  :deep(.n-button__icon) {
    display: none;  // 隐藏删除按钮
  }
}
</style>
