<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" />
          <input-filter v-model="queryForm.mobile" label="手机号" placeholder="请输入手机号" :width="240" />
          <radio-filter v-model="queryForm.status" label="处理状态" :list="statusOptions" :width="120" />
        </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>
        </div>
      </div>
      <div class="mt-5px py-10px px-15px flex justify-between items-center text-16px border-t border-gray-200">
        <div>未处理：<span class="text-red-500">{{count}}</span></div>
        <el-button type="primary" plain @click="fetchRefundList">刷新数据</el-button>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <!-- <div class="mb-10px">
        <span>未处理：</span>
        <span style="color: red;">{{ unhandledCount }}</span>
      </div> -->
      <el-table v-loading="loading" border ref="tableRef" height="100%" :data="list">
        <el-common-column prop="name" label="患者" :width="120" />
        <el-common-column prop="mobile" label="手机号" :width="140" />
        <el-common-column prop="applyTime" label="申请退费时间" :width="180" />
        <el-common-column prop="reason" label="申请退费原因" :width="180">
          <template #default="{row}">
            <el-tooltip placement="top" effect="light" popper-class="max-w-480px" :content="row.reason">
              <span>{{ row.reason }}</span>
            </el-tooltip>
          </template>
        </el-common-column>
        <el-common-column prop="statusText" label="处理状态" :width="100">
          <template #default="{ row }">
            <el-tooltip :disabled="row.status!=='REJECT'" placement="top" popper-class="max-w-480px">
              <template #content>
                拒绝理由：<br />{{ row.rejectReason }}
              </template>
              <div>
                <span :class="statusColorMap[row.status]">{{ statusMap[row.status] }}</span>
                <el-icon v-if="row.status=='REJECT'" class="ml-5px text-gray-500 transform translate-y-2px"
                  style="cursor:pointer;">
                  <InfoFilled />
                </el-icon>
              </div>
            </el-tooltip>
          </template>
        </el-common-column>
        <el-common-column prop="handleTime" label="处理时间" :width="180" />
        <el-table-column fixed="right" label="操作" :width="160">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer mr-10px" @click="viewOrder(row)">订单详情</el-text>
            <el-text v-if="row.status === 'INIT'" type="primary" class="cursor-pointer mr-10px"
              @click="agree(row)">同意</el-text>
            <el-text v-if="row.status === 'INIT'" type="danger" class="cursor-pointer" @click="reject(row)">拒绝</el-text>
          </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>
  <reject-modal :data="data" :visible="visible" :width="width" @close="close" @change="search" />
  <order-drawer showChatHistoryBtn showRxBtn :visible="orderVisible" :order="order" @close="orderVisible = false"
    @viewChatHistory="viewChatLogs()" />
  <chat-history-drawer :orderId="order ? order.orderId:''" :doctorCode="order ? order.doctorCode:''"
    :visible="chatVisible" :doctor-name="order.doctorName" :patient-name="order.name" @close="chatVisible = false" />
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { storeToRefs } from 'pinia'
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import { getRefundOrderList, handleRefundOrder, getPatientOrder } from "@/api/hlw";
import { memberStore } from "@/store/member";
import useModal from '@/hooks/useModal';

import { ArrowUpBold, ArrowDownBold, InfoFilled } from "@element-plus/icons-vue";
import { InputFilter, expandFilterBox, RadioFilter } 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 rejectModal from "./reject-modal.vue";
import orderDrawer from "@/components/order-drawer/order-drawer.vue";
import chatHistoryDrawer from "@/components/chat-history-drawer/chat-history-drawer.vue";

const list = ref([]);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const count = ref(0);
const loading = ref(false);
const canExpand = ref(true);
const expand = ref(false);
const unhandledCount = ref(0);
const { memberInfo } = storeToRefs(memberStore());
const { close, show, visible, width } = useModal(560);
const data = ref({});
const orderVisible = ref(false)
const order = ref({})

const params = ref({})
const statusMap = {
  INIT: '未处理',
  PASS: '已同意',
  REJECT: '已拒绝'
}
const statusColorMap = {
  INIT: 'text-red-500',
  PASS: 'text-green-500',
  REJECT: 'text-blue-500'
}

const queryForm = ref({
  name: "",
  mobile: "",
  status: ""
});


const statusOptions = Object.keys(statusMap).map(key => ({
  label: statusMap[key],
  value: key
}));
const chatVisible = ref(false);

function clear() {
  queryForm.value = { name: "", mobile: "", status: "" };
  search();
}

function search() {
  params.value = { ...queryForm.value };
  // ...请求数据逻辑...
  fetchRefundList();
}

async function fetchRefundList() {
  loading.value = true;
  const res = await getRefundOrderList({ ...params.value, page: page.value, pageSize: pageSize.value, doctorCode: memberInfo.value.doctorNo });
  loading.value = false;
  list.value = res && res.data && Array.isArray(res.data.list) ? res.data.list.map(i => ({
    ...i,
    status: i.refundInfo && i.refundInfo.status ? i.refundInfo.status : '',
    reason: i.refundInfo && i.refundInfo.reason ? i.refundInfo.reason : '',
    rejectReason: i.refundInfo && i.refundInfo.rejectReason ? i.refundInfo.rejectReason : '',
    applyTime: i.refundInfo && i.refundInfo.createTime ? dayjs(i.refundInfo.createTime).format("YYYY-MM-DD HH:mm") : '',
    handleTime: i.refundInfo && i.refundInfo.updateTime ? dayjs(i.refundInfo.updateTime).format("YYYY-MM-DD HH:mm") : '-',

  })) : [];
  total.value = res && res.data && res.data.total ? res.data.total : 0;
  count.value = res && res.data && res.data.count ? res.data.count : 0;
}

async function viewOrder(row) {
  const { success, message, data } = await getPatientOrder({ orderId: row.orderId });
  console.log(data)
  if (data && data.data) {
    order.value = data.data;
    orderVisible.value = true;
  } else {
    ElMessage.error(message || "获取订单详情失败");
  }
}
async function agree(row) {
  await ElMessageBox.confirm("是否同意退款？", "提示", {
    confirmButtonText: "同意",
    cancelButtonText: "取消",
    type: "warning",
  });
  loading.value = true;
  const res = await handleRefundOrder({ id: row._id, orderId: row.orderId, status: "PASS", doctorCode: memberInfo.value.doctorNo, operatorId: memberInfo.value._id, operator: memberInfo.value.anotherName });
  loading.value = false;
  if (res.success) {
    ElMessage.success(res.message);
    search();
  } else if (res.data && res.data.errType == 'HIS_REFUND_FAIL') {
    ElMessage.error(res.message)
    autoReject(row, res.message);
  } else {
    ElMessage.error(res.message)
  }
}
async function autoReject(row, reason) {
  loading.value = true;
  const res = await handleRefundOrder({ id: row._id, orderId: row.orderId, status: "REJECT", doctorCode: memberInfo.value.doctorNo, operatorId: memberInfo.value._id, operator: memberInfo.value.anotherName, reason });
  loading.value = false;
  if (res.success) {
    // ElMessage.success(res.message);
    search();
  } else {
    ElMessage.error(res.message || "自动拒绝失败，请手动处理");
  }
}
function reject(row) {
  // ...拒绝逻辑...
  data.value = { ...row };
  show()
}

function changeSize(val) {
  pageSize.value = val;
  search();
}
function changePage(val) {
  page.value = val;
  search();
}
function viewChatLogs() {
  chatVisible.value = true;
}

onMounted(() => {
  search();
});
</script>
