<template>
  <div class="commonly-drug-page">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" @submit.native.prevent>
        <el-form-item label="药品名称">
          <el-input
            v-model="searchForm.drugName"
            placeholder="请输入药品名称"
            clearable
            @keyup.enter.native="fetchList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchList">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增常用药品</el-button>
    </div>

    <!-- 药品列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="drugName" label="药品名称" min-width="120"></el-table-column>
        <el-table-column prop="drugSpec" label="规格" min-width="100"></el-table-column>
        <el-table-column prop="usageMethod" label="用法" min-width="100"></el-table-column>
        <el-table-column prop="usageFrequencyUnit" label="频次" min-width="80"></el-table-column>
        <el-table-column prop="usagePerUseCount" label="每次用药数量" min-width="90"></el-table-column>

        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" size="small" style="color: #f56c6c" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size.sync="pageSize"
        :current-page.sync="pageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="drugForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="form.drugName" placeholder="请输入药品名称"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="drugSpec">
          <el-input v-model="form.drugSpec" placeholder="请输入规格"></el-input>
        </el-form-item>
        <el-form-item label="用法" prop="usageMethod">
          <el-input v-model="form.usageMethod" placeholder="如：口服、外用等"></el-input>
        </el-form-item>
        <el-form-item label="频次" prop="usageFrequencyUnit">
          <el-input v-model="form.usageFrequencyUnit" placeholder="如：每日3次"></el-input>
        </el-form-item>
        <el-form-item label="每次用药数量" prop="usagePerUseCount">
          <el-input v-model="form.usagePerUseCount" placeholder="请输入数量"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCommonDrugList,
  addCommonDrug,
  editCommonDrug,
  deleteCommonDrug
} from '@/api/commonlyDrug'

export default {
  name: 'CommonlyDrug',
  data() {
    return {
      // 分页
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      tableData: [],

      // 搜索
      searchForm: {
        drugName: ''
      },

      // 弹窗
      dialogVisible: false,
      isEdit: false,
      form: {
        commonDrugId: null,
        drugName: '',
        drugSpec: '',
        usageMethod: '',
        usageFrequencyUnit: '',
        usagePerUseCount: ''
      },
      rules: {
        drugName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
        usageMethod: [{ required: true, message: '请输入用法', trigger: 'blur' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑常用药品' : '新增常用药品'
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    // 获取列表
    async fetchList() {
      this.loading = true
      try {
        const res = await getCommonDrugList({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          drugName: this.searchForm.drugName || undefined
        })
        const page = res.data
        this.tableData = page.list || []
        this.total = page.total || 0
      } catch (error) {
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.drugName = ''
      this.pageNum = 1
      this.fetchList()
    },

    // 分页事件
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchList()
    },

    // 新增
    handleAdd() {
      this.isEdit = false
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.drugForm.resetFields()
      })
    },

    // 编辑
    handleEdit(row) {
      this.isEdit = true
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm(`确定删除【${row.drugName}】？`, '提示', {
        type: 'warning'
      }).then(async () => {
        await deleteCommonDrug(row.commonDrugId)
        this.$message.success('删除成功')
        this.fetchList()
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.drugForm.validate(async (valid) => {
        if (!valid) return
        try {
          if (this.isEdit) {
            await editCommonDrug(this.form)
            this.$message.success('编辑成功')
          } else {
            await addCommonDrug(this.form)
            this.$message.success('新增成功')
          }
          this.dialogVisible = false
          this.fetchList()
        } catch (error) {
          console.error(error)
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.drugForm.resetFields()
      this.form = {
        commonDrugId: null,
        drugName: '',
        drugSpec: '',
        usageMethod: '',
        usageFrequencyUnit: '',
        usagePerUseCount: ''
      }
    }
  }
}
</script>

<style scoped>
.commonly-drug-page {
  padding: 20px;
}
.search-card {
  margin-bottom: 16px;
}
.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
