<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="人员姓名" prop="personId">
          <el-select v-model="queryParams.personId" placeholder="请选择人员姓名" clearable @change="handleQueryPersonChange">
            <el-option v-for="person in personList" :key="person.id" :label="person.name" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="健康档案" prop="healthRecordId">
          <el-select v-model="queryParams.healthRecordId" placeholder="请选择健康档案" clearable>
            <el-option v-for="health in healthRecordList" :key="health.id" :label="health.name" :value="health.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用药类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择用药类型" @change="handleTypeChange" clearable>
            <el-option v-for="dict in mar_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="药品名称" prop="medicineId">
          <el-select v-model="queryParams.medicineId" placeholder="请选择药品名称" clearable>
            <el-option v-for="medicine in medicineList" :key="medicine.id" :label="medicine.shortNameBrandPackaging" :value="medicine.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="药品来源" prop="resource">
          <el-select v-model="queryParams.resource" placeholder="请选择药品来源" clearable>
            <el-option v-for="dict in mar_resource" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用药地点" prop="place">
          <el-select v-model="queryParams.place" placeholder="请选择用药地点" clearable>
            <el-option v-for="dict in mar_place" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用药时间" prop="time">
          <el-date-picker v-model="queryParams.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['health:marRecord:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['health:marRecord:remove']">删除</el-button>
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['health:marRecord:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading" height="calc(100% - 0.65rem)">
        <el-table v-loading="loading" :data="marRecordList" @selection-change="handleSelectionChange" height="calc(100% - 0.65rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="人员姓名" align="center" width="120" prop="personName" />
          <el-table-column label="健康档案" align="center" width="180" prop="healthRecordName" />
          <el-table-column label="用药名称" align="center" prop="name" />
          <el-table-column label="用药类型" align="center" width="180" prop="type">
            <template #default="scope">
              <dict-tag :options="mar_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="药品来源" width="100" align="center" prop="resource">
            <template #default="scope">
              <dict-tag :options="mar_resource" :value="scope.row.resource" />
            </template>
          </el-table-column>
          <el-table-column label="用药地点" align="center" width="100" prop="place">
            <template #default="scope">
              <dict-tag :options="mar_place" :value="scope.row.place" />
            </template>
          </el-table-column>
          <el-table-column label="用药时间" align="center" prop="dosingTime" width="180"> </el-table-column>
          <el-table-column label="用药剂量" align="center" width="100" prop="dosage" />
          <el-table-column label="用药单位" align="center" width="100" prop="unit">
            <template #default="scope">
              <dict-tag :options="medical_unit" :value="scope.row.unit" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination small background layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 添加或修改用药记录对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="marRecordRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="人员姓名" prop="personId">
          <el-select v-model="form.personId" placeholder="请选择人员姓名" @change="handlePersonChange">
            <el-option v-for="person in personList" :key="person.id" :label="person.name" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="健康档案" prop="healthRecordId">
          <el-select v-model="form.healthRecordId" placeholder="请选择健康档案" clearable>
            <el-option v-for="health in healthRecordList" :key="health.id" :label="health.name" :value="health.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用药类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择用药类型" @change="handleTypeChange">
            <el-option v-for="dict in mar_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品名称" prop="medicineId">
          <el-select v-model="form.medicineId" placeholder="请选择药品名称" @change="handleMedicineChange" clearable>
            <el-option v-for="medicine in medicineList" :key="medicine.id" :label="medicine.shortNameBrandPackaging" :value="medicine.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用药名称" v-show="false" prop="name">
          <el-input v-model="form.name" placeholder="请输入用药名称" />
        </el-form-item>
        <el-form-item label="药品来源" prop="resource">
          <el-select v-model="form.resource" placeholder="请选择药品来源">
            <el-option v-for="dict in mar_resource" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用药地点" prop="place">
          <el-select v-model="form.place" placeholder="请选择用药地点">
            <el-option v-for="dict in mar_place" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用药时间" prop="dosingTime">
          <el-date-picker clearable v-model="form.dosingTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择用药时间"> </el-date-picker>
        </el-form-item>
        <el-form-item label="用药剂量" prop="dosage">
          <el-input @change="handleDosageChange" v-model="form.dosage" placeholder="请输入用药剂量"
        /></el-form-item>
        <el-form-item label="用药单位" disabled prop="unit">
          <el-select v-model="form.unit" placeholder="请选择用药单位">
            <el-option v-for="dict in medical_unit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="false" label="含量" prop="content"> <el-input disabled v-model="form.content" placeholder="请输入含量" /></el-form-item>
        <el-form-item v-show="false" label="含量单位" prop="contentUnit">
          <el-select disabled v-model="form.contentUnit" placeholder="请选择含量单位">
            <el-option v-for="dict in content_unit" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看用药记录'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MarRecord">
import { listMarRecord, getMarRecord, delMarRecord, addMarRecord, updateMarRecord } from '@/api/health/marRecord'
import { listPerson, getPerson } from '@/api/health/person'
import { listHealthRecord } from '@/api/health/healthRecord'
import { listMedicineBasic, getMedicineBasic } from '@/api/health/medicineBasic'
import dayjs from 'dayjs'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { mar_type, mar_place, mar_resource, medical_unit, content_unit } = proxy.useDict('mar_type', 'mar_place', 'mar_resource', 'medical_unit', 'content_unit')

const marRecordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const personList = ref([])
const healthRecordList = ref([])
const medicineList = ref([])
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['health:marRecord:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['health:marRecord:edit'] },
  { id: 'copy', icon: 'Link', title: '复制', hasPermi: ['health:marRecord:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['health:marRecord:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    healthRecordId: null,
    time: '',
    dosage: null,
    personId: null,
    resource: null,
    place: null
  },
  queryPersonParams: {
    pageNum: 1,
    pageSize: 1000
  },
  queryHealthRecordParams: {
    pageNum: 1,
    personId: null,
    state: '1',
    pageSize: 1000
  },
  queryMedicineParams: {
    pageNum: 1,
    treatmentType: null,
    pageSize: 1000
  },
  rules: {
    medicineId: [{ required: true, message: '药品名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '用药类型不能为空', trigger: 'change' }],
    healthRecordId: [{ required: true, message: '健康档案不能为空', trigger: 'change' }],
    dosingTime: [{ required: true, message: '用药时间不能为空', trigger: 'blur' }],
    dosage: [{ required: true, message: '用药剂量不能为空', trigger: 'blur' }],
    resource: [{ required: true, message: '药品来源不能为空', trigger: 'blur' }],
    place: [{ required: true, message: '用药地点不能为空', trigger: 'blur' }],
    unit: [{ required: true, message: '用药单位不能为空', trigger: 'blur' }],
    personId: [{ required: true, message: '人员姓名不能为空', trigger: 'blur' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    case 'copy':
      handleCopy(row)
      break
    default:
      break
  }
}

const { queryParams, form, rules, queryPersonParams, queryHealthRecordParams, queryMedicineParams } = toRefs(data)

const handleDosageChange = (val) => {}

const handlePersonChange = (personId) => {
  queryHealthRecordParams.personId = personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
    if (response.rows.length > 0) {
      form.value.healthRecordId = healthRecordList.value[0].id
    }
  })
}
const handleQueryPersonChange = (personId) => {
  queryHealthRecordParams.personId = personId
  queryParams.value.healthRecordId = null
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
}

const handleTypeChange = (type) => {
  queryMedicineParams.value.treatmentType = type

  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicineList.value = response.rows
  })
}
const handleMedicineChange = (medicineId) => {
  getMedicineBasic(medicineId).then((response) => {
    form.value.name = response.data.name
    form.value.unit = response.data.unit
    form.value.contentUnit = response.data.contentUnit
  })
}

/** 查询成员管理列表 */
function getPersonList() {
  listPerson(queryPersonParams.value).then((response) => {
    personList.value = response.rows
    if (response.rows.length > 0) {
      listHealthRecord(queryHealthRecordParams).then((res) => {
        healthRecordList.value = res.rows
      })
    }
  })
}

/** 查询药品管理列表 */
function getMedicineList() {
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicineList.value = response.rows
  })
}

