<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="出库状态" prop="outStatus">
        <el-select
          v-model="queryParams.outStatus"
          placeholder="请选择出库状态"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="dict in healthcare_entry_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="药品品种" prop="variety">
        <el-input
          v-model="queryParams.variety"
          placeholder="请输入药品品种"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库时间" prop="outTime">
        <el-date-picker
          clearable
          v-model="queryParams.outTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择出库时间"
        >
        </el-date-picker>
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pasd-healthcare:drugout:add']"
          >药品出库</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pasd-healthcare:drugout:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pasd-healthcare:drugout:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pasd-healthcare:drugout:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="drugoutList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column
        label="出库单号"
        align="center"
        prop="outCode"
        width="170px"
      />
      <el-table-column label="出库状态" align="center" prop="outStatus">
        <template #default="scope">
          <dict-tag
            :options="healthcare_entry_status"
            :value="scope.row.outStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="出库类型" align="center" prop="outType">
        <template #default="scope">
          <dict-tag :options="healthcare_out_type" :value="scope.row.outType" />
        </template>
      </el-table-column>
      <el-table-column label="药品品种" align="center" prop="variety" />
      <el-table-column label="出库数量" align="center" prop="outQuantity" />
      <el-table-column label="出库地点" align="center" prop="outPointName">
      </el-table-column>
      <el-table-column label="出库操作人" align="center" prop="outPerson" />
      <el-table-column
        label="出库时间"
        align="center"
        prop="outTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.outTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180PX"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pasd-healthcare:drugout:edit']"
            ><span v-if="scope.row.outStatus === 1">修改</span>
            <span v-else>查看详情</span></el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pasd-healthcare:drugout: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="1200px" append-to-body>
      <el-form
        ref="drugoutRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        :inline="true"
      >
        <el-form-item label="药品品种合计" prop="variety" label-width="100px">
          <el-input
            v-model="form.variety"
            placeholder="请输入药品品种"
            style="width: 350px"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="出库数量合计" prop="outQuantity" label-width="100">
          <el-input
            :model-value="outQuantitySummary"
            placeholder="出库数量合计"
            style="width: 350px"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="出库地点" prop="outPoint">
          <el-select
            v-model="form.outPoint"
            placeholder="请选择出库地点"
            style="width: 350px"
            :disabled="isDisabled"
          >
                  <el-option
                    v-for="dict in storeroomList"
                    :key="dict.id"
                    :label="dict.storeroomName"
                    :value="dict.id"
                  />
          </el-select>
        </el-form-item>
        <el-form-item label="出库时间" prop="outTime">
          <el-date-picker
            clearable
            v-model="form.outTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出库时间"
            style="width: 350px"
            :disabled="isDisabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出库类型" prop="outType">
          <el-radio-group v-model="form.outType" :disabled="isDisabled">
            <el-radio
              v-for="dict in healthcare_out_type"
              :key="dict.value"
              :value="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 仓库调拨 -->
        <div v-if="form.outType === 0">
          <el-form-item label="入库地点" prop="inboundLocation">
            <el-select
              v-model="form.inboundLocation"
              placeholder="请选择入库地点"
              style="width: 310px"
              :disabled="isDisabled"
            >
              <el-option
                v-for="dict in storeroomList"
                :key="dict.id"
                :label="dict.storeroomName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="签收人" prop="signee">
            <el-input
              v-model="form.signee"
              placeholder="请输入签收人"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="证明材料" prop="proofMaterial">
            <file-upload v-model="form.proofMaterial" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item label="用途详述" prop="purposeDetails">
            <el-input
              v-model="form.purposeDetails"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
        </div>
        <!-- 依申请出库 -->
        <div v-if="form.outType === 1">
          <el-form-item label="证明材料" prop="proofMaterial">
            <file-upload v-model="form.proofMaterial" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item label="所在单位" prop="affiliation">
            <el-input
              v-model="form.affiliation"
              placeholder="请输入所在单位"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="用途详述" prop="purposeDetails">
            <el-input
              v-model="form.purposeDetails"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
        </div>
        <!-- 过期报废 -->
        <div v-if="form.outType === 2">
          <el-form-item label="过期时间" prop="expirationDate">
            <el-date-picker
              clearable
              v-model="form.expirationDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择过期时间"
              style="width: 310px"
              :disabled="isDisabled"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="当前时间" prop="currentDatetime">
            <el-date-picker
              clearable
              v-model="form.currentDatetime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择当前时间"
              style="width: 310px"
              :disabled="isDisabled"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="销毁人" prop="destroyer">
            <el-input
              v-model="form.destroyer"
              placeholder="请输入销毁人"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="销毁地点" prop="destructionLocation">
            <el-input
              v-model="form.destructionLocation"
              placeholder="请输入销毁地点"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="销毁过程" prop="destructionProcess">
            <el-input
              v-model="form.destructionProcess"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="报废原因" prop="scrapReason">
            <el-input
              v-model="form.scrapReason"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
        </div>
        <!-- 数量修正 -->
        <div v-if="form.outType === 3">
          <el-form-item label="证明材料" prop="proofMaterial">
            <file-upload v-model="form.proofMaterial" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item label="用途详述" prop="purposeDetails">
            <el-input
              v-model="form.purposeDetails"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
        </div>
        <!-- 药品报损 -->
        <div v-if="form.outType === 4">
          <el-form-item label="报废原因" prop="scrapReason">
            <el-input
              v-model="form.scrapReason"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="处理方式" prop="disposalMethod">
            <el-input
              v-model="form.disposalMethod"
              placeholder="请输入处理方法"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="报损原因" prop="damageReason">
            <el-input
              v-model="form.damageReason"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
              style="width: 310px"
              :disabled="isDisabled"
            />
          </el-form-item>
        </div>
        <el-divider content-position="center">出库详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="Plus"
              @click="handleAddHealthcareInventoryDrugoutDetails"
              :disabled="isDisabled"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDeleteHealthcareInventoryDrugoutDetails"
              :disabled="isDisabled"
              >删除</el-button
            >
          </el-col>
        </el-row>
                <el-table
          :data="healthcareInventoryDrugoutDetailsList"
          :row-class-name="rowHealthcareInventoryDrugoutDetailsIndex"
          @selection-change="
            handleHealthcareInventoryDrugoutDetailsSelectionChange
          "
          ref="healthcareInventoryDrugoutDetails"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="药品名称" prop="medicineName" width="300px">
            <template #default="scope">
              <el-input
                v-model="scope.row.medicineName"
                placeholder="请输入药品名称"
                :disabled="true"
                style="width: 250px"
                @blur="syncDrugoutDetails()"
              />
            </template>
          </el-table-column>
          <el-table-column label="条码" align="center" prop="barcode" />
          <el-table-column label="生产厂家" align="center" prop="manufacturer" />
          <el-table-column label="出库批次" prop="outBatch" />
          <el-table-column label="出库库房" prop="outPointName" />
          <el-table-column label="剩余库存" width="220">
            <template #default="scope">
              <span>{{ formatRemainingInventory(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否拆分" width="120">
            <template #default="scope">
              <span>{{ (String(scope.row.isSplit).toUpperCase() === 'Y') ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="出库单位" width="160">
            <template #default="scope">
              <el-select
                v-model="scope.row.unitType"
                placeholder="选择单位"
                :disabled="isDisabled || getUnitOptions(scope.row).length === 1"
                style="width: 140px"
                @change="handleUnitChange(scope.row)"
              >
                <el-option
                  v-for="option in getUnitOptions(scope.row)"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="出库数量" prop="quantity" width="200px">
            <template #default="scope">
              <el-form-item
                :rules="[
                  { required: true, message: '出库数量不能为空', trigger: 'change' },
                  {
                    validator: (rule, value, callback) =>
                      validateQuantityRule(scope.row, value, callback),
                    trigger: ['change', 'blur'],
                  },
                ]"
              >
                <el-input-number
                  v-model="scope.row.quantity"
                  :min="1"
                  :precision="0"
                  :disabled="isDisabled"
                  controls-position="right"
                  style="width: 160px"
                  @change="handleQuantityChange(scope.row)"
                  @blur="handleQuantityBlur(scope.row)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="档案"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                type="text"
                icon="Edit"
                @click="openArchiveSelector(scope.row.index)"
                :disabled="isDisabled"
                >选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="isDisabled"
            >提交</el-button>
          <el-button type="primary" @click="handleSave" :disabled="isDisabled">
            {{ isSaving ? "保存中.." : "保存" }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
      <DrugArchive
        ref="archiveSelectorRef"
        title="药品档案选择"
        @selectedArchive="handleArchiveSelected"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Drugout">
import {
  addDrugout,
  delDrugout,
  getDrugout,
  listDrugout,
  saveDrugout,
  updateDrugout,
} from "@/api/healthcare/inventory/DrugOut/drugout.js";
import { listStoreroom } from "@/api/healthcare/inventory/StoreRoom/storeroom.js";
import DrugArchive from "@/components/drugFiling/index.vue";
import { ref, watchEffect, computed } from "vue";
const archiveSelectorRef = ref(null);

// 详情信息下标
const ListIndex = ref(null);
const openDrugFiling = ref(null);
const { proxy } = getCurrentInstance();
const { healthcare_out_type, healthcare_entry_point, healthcare_entry_status } =
  proxy.useDict(
    "healthcare_out_type",
    "healthcare_entry_point",
    "healthcare_entry_status"
  );

const isDisabled = ref(false);
const drugoutList = ref([]);
const healthcareInventoryDrugoutDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedHealthcareInventoryDrugoutDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const drugFilings = ref([]);
const selectedRow = reactive([]);

const data = reactive({
  form: {
    variety: 0,
    outQuantity: 0,
    outBoxQuantity: 0,
    outPackQuantity: 0,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    outStatus: null,
    variety: 0,
    outTime: null,
  },
  rules: {
    // variety: [
    //   { required: true, message: "药品品种不能为空", trigger: "blur" }
    // ],
    // outQuantity: [
    //   { required: true, message: "出库数量不能为空", trigger: "blur" }
    // ],
    outPoint: [
      { required: true, message: "出库地点不能为空", trigger: "change" },
      
    ],
    outTime: [{ required: true, message: "出库时间不能为空", trigger: "blur" }],
    outType: [
      { required: true, message: "出库类型不能为空", trigger: "change" },
    ],
    outRemark: [
      { required: true, message: "出库备注不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    inboundLocation: [
      { required: true, message: "入库地点不能为空", trigger: "blur" },
    ],
    signee: [
      { required: true, message: "签收人不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    purposeDetails: [
      { required: true, message: "用途明细不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    expirationDate: [
      { required: true, message: "过期时间不能为空", trigger: "blur" },
    ],
    currentDatetime: [
      { required: true, message: "当前时间不能为空", trigger: "blur" },
    ],
    destroyer: [
      { required: true, message: "销毁人不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    destructionLocation: [
      { required: true, message: "销毁地点不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    destructionProcess: [
      { required: true, message: "销毁过程不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    scrapReason: [
      { required: true, message: "报废原因不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    affiliation: [
      { required: true, message: "所在单位不能为空", trigger: "blur" },
      {
        pattern: /^[^\s]+$/,
        message: '禁止包含空格',
        trigger: 'blur',
      },
    ],
    proofMaterial: [
      // 证明材料字段为非必填
    ],
  },
});

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

// 打开对话框的方法
const openArchiveSelector = (index) => {
  archiveSelectorRef.value.showSelector();
  ListIndex.value = index - 1;
};

const UNIT_TYPES = {
  BOX: "BOX",
  PACK: "PACK",
};

const quantityTotals = computed(() => {
  return healthcareInventoryDrugoutDetailsList.value.reduce(
    (acc, cur) => {
      if (!cur) {
        return acc;
      }
      const qty = Number(cur.quantity) || 0;
      if (!qty) {
        return acc;
      }
      const unitType = cur.unitType || UNIT_TYPES.BOX;
      const ratio = Number(cur.unitQuantity) || 1;
      if (unitType === UNIT_TYPES.PACK) {
        acc.pack += qty;
        acc.total += qty;
      } else {
        acc.box += qty;
        acc.total += qty * ratio;
      }
      return acc;
    },
    { box: 0, pack: 0, total: 0 }
  );
});

const outQuantitySummary = computed(() => {
  const totals = quantityTotals.value;
  const parts = [];
  if (totals.box) {
    parts.push("箱:" + totals.box);
  }
  if (totals.pack) {
    parts.push("包:" + totals.pack);
  }
  parts.push("最小单位:" + totals.total);
  return parts.join(' / ');
});

// 计算药品品种合计
const calculateVarietyTotal = () => {
  const total = healthcareInventoryDrugoutDetailsList.value.filter(
    (item) => item && item.drugId
  ).length;
  form.value.variety = total;
  return total;
};

watchEffect(() => {
  const totals = quantityTotals.value;
  form.value.outQuantity = totals.total;
  form.value.outBoxQuantity = totals.box;
  form.value.outPackQuantity = totals.pack;
  calculateVarietyTotal();
});

// 处理选中药品档案后的回调
const syncDrugoutDetails = () => {
  form.value.healthcareInventoryDrugoutDetailsList =
    healthcareInventoryDrugoutDetailsList.value;
};

const ensureUnitMetadata = (row) => {
  if (!row) {
    return;
  }
  const normalizeUnit = (n, f) => {
    const s = String(n || "").trim();
    if (!s || /^\d+$/.test(s)) return f;
    return s;
  };
  row.inventoryUnit = normalizeUnit(row.inventoryUnit || row.unit, "主单位");
  row.splitUnit = normalizeUnit(row.splitUnit, "");
  row.unitQuantity = Number(row.unitQuantity) || 1;
  if (!row.unitType) {
    row.unitType = UNIT_TYPES.BOX;
  }
  const isSplit = String(row.isSplit || '').toUpperCase() === 'Y';
  if (row.unitType === UNIT_TYPES.PACK && !row.splitUnit) {
    if (isSplit) {
      row.splitUnit = "最小单位";
    } else {
      row.unitType = UNIT_TYPES.BOX;
    }
  }
  row.unit = row.unitType === UNIT_TYPES.PACK
    ? (row.splitUnit || "最小单位")
    : row.inventoryUnit;
};

const formatRemainingInventory = (row) => {
  if (!row) {
    return "0";
  }
  const boxNum = Number(row.remainingQuantity ?? row.boxCount ?? 0);
  const packNum = Number(row.remainingPackQuantity ?? row.packCount ?? 0);
  const parts = [];
  if (boxNum) {
    parts.push(String(boxNum) + (row.inventoryUnit || ""));
  }
  if (packNum) {
    parts.push(String(packNum) + (row.splitUnit || ""));
  }
  if (!parts.length) {
    return "0";
  }
  return parts.join(" / ");
};

const getUnitOptions = (row) => {
  const options = [];
  const normalizeUnit = (n, f) => {
    const s = String(n || "").trim();
    if (!s || /^\d+$/.test(s)) return f;
    return s;
  };
  const boxName = normalizeUnit(row && row.inventoryUnit, "主单位");
  const packName = normalizeUnit(row && row.splitUnit, "最小单位");
  options.push({ label: `主单位（${boxName}）`, value: UNIT_TYPES.BOX });
  const isSplit = String(row?.isSplit || '').toUpperCase() === 'Y';
  if (isSplit || (row && row.splitUnit)) {
    options.push({ label: `最小单位（${packName}）`, value: UNIT_TYPES.PACK });
  }
  return options;
};

const validateQuantityRule = (row, value, callback) => {
  if (!row) {
    callback();
    return;
  }
  if (value === null || value === undefined || value === "") {
    callback(new Error("出库数量不能为空"));
    return;
  }
  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    callback(new Error("数量需为正整数"));
    return;
  }
  ensureUnitMetadata(row);
  const available =
    row.unitType === UNIT_TYPES.PACK
      ? Number(row.remainingPackQuantity ?? row.packCount ?? 0)
      : Number(row.remainingQuantity ?? row.boxCount ?? 0);
  if (available <= 0) {
    callback(new Error("当前单位无可用库存"));
    return;
  }
  if (parsed > available) {
    callback(
      new Error(
        row.unitType === UNIT_TYPES.PACK ? "输入数量超过剩余库存" : "输入数量超过剩余库存"
      )
    );
    return;
  }
  callback();
};

const enforceQuantityBounds = (row) => {
  if (!row) {
    return;
  }
  if (row.quantity === null || row.quantity === "" || row.quantity === undefined) {
    return;
  }
  ensureUnitMetadata(row);
  let parsed = Number(row.quantity);
  if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed <= 0) {
    row.quantity = null;
    return;
  }
  const available =
    row.unitType === UNIT_TYPES.PACK
      ? Number(row.remainingPackQuantity ?? row.packCount ?? 0)
      : Number(row.remainingQuantity ?? row.boxCount ?? 0);
  if (available <= 0) {
    row.quantity = null;
    return;
  }
  if (parsed > available) {
    row.quantity = available;
  } else {
    row.quantity = parsed;
  }
};

const handleQuantityChange = (row) => {
  enforceQuantityBounds(row);
  syncDrugoutDetails();
};

const handleQuantityBlur = (row) => {
  enforceQuantityBounds(row);
  syncDrugoutDetails();
};

const handleUnitChange = (row) => {
  ensureUnitMetadata(row);
  if (row && row.quantity != null) {
    enforceQuantityBounds(row);
  }
  syncDrugoutDetails();
};

const normalizeDetailRows = () => {
  healthcareInventoryDrugoutDetailsList.value.forEach((row) => {
    if (!row) {
      return;
    }
    if (row.quantity === "") {
      row.quantity = null;
    }
    row.remainingQuantity =
      Number(row.remainingQuantity ?? row.boxCount ?? 0) || 0;
    row.remainingPackQuantity =
      Number(row.remainingPackQuantity ?? row.packCount ?? 0) || 0;
    row.unitQuantity =
      Number(row.unitQuantity ?? row.minNumber ?? 1) || 1;
    ensureUnitMetadata(row);
  });
  syncDrugoutDetails();
};
const handleArchiveSelected = (archive) => {
  if (archive == null || ListIndex.value == null) {
    return;
  }
  const rowIndex = ListIndex.value;
  const detail = healthcareInventoryDrugoutDetailsList.value[rowIndex];
  if (!detail) {
    return;
  }

  detail.drugId = archive.archiveId || archive.id || "";
  detail.medicineName = archive.medicineName || "";
  detail.barcode = archive.barcode || "";
  detail.manufacturer = archive.manufacturer || "";
  detail.outBatch = archive.batch || "";
  detail.filingId = archive.filingId || "";
  detail.outPointName = archive.storeroomName || "";
  detail.outPointId = archive.storeroomId || "";
  detail.expiryDate = archive.expiryDate || "";
  detail.retailPrice = archive.retailPrice || "";
  detail.remainingQuantity = Number(archive.boxCount ?? 0) || 0;
  detail.remainingPackQuantity = Number(archive.packCount ?? 0) || 0;
  detail.inventoryUnit = archive.inventoryUnit || detail.inventoryUnit || "";
  detail.splitUnit = archive.splitUnit || detail.splitUnit || "";
  detail.unitQuantity =
    Number(archive.unitQuantity ?? archive.minNumber ?? detail.unitQuantity ?? 1) || 1;
  detail.isSplit = (archive.isSplit ?? detail.isSplit ?? '').toString();

  if (archive.storeroomId && archive.storeroomId !== form.value.outPoint) {
    proxy.$modal.msgError("出库库房记录与药品库存库记录不一致，请重新选择!");
    detail.drugId = "";
    detail.medicineName = "";
    detail.barcode = "";
    detail.manufacturer = "";
    detail.outBatch = "";
    detail.filingId = "";
    detail.outPointName = "";
    detail.outPointId = "";
    detail.expiryDate = "";
    detail.retailPrice = "";
    detail.remainingQuantity = 0;
    detail.remainingPackQuantity = 0;
    detail.inventoryUnit = "";
    detail.splitUnit = "";
    detail.unitQuantity = 1;
    detail.quantity = null;
    normalizeDetailRows();
    return;
  }

  if (detail.unitType === UNIT_TYPES.PACK && !detail.splitUnit) {
    detail.unitType = UNIT_TYPES.BOX;
  }
  detail.quantity = null;
  normalizeDetailRows();
};;;

const storeroomList = ref([]);
/** 查询药品出库记录列表 */
function getList() {
  loading.value = true;
  listDrugout(queryParams.value).then((response) => {
    console.log(queryParams.value);
    drugoutList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  
    // 查询库房管理列表
  listStoreroom().then((response) => {
    storeroomList.value = response.rows;
    console.log(storeroomList.value)
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    outCode: null,
    outStatus: null,
    outType: null,
    variety: 0,
    outQuantity: 0,
    outBoxQuantity: 0,
    outPackQuantity: 0,
    cffiliation: null,
    outPoint: null,
    outPerson: null,
    outTime: null,
    createTime: null,
    createBy: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    inboundLocation: null,
    signee: null,
    proofMaterial: null,
    purposeDetails: null,
    unit: null,
    expirationDate: null,
    currentDatetime: null,
    destroyer: null,
    destructionLocation: null,
    destructionProcess: null,
    scrapReason: null,
    disposalMethod: null,
    damageReason: null,
    medicineName: null,
    outBatch: null,
  };
  healthcareInventoryDrugoutDetailsList.value = [];
  syncDrugoutDetails();
  proxy.resetForm("drugoutRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isDisabled.value = false;
  open.value = true;
  title.value = "添加药品出库记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getDrugout(_id).then((response) => {
    form.value = response.data;
    healthcareInventoryDrugoutDetailsList.value =
      response.data.healthcareInventoryDrugoutDetailsList;
    console.log(healthcareInventoryDrugoutDetailsList.value);
    normalizeDetailRows();
    if (form.value.outStatus === 0) {
      isDisabled.value = true;
    } else if (form.value.outStatus === 1) {
      isDisabled.value = false;
    }
    open.value = true;
    title.value = "查看药品出库记录";
  });
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["drugoutRef"].validate((valid) => {
    if (valid) {
      form.value.healthcareInventoryDrugoutDetailsList =
        healthcareInventoryDrugoutDetailsList.value;
      console.log("form.value", form.value);
      if (form.value.id != null) {
        updateDrugout(form.value).then((response) => {
          proxy.$modal.msgSuccess("出库成功");
          open.value = false;
          getList();
        });
      } else {
        addDrugout(form.value).then((response) => {
          proxy.$modal.msgSuccess("出库成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

const isSaving = ref(false);
// 保存按钮操作
const handleSave = () => {
  proxy.$refs["drugoutRef"].validate((valid) => {
    form.value.healthcareInventoryDrugoutDetailsList =
      healthcareInventoryDrugoutDetailsList.value;
    if (valid) {
      saveDrugout(form.value)
        .then((response) => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("保存成功");
            isSaving.value = true;
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        })
        .finally(() => {
          isSaving.value = false;
        });
    }
  });
};

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除药品出库记录编号 "' + _ids + '" 的数据项?')
    .then(function () {
      return delDrugout(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 出库详情：序号处理函数 */
function rowHealthcareInventoryDrugoutDetailsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 出库详情：添加按钮操作 */
function handleAddHealthcareInventoryDrugoutDetails() {
  const obj = {
    drugId: "",
    quantity: null,
    medicineName: "",
    batch: "",
    manufacturer: "",
    outBatch: "",
    barcode: "",
    outPointName: "",
    filingId: "",
    outPointId: "",
    expiryDate: "",
    retailPrice: "",
    remainingQuantity: 0,
    remainingPackQuantity: 0,
    inventoryUnit: "",
    splitUnit: "",
    unitQuantity: 1,
    unitType: UNIT_TYPES.BOX,
    unit: "",
    drugFilings: [],
  };
  healthcareInventoryDrugoutDetailsList.value.push(obj);
  ensureUnitMetadata(obj);
  syncDrugoutDetails();
}

/** 出库详情：删除按钮操作 */
function handleDeleteHealthcareInventoryDrugoutDetails() {
  if (checkedHealthcareInventoryDrugoutDetails.value.length == 0) {
    proxy.$modal.msgError(
      "请先选择要删除的出库详情,用于记录药品出库的详细信息数据"
    );
  } else {
    const healthcareInventoryDrugoutDetailss =
      healthcareInventoryDrugoutDetailsList.value;
    const checkedHealthcareInventoryDrugoutDetailss =
      checkedHealthcareInventoryDrugoutDetails.value;
    healthcareInventoryDrugoutDetailsList.value =
      healthcareInventoryDrugoutDetailss.filter(function (item) {
        return (
          checkedHealthcareInventoryDrugoutDetailss.indexOf(item.index) == -1
        );
      });
    normalizeDetailRows();
  }
}

/** 复选框选中数据 */
function handleHealthcareInventoryDrugoutDetailsSelectionChange(selection) {
  checkedHealthcareInventoryDrugoutDetails.value = selection.map(
    (item) => item.index
  );
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "pasd-healthcare/drugout/export",
    {
      ...queryParams.value,
    },
    `drugout_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
