<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="88px"
    >
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="选择巷道" prop="srmNumber">
        <el-select
          v-model="queryParams.srmNumber"
          placeholder="请选择巷道"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        >
        <el-option
            v-for="dict in streetList"
            :key="dict.plcId"
            :label="dict.name"
            :value="dict.plcId"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="随行工单号" prop="taskId">
        <el-input
          v-model="queryParams.taskId"
          placeholder="请输入随行工单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="方向" prop="fromDirection">
        <el-select
          v-model="queryParams.fromDirection"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        >
        <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DIRECTION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="列" prop="fromColumn">
        <el-input
          v-model="queryParams.fromColumn"
          placeholder="请输入列"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="层" prop="fromRow">
        <el-input
          v-model="queryParams.fromRow"
          placeholder="请输入层"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['logistics:order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['logistics:order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="随行工单号" align="center" prop="taskId" />
      <!-- <el-table-column label="巷道编码" align="center" prop="srmNumber" />
      <el-table-column label="方向" align="center" prop="fromDirection">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DIRECTION" :value="scope.row.fromDirection" />
        </template>
      </el-table-column>
      <el-table-column label="位置" align="center" prop="fromRow" >
        <template #default="scope">
          <space  >{{ scope.row.fromRow+'层-'+scope.row.fromColumn+'列' }}</space>
        </template>
      </el-table-column> -->
      <el-table-column label="位置" align="center" prop="row" >
        <template #default="scope">
          <space  >{{  position(scope.row)}}</space>
        </template>
      </el-table-column>
      
      
      <el-table-column label="图片" align="center" prop="pics" min-width="150">
        
        <template #default="scope">
          <div v-if="scope.row.pics"  class="image-cell-container">
            <el-image
              v-for="(pic, index) in scope.row.pics.split(';')"
              :key="index"
              :src="pic"
              style="width: 100px; height: 100px; margin-right: 10px;"
              :preview-src-list="[pic]"
              :initial-index="0"
			:preview-teleported="true"
              fit="cover"
              :disabled="true"
            />
          </div>
          <div v-else>
            无图片
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="时间" align="center" prop="row" min-width="30">
        <template #default="scope">
          <span v-if="scope.row.endTime">
      {{ formatTimeDiff(scope.row.startTime, scope.row.endTime) }}
    </span>
    <span v-else>
      未结束
    </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
          v-if="(scope.row.videoPath1 && scope.row.videoPath1.trim() !== '' ||
                scope.row.videoPath2 && scope.row.videoPath2.trim() !== '') &&
                scope.row.endTime" 
            link
            type="primary"
            @click="videoPlay(scope.row.videoPath1,scope.row.videoPath2)"
            v-hasPermi="['logistics:order:delete']"
          >
            视频
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['logistics:order:delete']"
          >
            删除
          </el-button>
         
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    
    <el-dialog v-model="dialogVisible" title="视频" width="500">
  <video v-if="video1Src" ref="videoPlayer1" width="100%" controls autoplay muted>
    <source :src="video1Src" type="video/mp4" />
    您的浏览器不支持 video 标签。
  </video>

  <video v-if="video2Src" ref="videoPlayer2" width="100%" controls autoplay muted>
    <source :src="video2Src" type="video/mp4" />
    您的浏览器不支持 video 标签。
  </video>
</el-dialog>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">

import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { StreetApi,StreetVO } from '@/api/logistics/street'
import download from '@/utils/download'
import { OrderApi, OrderVO } from '@/api/logistics/order'
import OrderForm from './OrderForm.vue'
import { log } from 'console'
import { da } from 'element-plus/es/locale'

/** 随行记录 列表 */
defineOptions({ name: 'Order' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化ist

const dialogVisible = ref(false)

const streetList = ref<StreetVO[]>([]) // 巷道队列

const loading = ref(true) // 列表的加载中
const list = ref<OrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  startTime: [],
  endTime: [],
  srmNumber: undefined,
  taskId: undefined,
  fromDirection: undefined,
  fromColumn: undefined,
  fromRow: undefined,
  fromSeparation: undefined,
  pics: undefined,
  trayCode: undefined,
  storageCode: undefined,
  toDirection: undefined,
  toColumn: undefined,
  toSeparation: undefined,
  toRow: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const video1Src = ref("") // 第一个视频
const video2Src = ref("") // 第二个视频
const videoPlayer1 = ref<HTMLVideoElement | null>(null)
const videoPlayer2 = ref<HTMLVideoElement | null>(null)
const videoPlay = (video1: string, video2: string) => {
  // 先关闭再打开对话框，确保能重新加载
  dialogVisible.value = false
  nextTick(() => {
    dialogVisible.value = true

    // 设置视频地址
    video1Src.value = video1
    video2Src.value = video2

    // 下一帧 DOM 更新后，手动调用 load()
    nextTick(() => {
      if (videoPlayer1.value) {
        videoPlayer1.value.load()
      }
      if (videoPlayer2.value) {
        videoPlayer2.value.load()
      }
    })
  })
}
/**
 * 计算两个时间之间的差值，并格式化为 分钟:秒
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @returns 格式化后的时间差字符串
 */
 const formatTimeDiff = (startTime: string, endTime: string): string => {
  const start = new Date(startTime).getTime();
  const end = new Date(endTime).getTime();
  const diffMs = end - start; // 毫秒差
  
  if (diffMs <= 0) return '0:00';
  
  const totalSeconds = Math.floor(diffMs / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};

/**
 * 计算位置string
 */
 const position = (row): string => {
  const from =row.fromSide==2?"库外": row.srmNumber+"-"+ (row.fromDirection?"左侧-":"右侧-")+ row.fromRow+'层-'+row.fromColumn+'列' +(row.fromSeparation==2?"深货位":"")
  const to = row.toSide==2?"库外":row.srmNumber+"-"+ (row.toDirection?"左侧-":"右侧-")+ row.toRow+'层-'+row.toColumn+'列' +(row.toSeparation==2?"深货位":"")
  return from+"->"+to;
};
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


/** 查询巷道列表 */
const getStringList =  () => {
 
  try {
    const data = StreetApi.getStreetList()
    data.then((res)=>{
      streetList.value = res
    })
    console.log(data);
    
    console.log(streetList);
    
  } finally {
    
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, '随行记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getStringList()
})
</script>
<style scoped>
.image-cell-container {
  overflow-x: auto;
  white-space: nowrap;
}

.image-cell-container::-webkit-scrollbar {
  height: 6px;
}

.image-cell-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}
</style>