<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :model="queryParams"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="查询日期：">
        <el-date-picker
          v-model="queryTime"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 300px; margin-right: 20px"
          value-format="YYYY-MM-DD"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结算类型：">
        <el-select
          v-model="queryParams.settlementType"
          placeholder="结算类型"
          clearable
          style="width: 150px; margin-right: 30px"
        >
          <el-option
            label="日结"
            value="daily"
          />
          <el-option
            label="周结"
            value="weekly"
          />
          <el-option
            label="月结"
            value="monthly"
          />
        </el-select>
        <el-button
          type="primary"
          plain
          icon="Search"
          @click="handleQuery"
        >
          查询
        </el-button>
        <el-button
          type="primary"
          plain
          icon="Printer"
          @click="handlePrint"
        >
          打印
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['medication:dayEndSettlement:add']"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['medication:dayEndSettlement:edit']"
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['medication:dayEndSettlement:remove']"
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['medication:dayEndSettlement:export']"
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >
          导出
        </el-button>
      </el-col>
      <right-toolbar
        v-model:show-search="showSearch"
        @query-table="getList"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="dayEndSettlementList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="结算单号"
        align="center"
        prop="settlementNo"
      />
      <el-table-column
        label="结算日期"
        align="center"
        prop="settlementDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.settlementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结算类型"
        align="center"
        prop="settlementType"
      />
      <el-table-column
        label="结算状态"
        align="center"
        prop="status"
      >
        <template #default="scope">
          <dict-tag
            :options="sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="总金额"
        align="center"
        prop="totalAmount"
      />
      <el-table-column
        label="操作人"
        align="center"
        prop="operator"
      />
      <el-table-column
        label="操作时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-hasPermi="['medication:dayEndSettlement:query']"
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button
            v-hasPermi="['medication:dayEndSettlement:edit']"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            v-hasPermi="['medication:dayEndSettlement:remove']"
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改日结结算单对话框 -->
    <el-dialog
      v-model="open"
      :title="title"
      width="500px"
      append-to-body
    >
      <el-form
        ref="dayEndSettlementRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          label="结算单号"
          prop="settlementNo"
        >
          <el-input
            v-model="form.settlementNo"
            placeholder="请输入结算单号"
          />
        </el-form-item>
        <el-form-item
          label="结算日期"
          prop="settlementDate"
        >
          <el-date-picker
            v-model="form.settlementDate"
            clearable
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结算日期"
          />
        </el-form-item>
        <el-form-item
          label="结算类型"
          prop="settlementType"
        >
          <el-select
            v-model="form.settlementType"
            placeholder="请选择结算类型"
          >
            <el-option
              label="日结"
              value="daily"
            />
            <el-option
              label="周结"
              value="weekly"
            />
            <el-option
              label="月结"
              value="monthly"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="结算状态"
          prop="status"
        >
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="总金额"
          prop="totalAmount"
        >
          <el-input-number
            v-model="form.totalAmount"
            placeholder="请输入总金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #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="DayEndSettlement">
import { listDayEndSettlement, getDayEndSettlement, delDayEndSettlement, addDayEndSettlement, updateDayEndSettlement } from "@/api/medicationmanagement/dayEndSettlement";

const { proxy } = getCurrentInstance();
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 open = ref(false);
const queryTime = ref([]);

const dayEndSettlementList = ref([]);
const queryFormRef = ref();
const dayEndSettlementRef = ref();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  settlementNo: null,
  settlementDate: null,
  settlementType: null,
  status: null
});

const form = ref({});
const rules = ref({
  settlementNo: [
    { required: true, message: "结算单号不能为空", trigger: "blur" }
  ],
  settlementDate: [
    { required: true, message: "结算日期不能为空", trigger: "blur" }
  ],
  settlementType: [
    { required: true, message: "结算类型不能为空", trigger: "change" }
  ],
  totalAmount: [
    { required: true, message: "总金额不能为空", trigger: "blur" }
  ]
});

const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

/** 查询日结结算单列表 */
const getList = async () => {
  loading.value = true;
  try {
    const response = await listDayEndSettlement(queryParams.value);
    dayEndSettlementList.value = response.rows;
    total.value = response.total;
  } catch (error) {
    console.error('获取日结结算单列表失败:', error);
  } finally {
    loading.value = false;
  }
};

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

/** 表单重置 */
const reset = () => {
  form.value = {
    id: null,
    settlementNo: null,
    settlementDate: null,
    settlementType: null,
    status: "0",
    totalAmount: null,
    remark: null
  };
  proxy.resetForm("dayEndSettlementRef");
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加日结结算单";
};

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  const settlementId = row.id || ids.value[0];
  getDayEndSettlement(settlementId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改日结结算单";
  });
};

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

/** 删除按钮操作 */
const handleDelete = (row) => {
  const settlementIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除日结结算单编号为"' + settlementIds + '"的数据项？').then(function() {
    return delDayEndSettlement(settlementIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download("medication/dayEndSettlement/export", {
    ...queryParams.value
  }, `dayEndSettlement_${new Date().getTime()}.xlsx`);
};

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

/** 查看按钮操作 */
const handleView = (row) => {
  // TODO: 实现查看功能
  proxy.$modal.msgSuccess("查看功能待实现");
};

/** 初始化数据 */
getList();
</script>