<template>
  <my-layout>
    <layout-item class="bg-white">
      <div class="py-5px flex" @keyup.enter="search()">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="true" class="flex-grow" :expand="expand">
          <input-filter v-model="queryForm.name" label="患者名称" placeholder="请输入搜索内容" :width="240" />
          <check-box-filter filterable placeholder="搜索医生" v-if="!doctorView" v-model="queryForm.doctorCodes" label="开方医生" :list="doctors"
            :width="200" />
          <date-range-filter v-model:dates="queryForm.dates" label="下单时间" :text="orderDatesText" :width="240"
            :showShortcuts="false" />
          <radio-filter v-model="queryForm.orderType" :list="orderTypes" label="问诊类型" :width="200" />
          <custom-filter label="来源" :width="360">
            <el-select v-model="queryForm.storeIds" class="w-full" placeholder="全部" clearable filterable multiple
              collapse-tags :filter-method="filterMethod">
              <el-option v-for="i in options" :key="i._id" :label="i.showLabel" :value="i.value">{{i.label}}</el-option>
            </el-select>
          </custom-filter>
          <radio-filter v-model="queryForm.orderSource" label="终端" :list="sourceList" :width="200" />
          <radio-filter v-model="queryForm.orderStatus" label="状态" :list="statusOptions" />
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button v-if="canExpand" text plain @click="expand = !expand">
            <span class="mr-5px">{{ expand ? "收起筛选" : "更多筛选" }}</span>
            <el-icon v-if="expand">
              <ArrowUpBold />
            </el-icon>
            <el-icon v-else>
              <ArrowDownBold />
            </el-icon>
          </el-button>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button plain @click="clear()">重置</el-button>
          <el-button type="success" @click="download">导出Excel</el-button>
        </div>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table v-loading="loading" border ref="tableRef" height="100%" :data="list"
        @selection-change="handleSelectionChange">
        <!-- ...如需多选可加 selection 列... -->
        <el-common-column prop="status" label="状态" :width="100">
          <template #default="{ row }">
            <span :style="{color:row.statusColor}">{{ row.statusText }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="name" label="患者" :width="120">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer" @click="viewArchive(row)">{{ row.name }}</el-text>
          </template>
        </el-common-column>
        <el-common-column prop="doctorName" label="医生" :width="120" />
        <el-common-column prop="deptName" label="科室" :width="120" />
        <el-common-column prop="orderTime" label="下单时间" :width="160" />
        <el-common-column prop="orderType" label="问诊类型" :width="120" />
        <el-common-column prop="drugStoreName" label="来源" :width="180" />
        <el-common-column prop="platform" label="终端" :width="120" />
        <el-common-column prop="orderId" label="订单号" :width="160" />
        <el-table-column fixed="right" type="action" label="操作" :width="180">
          <template #default="{ row }">
            <div class="flex items-center whitespace-nowrap">
              <el-text type="primary" class="cursor-pointer mr-10px" @click="viewDetails(row)">详情</el-text>
              <el-text type="primary" class="cursor-pointer" @click="viewChatLogs(row)">会话记录</el-text>
              <el-tooltip v-if="row.videoRecordCount > 0" content="视频问诊回放" placement="top">
                <img
                  class="ml-10px cursor-pointer video-playback-icon"
                  src="/icons/hlw-video-playback.svg"
                  alt="视频问诊回放"
                  @click.stop="openVideoRecords(row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </layout-item>
  </my-layout>
  <archive-drawer :patient="patient || {}" :visible="archiveVisible" @close="archiveVisible = false" />
  <chat-history-drawer :orderId="current ? current.orderId:''" :doctorCode="current ? current.doctorCode:''"
    :visible="chatVisible" :doctor-name="current ? current.doctorName :''" :patient-name="current ? current.name :''"
    @close="chatVisible = false" />
  <order-drawer showChatHistoryBtn showRxBtn :visible="orderVisible" :order="current" @close="orderVisible = false"
    @viewChatHistory="viewChatLogs(current)" />

  <!-- 视频问诊回放：多条列表弹窗 -->
  <el-dialog v-model="videoListVisible" title="视频问诊回放" width="720px">
    <el-table v-loading="videoLoading" border :data="videoList" height="360px">
      <el-common-column prop="createdAtText" label="录制时间" :width="180" />
      <el-common-column prop="durationText" label="时长" :width="100" />
      <el-table-column label="操作" :width="100">
        <template #default="{ row }">
          <el-button text type="primary" @click="playVideo(row)">播放</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="videoListVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 视频播放弹窗 -->
  <el-dialog v-model="videoPlayVisible" title="视频问诊回放播放" width="900px" @closed="currentVideoUrl = ''">
    <video v-if="currentVideoUrl" controls autoplay style="width: 100%; max-height: 70vh" :src="currentVideoUrl"></video>
    <div v-else class="text-gray-500">暂无可播放视频</div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { dayjs, ElMessage } from "element-plus";
import { useHlw, getDrugStoreOptions, downloadExcel, getAllDoctorNos, getMrtcRecordList } from "@/api/hlw";
import useElPagination from "@/hooks/useElPagination";
import OrderSource, { sourceList } from '@/baseData/source'
import { getStatus, statusOptions } from '@/utils/hlw-order';
import { memberStore } from "@/store/member";

import { ArrowUpBold, ArrowDownBold } from "@element-plus/icons-vue";
import { InputFilter, expandFilterBox, RadioFilter, CheckBoxFilter, DateRangeFilter, CustomFilter } from "@/components/filter-bar";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import archiveDrawer from "@/components/archive-drawer/archive-drawer.vue";
import chatHistoryDrawer from "@/components/chat-history-drawer/chat-history-drawer.vue";
import orderDrawer from "@/components/order-drawer/order-drawer.vue";

const { list, page, pageSize, total, changePage, changeSize } = useElPagination(fetchOrders);
const props = defineProps({
  doctorView: {
    type: Boolean,
    default: false
  }
});

const today = dayjs().format("YYYY-MM-DD");
const queryForm = ref({
  name: "",
  doctorCodes: [],
  dates: [today, today],
  orderType: "",
  storeIds: "",
  orderSource: "",
  orderStatus: ""
});
const params = ref({});
const patient = ref({});
const archiveVisible = ref(false);
const storeList = ref([]);
const storename = ref('')
const orderVisible = ref(false);
const orderTypes = ref([
  { label: '在线复诊', value: 'im' },
  { label: '在线续方', value: 'pres' },
  { label: '在线配药', value: 'onlineMedicinePurchase' },
  { label: '中药饮片', value: 'wineConsult' },
]);
const loading = ref(false);
const canExpand = ref(true);
const expand = ref(false);
const doctors = ref([]);
const options = computed(() => storeList.value.filter(i => i.label.includes(storename.value.trim())))
const orderDatesText = computed(() => queryForm.value.dates.length > 0 ? `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}` : "全部");
const { memberInfo } = storeToRefs(memberStore());
const current = ref(null);
const chatVisible = ref(false);

// 视频问诊回放弹窗状态
const videoListVisible = ref(false);
const videoPlayVisible = ref(false);
const videoLoading = ref(false);
const videoList = ref([]);
const currentVideoUrl = ref("");

function clear() {
  queryForm.value = {
    name: "",
    doctorCodes: [],
    dates: [],
    orderType: "",
    storeIds: "",
    orderSource: "",
    orderStatus: ""
  };
  search();
}

function search() {
  params.value = {
    name: queryForm.value.name,
    doctorCodes: queryForm.value.doctorCodes,
    storeIds: queryForm.value.storeIds,
    orderSource: queryForm.value.orderSource,
  }
  if (queryForm.value.dates.length) {
    params.value.startDate = queryForm.value.dates[0];
    params.value.endDate = queryForm.value.dates[1];
  }
  if (queryForm.value.orderType) {
    if (queryForm.value.orderType === 'pres') params.value.isPres = true
    if (queryForm.value.orderType === 'im') params.value.isPres = false
    if (queryForm.value.orderType === 'onlineMedicinePurchase') params.value.consultType = 'onlineMedicinePurchase'
  }
  if (params.value.consultType === 'onlineMedicinePurchase') {
    delete params.value.storeIds;
  }
  if (queryForm.value.orderStatus) {
    params.value.orderStatus = queryForm.value.orderStatus
  }
  if (props.doctorView) {
    params.value.doctorCodes = [memberInfo.value.doctorNo || '']
    params.value.isDoctorView = true;
  }
  page.value = 1;
  fetchOrders();
}

function viewArchive(row) {
  patient.value = row;
  archiveVisible.value = true;
}

async function fetchOrders() {
  loading.value = true;
  const { success, data, message } = await useHlw({ type: 'getHlwOrderList', ...params.value, page: page.value, pageSize: pageSize.value });
  list.value = Array.isArray(data.list) ? data.list.map(i => {
    if (i.orderStatus == 'pending' && i.payStatus === 'pending' && i.payExpireTime < Date.now()) {
      i.orderStatus = 'cancelled';
    }
    const { text, color } = getStatus(i);
    const isOnlineMedicinePurchase = i.consultType === 'onlineMedicinePurchase';
    return {
      ...i,
      orderTime: dayjs(i.createTime).format("YYYY-MM-DD HH:mm"),
      orderType: isOnlineMedicinePurchase ? '在线配药' : (i.preOrderId ? '在线续方' : '在线复诊'),
      drugStoreName: isOnlineMedicinePurchase ? '—' : (i.drugStoreName || ''),
      platform: OrderSource[i.orderSource] || '',
      statusText: text,
      statusColor: color,
    }
  }) : []
  total.value = data.total || 0;
  if (!success) {
    ElMessage.error(message);
  }
  loading.value = false;
}

async function getStores() {
  const { data } = await getDrugStoreOptions();
  storeList.value = data && Array.isArray(data.list) ? data.list.map(i => ({
    label: i.name,
    showLabel: typeof i.name === 'string' && i.name.length > 10 ? i.name.slice(0, 10) + '...' : i.name,
    _id: i._id,
    value: i.store_id
  })).slice(0, 120) : []
}

function viewDetails(row) {
  // ...详情逻辑...
  current.value = row;
  orderVisible.value = true;
}
function viewChatLogs(row) {
  // ...会话记录逻辑...
  current.value = row;
  chatVisible.value = true;
}

function normalizeVideoRecord(rec) {
  const startAt = rec.startAt || rec.createdAt || 0;
  const endAt = rec.endAt || 0;
  const durationMs = endAt && startAt && endAt > startAt ? endAt - startAt : 0;
  return {
    ...rec,
    createdAtText: startAt ? dayjs(startAt).format("YYYY-MM-DD HH:mm") : "-",
    durationText: durationMs ? `${Math.round(durationMs / 1000)}s` : "-",
  };
}

async function openVideoRecords(order) {
  if (!order || !order.orderId) return;
  videoLoading.value = true;
  try {
    const { success, data, message } = await getMrtcRecordList({
      orderId: order.orderId,
      onlyPlayable: true,
    });
    const rawList = (data && data.list) || (data && data.data && data.data.list) || [];
    videoList.value = Array.isArray(rawList) ? rawList.map(normalizeVideoRecord) : [];
    if (!success) {
      ElMessage.error(message || "获取视频回放失败");
      return;
    }
    if (videoList.value.length === 1) {
      playVideo(videoList.value[0]);
    } else if (videoList.value.length > 1) {
      videoListVisible.value = true;
    } else {
      ElMessage.warning("暂无可播放的视频问诊回放");
    }
  } finally {
    videoLoading.value = false;
  }
}

function playVideo(rec) {
  currentVideoUrl.value = rec.playUrl || rec.fileUrl || rec.filePath || "";
  if (!currentVideoUrl.value) {
    ElMessage.warning("视频地址缺失，无法播放");
    return;
  }
  videoListVisible.value = false;
  videoPlayVisible.value = true;
}
async function download() {
  // console.log(params.value)
  const payload = { ...params.value, type: 'downloadOrder' };
  if (Array.isArray(params.value.storeIds)) {
    payload.storeIds = params.value.storeIds.join(',')
  }
  console.log(payload)
  downloadExcel(payload)
}

function handleSelectionChange() {
  // ...如需多选可实现
}

function filterMethod(val) {
  storename.value = val
}

async function getDoctors() {
  const { data } = await getAllDoctorNos();
  doctors.value =
    data && data.data && Array.isArray(data.data)
      ? data.data.map((i) => ({
        label: i.doctorName,
        value: i.doctorNo,
      }))
      : [];
}

onMounted(() => {
  search();
  getStores()
  if (!props.doctorView) {
    getDoctors()
  }
});
</script>

<style scoped>
.video-playback-icon {
  width: 20px;
  height: 20px;
  display: inline-block;
}
</style>
