<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间类型" prop="timeType">
        <el-select v-model="queryParams.timeType" placeholder="请选择时间类型" clearable>
          <el-option label="会诊时间" value="consultation" />
          <el-option label="申请时间" value="application" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="请选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="请选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="申请科室" prop="department">
        <el-input
          v-model="queryParams.department"
          placeholder="请输入申请科室"
          clearable
        />
      </el-form-item>
      <el-form-item label="申请医生" prop="requestingPhysician">
        <el-input
          v-model="queryParams.requestingPhysician"
          placeholder="请输入申请医生"
          clearable
        />
      </el-form-item>
      <el-form-item label="会诊状态" prop="consultationStatus">
        <el-select v-model="queryParams.consultationStatus" placeholder="请选择会诊状态" clearable>
          <el-option label="全部" value="" />
          <el-option label="新开" :value="0" />
          <el-option label="已提交" :value="10" />
          <el-option label="已确认" :value="20" />
          <el-option label="已签名" :value="30" />
          <el-option label="已完成" :value="40" />
          <el-option label="已取消" :value="50" />
        </el-select>
      </el-form-item>
      <el-form-item label="病人姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入病人姓名"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-printer" size="mini" @click="handlePrint">打印</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['consultation:request:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-document-checked"
          size="mini"
          :disabled="single"
          @click="handleSubmit"
          v-hasPermi="['consultation:request:submit']"
        >提交</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="single"
          @click="handleEnd"
          v-hasPermi="['consultation:request:end']"
        >结束</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleSave"
          v-hasPermi="['consultation:request:edit']"
        >保存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="急" align="center" prop="consultationUrgency" :formatter="urgentFormatter" />
      <el-table-column label="申请单号" align="center" prop="consultationId" />
      <el-table-column label="会诊时间" align="center" prop="consultationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.consultationDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邀请对象" align="center" prop="invitedObject" />
      <el-table-column label="申请科室" align="center" prop="department" />
      <el-table-column label="申请医师" align="center" prop="requestingPhysician" />
      <el-table-column label="申请时间" align="center" prop="consultationRequestDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.consultationRequestDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交" align="center" prop="consultationStatus">
        <template #default="scope">
          <el-switch
            v-model="scope.row.consultationStatus"
            :active-value="10"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleToggleSubmit(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="结束" align="center" prop="consultationStatus">
        <template #default="scope">
          <el-switch
            v-model="scope.row.consultationStatus"
            :active-value="40"
            :inactive-value="30"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="scope.row.consultationStatus !== 30"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['consultation:request:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['consultation:request:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['consultation:request:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 会诊申请单弹窗 -->
    <el-dialog :title="title" v-model="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请单号" prop="consultationId">
              <el-input v-model="form.consultationId" placeholder="系统自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间" prop="consultationRequestDate">
              <el-input v-model="form.consultationRequestDate" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="病人姓名" prop="patientName">
              <el-input v-model="form.patientName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="genderEnum">
              <el-input v-model="form.genderEnum" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会诊时间" prop="consultationDate">
              <el-date-picker
                v-model="form.consultationDate"
                type="datetime"
                placeholder="选择会诊时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="consultationUrgency">
              <el-checkbox v-model="form.consultationUrgency" true-label="紧急" false-label="一般">是否紧急</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请医师" prop="requestingPhysician">
              <el-input v-model="form.requestingPhysician" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请科室" prop="department">
              <el-input v-model="form.department" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="门诊诊断" prop="provisionalDiagnosis">
          <el-input v-model="form.provisionalDiagnosis" type="textarea" :rows="2" readonly />
        </el-form-item>
        <el-form-item label="会诊邀请对象" prop="invitedObject">
          <el-input v-model="form.invitedObject" type="textarea" :rows="2" placeholder="请选择会诊专家" />
        </el-form-item>
        <el-form-item label="会诊确认参加医师" prop="confirmingPhysicianParticipation">
          <el-input v-model="form.confirmingPhysicianParticipation" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="所属医生" prop="confirmingPhysicianName">
          <el-input v-model="form.confirmingPhysicianName" />
        </el-form-item>
        <el-form-item label="代表科室" prop="confirmingDepartmentName">
          <el-input v-model="form.confirmingDepartmentName" />
        </el-form-item>
        <el-form-item label="签名医生" prop="signature">
          <el-input v-model="form.signature" />
        </el-form-item>
        <el-form-item label="签名时间" prop="signatureDate">
          <el-input v-model="form.signatureDate" readonly />
        </el-form-item>
        <el-form-item label="病史及会诊目的" prop="consultationPurpose">
          <el-input v-model="form.consultationPurpose" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="会诊意见" prop="consultationOpinion">
          <el-input v-model="form.consultationOpinion" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ConsultationRequest">
import { listRequest, getRequest, delRequest, addRequest, updateRequest, submitRequest, cancelSubmitRequest, endRequest, cancelRequest } from "@/api/consultation/request";

const { proxy } = getCurrentInstance();
const requestList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(false);
const total = ref(0);
const title = ref("");
const open = ref(false);
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    timeType: 'consultation',
    startTime: null,
    endTime: null,
    department: null,
    requestingPhysician: null,
    consultationStatus: null,
    patientName: null
  },
  rules: {
    patientName: [
      { required: true, message: "病人姓名不能为空", trigger: "blur" }
    ],
    consultationDate: [
      { required: true, message: "会诊时间不能为空", trigger: "change" }
    ],
    invitedObject: [
      { required: true, message: "会诊邀请对象不能为空", trigger: "blur" }
    ],
    consultationPurpose: [
      { required: true, message: "病史及会诊目的不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询会诊申请列表 */
function getList() {
  loading.value = true;
  listRequest(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    requestList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryForm");
  handleQuery();
}

/** 重置表单 */
function reset() {
  form.value = {
    id: null,
    consultationId: null,
    patientId: null,
    encounterId: null,
    orderId: null,
    patientName: null,
    patientBusNo: null,
    patientIdentifierNo: null,
    genderEnum: null,
    age: null,
    department: null,
    departmentId: null,
    requestingPhysician: null,
    requestingPhysicianId: null,
    consultationRequestDate: null,
    invitedObject: null,
    consultationDate: null,
    consultationPurpose: null,
    provisionalDiagnosis: null,
    consultationOpinion: null,
    consultationStatus: 0,
    consultationUrgency: '一般',
    confirmingPhysician: null,
    confirmingPhysicianId: null,
    confirmingDate: null,
    signature: null,
    signaturePhysicianId: null,
    signatureDate: null,
    cancelNatureDate: null,
    cancelReason: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    tenantId: null,
    isDeleted: 0,
    remark: null,
    consultationActivityId: null,
    consultationActivityName: null,
    confirmingPhysicianName: null,
    confirmingDepartmentName: null,
    confirmingPhysicianParticipation: null
  };
  proxy.resetForm("form");
}

/** 格式化紧急标识 */
function urgentFormatter(row, column, cellValue) {
  return cellValue === '紧急' ? '✓' : '';
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加会诊申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getRequest(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改会诊申请";
  });
}

/** 查看按钮操作 */
function handleView(row) {
  reset();
  const id = row.id;
  getRequest(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看会诊申请";
    // 设置为只读模式
  });
}

/** 提交按钮操作 */
function handleSubmit() {
  const id = ids.value[0];
  if (id) {
    submitRequest(id).then(response => {
      proxy.$modal.msgSuccess(response.msg || "提交成功");
      getList();
    });
  } else {
    proxy.$modal.msgError("请选择要提交的会诊申请");
  }
}

/** 结束按钮操作 */
function handleEnd() {
  const id = ids.value[0];
  if (id) {
    endRequest(id).then(response => {
      proxy.$modal.msgSuccess(response.msg || "结束成功");
      getList();
    });
  } else {
    proxy.$modal.msgError("请选择要结束的会诊申请");
  }
}

/** 保存按钮操作 */
function handleSave() {
  proxy.$refs["form"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRequest(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRequest(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除会诊申请编号为"' + ids + '"的数据项？').then(function() {
    return delRequest(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 提交/取消提交切换 */
function handleToggleSubmit(row) {
  if (row.consultationStatus === 10) {
    // 取消提交
    cancelSubmitRequest(row.id).then(response => {
      proxy.$modal.msgSuccess(response.msg || "取消提交成功");
      getList();
    });
  } else {
    // 提交
    submitRequest(row.id).then(response => {
      proxy.$modal.msgSuccess(response.msg || "提交成功");
      getList();
    });
  }
}

/** 打印按钮操作 */
function handlePrint() {
  // 实现打印功能
  proxy.$modal.msgSuccess("打印功能待实现");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["form"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRequest(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRequest(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>