<template>
  <el-dialog :model-value="visible" :width="width" title="驳回原因" @close="close()">
    <el-scrollbar wrap-class="el-dialog-body-full-scroll">
      <el-form label-position="top" class="pt-10px">
        <el-form-item class="is-required -mb-8px pl-20px" label="请选择退诊原因">
          <div class="w-0 flex-grow pl-20px">
            <div v-for="item in reasonGroup" :key="item.key">
              <el-checkbox :model-value="groupSelect[item.key]" :label="item.title" @update:model-value="toggle($event, item.key, item.list)">
                <span class="font-semibold text-black">{{ item.title }}</span>
              </el-checkbox>
              <div class="pl-15px">
                <el-checkbox-group v-model="reasons">
                  <div v-for="subItem in item.list">
                    <el-checkbox :key="subItem" :label="subItem" />
                  </div>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item class="mt-15px pl-20px" label="请他原因（补充说明）">
          <el-input v-model="otherReason" type="textarea" placeholder="请输入" resize="none" :autosize="{ minRows: 5, maxRows: 8 }" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" @click="close()">取消</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" @click="confirm()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { refundConsultation } from "@/api/hlw";

const emits = defineEmits(["close", "change", "refund"]);
const props = defineProps({
  ids: { type: Array, default: () => [] },
  visible: { type: Boolean, default: false },
  width: { type: [String, Number], default: "500px" },
  memberInfo: { type: Object, default: () => {} },
  order: { type: Object, default: () => {} },
});

const reasonGroup = [
  { title: "患者不符合复诊条件", list: ["患者未提供完整的病历资料", "患者病情变化、病情危急或病情复杂，需要线下复查"], key: "patient" },
  { title: "药物相关问题", list: ["需调整药方，建议线下就诊", "所需药品不在互联网医院开药范围", "患者药物过敏史不明确"], key: "drug" },
  { title: "患者资料不全", list: ["患者未填写完整的基本信息", "患者未提供最新病情描述"], key: "profile" },
  { title: "患者沟通问题", list: ["患者无法联系或未回复医生询问", "患者描述病情不清晰，无法判断"], key: "communication" },
  { title: "医生判断原因", list: ["依据现有病历资料依然无法明确诊断", "患者需多学科会诊，无法线上处理", "怀疑可能是传染病病例"], key: "doctor" },
  { title: "缺相关证明", list: ["缺少实体医疗机构诊断证明或三天内有效医嘱单"], key: "missing_proof" },
];
const loading = ref(false);
const reasons = ref([]);
const otherReason = ref("");
const groupSelect = computed(() =>
  reasonGroup.reduce((acc, cur) => {
    acc[cur.key] = cur.list.every((i) => reasons.value.includes(i));
    return acc;
  }, {})
);

function toggle(val, key, list) {
  const excludeReasons = reasons.value.filter((i) => !list.includes(i));
  if (val) {
    reasons.value = [...excludeReasons, ...list];
  } else {
    reasons.value = [...excludeReasons];
  }
}

function close() {
  emits("close");
}

async function confirm() {
  if (loading.value) return;
  const arr = [...reasons.value, otherReason.value.trim()].filter((i) => typeof i === "string" && i.trim());
  if (arr.length === 0) {
    ElMessage.error("请填写驳回原因");
  } else {
    loading.value = true;
    await ElMessageBox.confirm(`确定退诊并退款吗？`, "提示", { type: "warning" });
    await refund(arr);
    loading.value = false;
  }
}

async function refund(arr) {
  const reason = arr.join("，");
  const { orderSource } = props.order;
  const str = `本次问诊已取消，取消原因: ${reason}，${orderSource === "MATEPAD" ? "请联系线下退费" : "费用将于48小时内退还您的支付账户"}`;
  const { success, message } = await refundConsultation({ orderId: props.order.orderId, reason: str, orderSource });
  if (success) {
    emits("refund");
  } else {
    ElMessage.error(message);
  }
}

watch(
  () => props.visible,
  (n) => {
    if (n) {
      reasons.value = [];
      otherReason.value = "";
      loading.value = false;
    }
  }
);
</script>