/** 查询用药记录列表 */
function getList() {
  loading.value = true
  const timeRange = queryParams.value.time
  let st = ''
  let et = ''
  if (timeRange && timeRange.length === 2) {
    st = dayjs(timeRange[0]).format('YYYY-MM-DD')
    et = dayjs(timeRange[1]).format('YYYY-MM-DD')
  }
  queryParams.value.startTime = st
  queryParams.value.endTime = et
  listMarRecord(queryParams.value).then((response) => {
    marRecordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  queryMedicineParams.value.treatmentType = null
  getMedicineList()
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    healthRecordId: null,
    dosingTime: null,
    dosage: null,
    personId: null,
    resource: '1',
    place: '1',
    medicineId: null,
    unit: null,
    content: '1',
    contentUnit: null
  }
  proxy.resetForm('marRecordRef')
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryMedicineParams.value.treatmentType = null
  getMedicineList()
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

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

// 查看
const handleView = (row) => {
  title.value = '查看用药记录'
  queryHealthRecordParams.personId = row.personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.dosingTime = dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss')
  if (personList.value.length > 0) {
    form.value.personId = personList.value[0].id
    queryHealthRecordParams.personId = personList.value[0].id
    listHealthRecord(queryHealthRecordParams).then((response) => {
      healthRecordList.value = response.rows
      if (response.rows.length > 0) {
        form.value.healthRecordId = healthRecordList.value[0].id
      }
    })
  }
  queryMedicineParams.value.treatmentType = null
  getMedicineList()
  open.value = true
  title.value = '添加用药记录'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  queryHealthRecordParams.personId = row.personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
  const _id = row.id || ids.value
  getMarRecord(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改用药记录'
  })
}

/** 复制按钮操作 */
function handleCopy(row) {
  reset()
  queryHealthRecordParams.personId = row.personId
  listHealthRecord(queryHealthRecordParams).then((response) => {
    healthRecordList.value = response.rows
  })
  const _id = row.id || ids.value
  getMarRecord(_id).then((response) => {
    form.value = response.data
    form.value.id = null
    form.value.dosingTime = dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss')
    open.value = true
    title.value = '复制用药记录'
  })
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delMarRecord(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'health/marRecord/export',
    {
      ...queryParams.value
    },
    `marRecord_${new Date().getTime()}.xlsx`
  )
}

getList()
getPersonList()
getMedicineList()
</script>
