<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="screeningTime">
              <el-date-picker v-model="screeningTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
            </el-form-item>
            <el-form-item label="看诊类型" prop="visitType">
              <el-select v-model="queryParams.visitType" placeholder="请选择" clearable>
                <el-option v-for="item in treatment_user_type" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="筛查类型" prop="configId">
              <div>
                <el-select v-model="queryParams.configId" placeholder="请选择" clearable>
                  <el-option v-for="item in screeningAssessmentConfigList" :key="item.configId" :label="item.name" :value="item.configId" />
                </el-select>
              </div>
            </el-form-item>
            <el-form-item prop="patientNo">
              <el-input v-model="queryParams.patientNo" placeholder="姓名/门诊号/住院号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:screening:add']">新增营养筛查</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:screening:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:screening:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:screening:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="screeningList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="时间" align="center" prop="screeningTime"  />
        <el-table-column label="看诊类型" align="center" prop="visitType" />
        <el-table-column label="门诊/住院号" align="center" prop="patientNo" />
        <el-table-column label="营养筛查类型" align="center" prop="configName" />
        <el-table-column label="营养筛查分数" align="center" prop="screeningScore" />
        <el-table-column label="营养筛查结论" align="center" prop="screeningConclusion" />
        <el-table-column label="支付状态" align="center" prop="paymentStatus" />
        <el-table-column label="筛查医生/护士" align="center" prop="createByName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
            </el-tooltip>
            <!-- <el-tooltip content="打印" placement="top">
              <el-button link type="primary" icon="Print" @click="handleUpdate(scope.row)">打印</el-button>
            </el-tooltip> -->
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:screening:remove']">删除</el-button>
            </el-tooltip>
          </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-card>
    <!-- 添加或修改营养筛查对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <div class="screening-type-grid">
            <el-button
              v-for="item in screeningAssessmentConfigList"
              :key="item.configId"
              type="primary"
              plain 
              class="screening-type-btn"              
              @click="handleScreeningSelect(item.configId)"
              style="width: 350px;margin-left:0px">            
              {{ item.name }}
            </el-button>
          </div>       
    </el-dialog>
  </div>
</template>

<script setup name="Screening" lang="ts">
import { listScreening, getScreening, delScreening, addScreening, updateScreening } from '@/api/patients/screening';
import { ScreeningVO, ScreeningQuery, ScreeningForm } from '@/api/patients/screening/types';
import { listScreeningAssessmentConfig } from '@/api/system/screeningAssessmentConfig';
import { ScreeningAssessmentConfigQuery,ScreeningAssessmentConfigVO } from '@/api/system/screeningAssessmentConfig/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { treatment_user_type } = toRefs<any>(proxy?.useDict('treatment_user_type'));

const screeningTime = ref<[DateModelType, DateModelType]>(['', '']);
const screeningList = ref<ScreeningVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const screeningAssessmentConfigList = ref<ScreeningAssessmentConfigVO[]>([]);
const router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const screeningFormRef = ref<ElFormInstance>();
const { patientInfo } = defineProps<{ patientInfo: any }>()
const emit = defineEmits(['change'])

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ScreeningForm = {
  id: undefined,
  patientId: undefined,
  configId: undefined,
  screeningTime: undefined,
  visitType: undefined,
  patientNo: undefined,
  screeningScore: undefined,
  screeningConclusion: undefined,
  paymentStatus: undefined,
  status: undefined,
}
const data = reactive<PageData<ScreeningForm, ScreeningQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientId: undefined,
    configId: undefined,
    screeningTime: undefined,
    visitType: undefined,
    patientNo: undefined,
    screeningScore: undefined,
    screeningConclusion: undefined,
    paymentStatus: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    configId: [
      { required: true, message: "营养筛查类型不能为空", trigger: "blur" }
    ],
    screeningTime: [
      { required: true, message: "筛查时间不能为空", trigger: "blur" }
    ],
    visitType: [
      { required: true, message: "看诊类型不能为空", trigger: "change" }
    ],
    patientNo: [
      { required: true, message: "门诊/住院号不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询筛查/评估配置列表 */
const getScreeningConfigList = async () => {
  let param=ref<ScreeningAssessmentConfigQuery>({
    pageNum: 1,
    type: '1',
    pageSize: -1,
  });
  const res = await listScreeningAssessmentConfig(param.value);
  screeningAssessmentConfigList.value = res.rows;   
}

/** 查询营养筛查列表 */
const getList = async () => {
  loading.value = true;    
  queryParams.value.patientId= patientInfo.id; 
  const res = await listScreening(proxy?.addDateRange(queryParams.value, screeningTime.value));
  screeningList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  screeningFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "选择营养筛查";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ScreeningVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getScreening(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改营养筛查";
}

const handleView = async (row?: ScreeningVO) => {
  emit('change', 'nutritionScreeningAdd',window.btoa(row.id.toString()))
}


/** 提交按钮 */
const submitForm = () => {
  screeningFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateScreening(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addScreening(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ScreeningVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除营养筛查编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delScreening(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/screening/export', {
    ...queryParams.value
  }, `screening_${new Date().getTime()}.xlsx`)
}

const handleScreeningSelect = (configId:number) => {   
  emit('change', 'nutritionScreeningAdd',configId)
} 

function formatDate(date) {
  const pad = n => n < 10 ? '0' + n : n;
  return date.getFullYear() + '-' +
    pad(date.getMonth() + 1) + '-' +
    pad(date.getDate())   ;
}

onMounted(() => {
  getList();
  getScreeningConfigList(); 
  
  let now=new Date();
  let start=formatDate(now);
  let end=formatDate(new Date(now.getTime()-24*60*60*1000*30));
  screeningTime.value=[end+' 00:00:00',start+' 23:59:59'];  
});
</script>

<style scoped>
.screening-type-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.screening-type-btn {
  font-weight: normal;
  font-size: 16px;
  height: 48px;
  border-radius: 8px;  
}
</style>
