<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="200" 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 { auditDiagnosis } from "@/api/hlw.js";

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

const reasonGroup = [
  { title: "诊断不合格", list: ["部分药品缺少适应症", "诊断与药品适应症不符", "诊断与用药人年龄或性别不符"], key: "diagnosis" },
  { title: "用法用量不合格", list: ["单次剂量或给药频次不适宜", "给药途径不适宜", "药品总量超量"], key: "usage" },
  { title: "用药禁忌", list: ["重复用药", "药物配伍禁忌", "儿童或未成人禁用", "肝、肾功能异常禁用", "备孕、孕期、哺乳期禁用", "过敏史、既往史禁用"], key: "medication" },
  { 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 {
    await ElMessageBox.confirm(`确定审核不通过吗？`, "提示", { type: "warning" });
    loading.value = true
    const { success, message, data } = await auditDiagnosis({
      ids: props.ids,
      status: "UNPASS",
      reasons: arr,
      pharmacistNo: props.memberInfo.workNo,
      pharmacist: props.memberInfo.anotherName,
    });
    loading.value = false
    const failList = data && Array.isArray(data.failList) ? data.failList : [];
    if (failList.lenght) {
      ElMessage.error(failList[0].message);
      return
    }
    if (success) {
      ElMessage.success(message);
      close();
      emits("change");
    } else {
      ElMessage.error(message);
    }
  }
}

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