<template>
  <div class="app-container" v-loading="pageLoading" loading-text="审批中...">
    <!-- <el-row :gutter="10" class="mb8" v-if="viewStatus">
      <el-col :span="1.5">
        <el-button v-if="viewStatus != 'view'" plain type="primary" icon="Edit" @click="handelApply"
          >审批通过</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="viewStatus != 'view'"
          type="primary"
          plain
          icon="Edit"
          @click="handleReject"
          >驳回</el-button
        >
      </el-col>
    </el-row> -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- v-if="scope.row.statusEnum == '1' || scope.row.statusEnum == '9'" -->
        <!-- v-hasPermi="['system:user:remove']" -->
        <el-button plain type="primary" icon="Plus" @click="handleSubmitApproval()"
          >提交审核</el-button
        >
        <!-- <el-button type="primary" plain icon="Plus" @click="submitAudit"
            >提交审核</el-button
          > -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Printer" :disabled="multiple" @click="handleDelete"
          >打印</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="EditPen" @click="handleTotalAmount"
          >计算金额</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="EditPen" @click="handleBatchAdd"
          >生成批量调拨单</el-button
        >
      </el-col>
    </el-row>
    <el-button type="primary" plain @click="handleExport" v-if="viewStatus == 'view'"
      >导出</el-button
    >
    <el-form
      :model="receiptHeaderForm"
      ref="receiptHeaderRef"
      :inline="true"
      label-width="120px"
      :rules="rules"
    >
      <el-row :gutter="10">
        <el-form-item label="单据号：" prop="busNo">
          <el-input
            v-model="receiptHeaderForm.busNo"
            placeholder="单据号："
            clearable
            style="width: 260px"
            disabled
          />
        </el-form-item>
        <el-form-item label="单据日期：">
          <el-date-picker
            v-model="receiptHeaderForm.occurrenceTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            :disabled="data.isEdit"
          />
        </el-form-item>
        <el-form-item label="药品类型：" prop="medicationType" label-width="115px">
          <el-select
            v-model="receiptHeaderForm.medicationType"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
            @change="
              (value) => {
                itemType = value;
              }
            "
          >
            <!-- 字典 purchase_type -->
            <el-option
              v-for="itemType in purchase_type"
              :key="itemType.value"
              :label="itemType.label"
              :value="itemType.value"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row :gutter="10">
        <el-form-item label="源仓库类型：" prop="sourceTypeEnum">
          <el-select
            v-model="receiptHeaderForm.sourceTypeEnum"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
            @change="handleChangeSourceTypeEnum"
          >
            <el-option
              v-for="supplier in warehous_type"
              :key="supplier.value"
              :label="supplier.label"
              :value="supplier.value"
            />
          </el-select>
        </el-form-item>
        <!-- sourceLocationName -->
        <el-form-item label="源仓库：" prop="sourceLocationId" required>
          <el-select
            v-model="receiptHeaderForm.sourceLocationId"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
          >
            <!-- purchase_type -->
            <el-option
              v-for="supplier in sourceTypeListOptions"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <!-- sourceLocationStoreName -->
        <el-form-item label="源货位：" prop="sourceLocationStoreId">
          <el-select
            v-model="receiptHeaderForm.sourceLocationStoreId"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
          >
            <el-option
              v-for="supplier in sourceLocationStoreIdListOptions"
              :key="supplier.value"
              :label="supplier.label"
              :value="supplier.value"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row :gutter="10">
        <el-form-item label="目的仓库类型：" prop="purposeTypeEnum">
          <el-select
            v-model="receiptHeaderForm.purposeTypeEnum"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
            @change="handleChangePurposeTypeEnum"
          >
            <el-option
              v-for="dict in warehous_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- purposeLocationName -->
        <el-form-item label="目的仓库：" prop="purposeLocationId" required>
          <el-select
            v-model="receiptHeaderForm.purposeLocationId"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
          >
            <!-- purchase_type -->
            <el-option
              v-for="supplier in purposeTypeListOptions"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <!-- purposeLocationStoreName -->
        <el-form-item label="目的货位：" prop="purposeLocationStoreId">
          <el-select
            v-model="receiptHeaderForm.purposeLocationStoreId"
            placeholder="请选择目的货位"
            style="width: 150px"
          >
            <el-option
              v-for="supplier in purposeLocationStoreIdListOptions"
              :key="supplier.value"
              :label="supplier.label"
              :value="supplier.value"
            />
          </el-select>
        </el-form-item>
        <!-- purposeLocationStoreName -->
        <el-form-item label="目的货位：" prop="purposeLocationStoreId">
          <el-select
            v-model="receiptHeaderForm.purposeLocationStoreId"
            placeholder=""
            clearable
            style="width: 150px"
            :disabled="data.isEdit"
          >
            <el-option
              v-for="supplier in purposeLocationStoreIdListOptions"
              :key="supplier.value"
              :label="supplier.label"
              :value="supplier.value"
            />
          </el-select>
        </el-form-item>
      </el-row>
    </el-form>
    <el-tabs type="border-card">
      <el-tab-pane label="调拨单据明细">
        <el-row :gutter="10" class="mb8" v-if="!viewStatus">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleSave"
              >批量保存所有数据</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" @click="handleDelete">删除行</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- <el-input placeholder="输入项目名/拼音搜索" v-model="searchKey"/> -->
          </el-col>
        </el-row>
        <el-form :model="form" ref="formRef" :disabled="viewStatus == 'apply'">
          <el-table
            v-loading="loading"
            :data="currentPageData"
            @row-click="handleRowClick"
            ref="tableRef"
            max-height="450"
            @selection-change="handleSelectionChange"
            border
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column type="index" label="序号" width="60" fixed align="center" />
            <el-table-column label="项目" align="center" key="name" prop="name" width="200" fixed>
              <template #default="scope">
                {{ scope.row.name }}
              </template>
            </el-table-column>
            <el-table-column
              label="规格"
              align="center"
              key="totalVolume"
              prop="totalVolume"
              width="200"
            >
              <template #default="scope">
                {{ scope.row.totalVolume }}
              </template>
            </el-table-column>
            <el-table-column
              label="厂家/产地"
              align="center"
              key="manufacturerText"
              prop="manufacturerText"
              :show-overflow-tooltip="true"
              width="220"
            >
              <template #default="scope">
                {{ scope.row.manufacturerText }}
              </template>
            </el-table-column>
            <el-table-column
              label="调拨单位"
              align="center"
              key="unitCode"
              prop="unitCode"
              :show-overflow-tooltip="true"
              width="90"
            >
              <template #default="scope">
                <el-form-item
                  :prop="`purchaseinventoryList.${scope.$index}.unitCode`"
                  :rules="tableRules.unitCode"
                >
                  <div class="select_wrapper_div">
                    <el-select
                      v-model="scope.row.unitCode"
                      placeholder=" "
                      :disabled="viewStatus == 'view'"
                      :class="{ 'error-border': scope.row.error }"
                      @change="(value) => handleUnitCodeChange(scope.row, scope.$index, value)"
                    >
                      <el-option
                        v-for="(item, index) in scope.row.unitList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="源仓库库存数量"
              align="center"
              key="totalSourceQuantityDisplay"
              prop="totalSourceQuantityDisplay"
              width="120"
            >
              <template #default="scope">
                {{ scope.row.totalSourceQuantityDisplay }}
              </template>
            </el-table-column>
            <el-table-column
              label="目的仓库库存数量"
              align="center"
              key="totalPurposeQuantityDisplay"
              prop="totalPurposeQuantityDisplay"
              width="130"
            >
              <template #default="scope">
                {{ scope.row.totalPurposeQuantityDisplay }}
              </template>
            </el-table-column>
            <el-table-column
              label="调拨数量"
              align="center"
              key="itemQuantityDisplay"
              prop="itemQuantityDisplay"
              width="120"
            >
              <template #default="scope">
                <el-form-item
                  :prop="`purchaseinventoryList.${scope.$index}.itemQuantityDisplay`"
                  :rules="tableRules.itemQuantityDisplay"
                >
                  <div class="select_wrapper_div">
                    <el-input
                      :disabled="viewStatus == 'view'"
                      v-model="scope.row.itemQuantityDisplay"
                      placeholder=""
                      @change="(value) => handleItemQuantityChange(scope.row, value)"
                      :class="{ 'error-border': scope.row.error }"
                    />
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="调拨单价 "
              align="right"
              header-align="center"
              key="price"
              prop="price"
              width="130"
            >
              <template #default="scope">
                {{ scope.row.price + ' 元/ ' + scope.row.unitCode_dictText }}
              </template>
            </el-table-column>
            <el-table-column
              label="合计金额 "
              align="right"
              header-align="center"
              key="totalPrice"
              prop="totalPrice"
              width="130"
            >
              <template #default="scope">
                {{ scope.row.totalPrice + ' 元' }}
              </template>
            </el-table-column>
            <el-table-column
              label="产品批号"
              align="center"
              key="lotNumber"
              prop="lotNumber"
              width="160"
            >
              <template #default="scope">
                {{ scope.row.lotNumber }}
              </template>
            </el-table-column>
            <el-table-column
              label="生产日期"
              align="center"
              key="startTime"
              prop="startTime"
              width="150"
            >
              <template #default="scope">
                {{ proxy.formatDateStr(scope.row.startTime, 'YYYY-MM-DD') }}
              </template>
            </el-table-column>
            <el-table-column
              label="有效期至"
              align="center"
              key="endTime"
              prop="endTime"
              width="150"
            >
              <template #default="scope">
                {{ proxy.formatDateStr(scope.row.endTime, 'YYYY-MM-DD') }}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" key="remake" prop="remake" width="130">
              <template #default="scope">
                <el-form-item
                  :prop="`purchaseinventoryList.${scope.$index}.remake`"
                  :rules="tableRules.remake"
                >
                  <el-input
                    v-model="scope.row.remake"
                    placeholder=""
                    @blur="remakeBlur(scope.row, scope.$index)"
                    :disabled="viewStatus == 'view'"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              v-if="viewStatus != 'view'"
              label="操作"
              align="center"
              width="80"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleScan(scope.row, scope.$index)"
                  >扫码</el-button
                >
              </template>
            </el-table-column>
            <!-- <el-table-column
                label="操作"
                align="center"
                width="80"
                class-name="small-padding fixed-width"
                fixed="right"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleSave(scope.row, scope.$index)"
                    v-hasPermi="['system:user:edit']"
                    >保存</el-button
                  >
                </template>
              </el-table-column> -->
          </el-table>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredData.length"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-row
      :gutter="10"
      class="mb8"
      style="margin-top: 15px; display: flex; align-items: center; justify-content: flex-start"
    >
      <el-col :span="3">
        <span>制单人：{{ userStore.name }}</span>
      </el-col>
      <el-col :span="2">
        <span>审核人：</span>
      </el-col>
      <el-col :span="2">
        <span>单据状态：</span>
      </el-col>
      <el-col :span="6">
        <el-row :gutter="8" style="display: flex; align-items: center; justify-content: flex-start">
          <el-col :span="10">
            <span>合计金额：{{ totalAmount ? totalAmount.toFixed(4) : 0 }}</span>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <TraceNoDialog
      :ypName="ypName"
      :openDialog="openTraceNoDialog"
      :rowData="rowData"
      @submit="submit"
      @cancel="openTraceNoDialog = false"
    />
    <!-- </el-dialog> -->
  </div>
</template>

<script setup name="batchTransfer">
import {
  addTransferProductBatch,
  delTransferProduct,
  getBusNoInit,
  getDispensaryList,
  getInit,
  getPharmacyList,
  getTransferProductDetail,
  getTransferProductDetails,
  productTransferApproved,
  reject,
  submitApproval,
} from '../components/transferManagement';
import {formatDate} from '@/utils/index';
import useUserStore from '@/store/modules/user';
import {useStore} from '@/store/store';
import useTagsViewStore from '@/store/modules/tagsView';
import TraceNoDialog from '@/components/OpenHis/TraceNoDialog/index.vue';

const tagsViewStore = useTagsViewStore();
const store = useStore();
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const openTraceNoDialog = ref(false);
const ypName = ref('');
const currentIndex = ref('');
const rowData = ref({});

const { proxy } = getCurrentInstance();
const { warehous_type, category_code, service_type_code, specialty_code, purchase_type } =
  proxy.useDict(
    'warehous_type',
    'category_code',
    'service_type_code',
    'specialty_code',
    'purchase_type'
  );
const viewStatus = ref('');
// 总页数
const totalPages = ref(0);
// 总数据条数
const totalSize = ref(0);
// 存放列表数据
const tableData = ref([]);
// 当前页码
const pageNum = ref(1);
// 每页显示数据
const pageSize = ref(20);
const purchaseinventoryList = ref([]);
const open = ref(false);
const loading = ref(false);
const ids = ref([]);
const rowList = ref([]);

const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const visible = ref(false);
const row = ref({});
const rowIndex = ref(-1);
const totalAmount = ref(0);
const pageLoading = ref(false);

const form = reactive({
  purchaseinventoryList: [],
});

const forms = reactive({
  purchaseinventoryList: [],
});
const receiptHeaderForm = reactive({
  busNo: undefined,
  occurrenceTime: formatDate(new Date()),
});

const data = reactive({
  isEdit: false,
  isAdding: true,
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    sourceLocationId: '',
    purposeLocationId: '',
    medicationType: '',
    // searchKey: undefined, // 供应商名称
    // busNo: undefined, // 编码
    // statusEnum: undefined, // 状态
    // supplierId: undefined, //
    // occurrence_time: undefined, // 申请时间
    // practitionerId: undefined, // 经手人ID
  },
  rules: {
    purposeLocationId: [{ required: true, message: '请选择目的仓库', trigger: 'change' }],
    sourceLocationId: [{ required: true, message: '请选择源仓库', trigger: 'change' }],
    medicationType: [{ required: true, message: '请选择药品类型', trigger: 'change' }],
  },
  tableRules: {
    // name: [{ required: true, message: '项目不能为空', trigger: 'change' }],
    // totalpackagingLevels: [
    //   { required: true, message: "规格不能为空", trigger: "blur" },
    // ],
    // unitCode: [{ required: true, message: '计量单位不能为空', trigger: 'change' }],
    // itemQuantityDisplay: [{ required: true, message: '调拨数量不能为空', trigger: 'blur' }],
    // lotNumber: [
    //   { required: true, message: "产品批号不能为空", trigger: "blur" },
    // ],
    // traceNo: [{ required: true, message: "追溯码不能为空", trigger: "blur" }],
    // startTime: [
    //   { required: true, message: "开始时间不能为空", trigger: "blur" },
    // ],
    // endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
    // price: [{ required: true, message: "单价不能为空", trigger: "blur" }],
    // totalPrice: [{ required: true, message: "总价不能为空", trigger: "blur" }],
  },
});

const { queryParams, rules, tableRules } = toRefs(data);
const purposeTypeListOptions = ref(undefined);
const sourceTypeListOptions = ref(undefined);
const sourceLocationStoreIdListOptions = ref(undefined);
const purposeLocationStoreIdListOptions = ref(undefined);
const categoryListOptions = ref(undefined);

const selectedRows = ref([]); // 用于存储选中的行
const emit = defineEmits(['refresh']);
const tableRef = ref(undefined); // 表格引用
const currentRow = ref(undefined); // 当前操作的行
const medicineSearchKey = ref('');
const itemType = ref('');
const totalIncentoryInfoList = ref([]);

watch(
  () => store.currentDataPLDB,
  (newVlaue) => {
    if (newVlaue && !route.query.supplyBusNo) {
      form.purchaseinventoryList = newVlaue?.purchaseinventoryList;
      receiptHeaderForm.busNo = newVlaue?.receiptHeaderForm.busNo;
      receiptHeaderForm.occurrence_time = newVlaue?.receiptHeaderForm.occurrence_time;
      receiptHeaderForm.sourceTypeEnum = newVlaue?.receiptHeaderForm.sourceTypeEnum;
      handleChangeSourceTypeEnum(receiptHeaderForm.sourceTypeEnum, 1);
      receiptHeaderForm.sourceLocationId = newVlaue?.receiptHeaderForm.sourceLocationId;
      receiptHeaderForm.purposeTypeEnum = newVlaue?.receiptHeaderForm.purposeTypeEnum;
      handleChangePurposeTypeEnum(receiptHeaderForm.purposeTypeEnum, 1);
      receiptHeaderForm.purposeLocationId = newVlaue?.receiptHeaderForm.purposeLocationId;
      receiptHeaderForm.medicationType = newVlaue?.receiptHeaderForm.medicationType;
    }
  },
  { immediate: true }
);
watch(
  () => store.currentDataPLDBALL,
  (newVlaue) => {
    if (newVlaue && !route.query.supplyBusNo) {
      forms.purchaseinventoryList = newVlaue?.purchaseinventoryList;
    }
  },
  { immediate: true }
);

// 监听路由变化
watch(
  () => route.query,
  (newValue) => {
    if (newValue.isEdit) {
      data.isEdit = true;
      pageLoading.value = true;
      getTransferProductDetail({ busNo: newValue.supplyBusNo, pageSize: 1000, pageNo: 1 }).then(
        (res) => {
          editTable(res.data.records);
          receiptHeaderForm.busNo = newValue.supplyBusNo;
          receiptHeaderForm.sourceTypeEnum = res.data.records[0].sourceTypeEnum.toString();
          receiptHeaderForm.sourceLocationId = res.data.records[0].sourceLocationId;
          receiptHeaderForm.purposeTypeEnum = res.data.records[0].purposeTypeEnum.toString();
          receiptHeaderForm.purposeLocationId = res.data.records[0].purposeLocationId;
          receiptHeaderForm.occurrenceTime = proxy.formatDateStr(
            res.data.records[0].applyTime,
            'YYYY-MM-DD HH:mm:ss'
          );
          handleChangePurposeTypeEnum(receiptHeaderForm.purposeTypeEnum, 1);
          handleChangeSourceTypeEnum(receiptHeaderForm.sourceTypeEnum, 1);
          pageLoading.value = false;
        }
      );
    }
  },
  { immediate: true }
);

function handelApply() {
  pageLoading.value = true;
  productTransferApproved(route.query.supplyBusNo)
    .then((res) => {
      pageLoading.value = false;
      if (res.code == 200) {
        proxy.$modal.msgSuccess('操作成功');
        store.clearCurrentDataPLDB();
        store.clearCurrentDataPLDBAll();
        // 跳转到审核页面
        router.replace({
          path: '/financialManagement/medicationmanagement/billapproval',
          query: { type: 'batchTransfer' },
        });
      }
    })
    .catch(() => {
      pageLoading.value = false;
    });
}

// 驳回
function handleReject() {
  reject(route.query.supplyBusNo).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('操作成功');
      store.clearCurrentDataPLDB();
      store.clearCurrentDataPLDBAll();
      // 跳转到审核页面
      router.replace({
        path: '/financialManagement/medicationmanagement/billapproval',
        query: { type: 'batchTransfer' },
      });
    }
  });
}
/** 提交审核按钮 */
function handleSubmitApproval() {
  let length = totalIncentoryInfoList.value.length;
  if (length < 1) {
    proxy.$modal.msgWarning('请先添加单据');
  } else if (data.isEdit) {
    proxy.$modal.msgWarning('单据未保存');
  } else {
    submitApproval(receiptHeaderForm.busNo).then((response) => {
      proxy.$modal.msgSuccess('提交审批成功');
      // proxy.$tab.closePage(route).then(({ visitedViews }) => {  // 关闭当前页
      //   toLastView(visitedViews, route)
      // })
      tagsViewStore.delView(router.currentRoute.value);
      // 跳转到调拨管理页面
      router.replace({ path: 'transferManagentList' });
    });
  }
}

// 切换仓库类型获取药房/药库列表   目的仓库切换
function handleChangePurposeTypeEnum(value, type) {
  if (value == 16) {
    getPharmacyList().then((res) => {
      purposeTypeListOptions.value = res.data;
      if (!route.query.supplyBusNo && !type) {
        receiptHeaderForm.purposeLocationId = '';
        receiptHeaderForm.purposeLocationId1 = '';
      }
    }).catch(error => {
      console.error('Error fetching pharmacy list:', error);
    });
  } else if (value == 11) {
    getDispensaryList().then((res) => {
      purposeTypeListOptions.value = res.data;
      if (!route.query.supplyBusNo && !type) {
        receiptHeaderForm.purposeLocationId = '';
        receiptHeaderForm.purposeLocationId1 = '';
      }
    }).catch(error => {
      console.error('Error fetching dispensary list:', error);
    });
  } else {
    purposeTypeListOptions.value = [];
  }
}
// 源仓库切换
function handleChangeSourceTypeEnum(value, type) {
  if (value == 16) {
    getPharmacyList().then((res) => {
      sourceTypeListOptions.value = res.data;
      if (!route.query.supplyBusNo && !type) {
        receiptHeaderForm.sourceLocationId = '';
        receiptHeaderForm.sourceLocationId1 = '';
      }
    }).catch(error => {
      console.error('Error fetching pharmacy list:', error);
    });
  } else if (value == 11) {
    getDispensaryList().then((res) => {
      sourceTypeListOptions.value = res.data;
      if (!route.query.supplyBusNo && !type) {
        receiptHeaderForm.sourceLocationId = '';
        receiptHeaderForm.sourceLocationId1 = '';
      }
    }).catch(error => {
      console.error('Error fetching dispensary list:', error);
    });
  } else {
    sourceTypeListOptions.value = [];
  }
}
function editBatchTransfer(index) {
  if (queryParams.value.pageNo == 1) {
    forms.purchaseinventoryList[index] = form.purchaseinventoryList[index];
  } else {
    let editIndex =
      (Number(queryParams.value.pageNo) - 1) * Number(queryParams.value.pageSize) + index;
    forms.purchaseinventoryList[editIndex] = form.purchaseinventoryList[index];
  }
}
// 单位处理
function handleUnitCodeChange(row, index, value) {
  if (row.unitCodeMap[value] == 'unit') {
    row.totalSourceQuantityDisplay = formatInventory(
      row.totalSourceQuantity,
      row.partPercent,
      row.unitCode_dictText,
      row.minUnitCode_dictText
    );
    row.totalPurposeQuantityDisplay = formatInventory(
      row.totalPurposeQuantity,
      row.partPercent,
      row.unitCode_dictText,
      row.minUnitCode_dictText
    );
    row.itemQuantityDisplay = formatInventory(
      row.itemQuantity,
      row.partPercent,
      row.unitCode_dictText,
      row.minUnitCode_dictText
    );
  } else {
    row.totalSourceQuantityDisplay = row.totalSourceQuantity;
    row.totalPurposeQuantityDisplay = row.totalPurposeQuantity;
    row.itemQuantityDisplay = row.itemQuantity;
  }
  // 更新总数据中对应的记录
  const totalIndex = totalIncentoryInfoList.value.findIndex((item) => item.id === row.id);
  if (totalIndex !== -1) {
    totalIncentoryInfoList.value[totalIndex].unitCode = value;
  }
}

function handleItemQuantityChange(row, value) {
  debugger;
  let quantityTemp = ''; // 转换成小单位的临时变量 做校验
  // 大单位情况
  if (row.unitCodeMap[row.unitCode] == 'unit') {
    // 校验调拨数量不能大于原库存数量
    quantityTemp = row.partPercent * value;
    row.itemQuantity = quantityTemp;
  } else {
    row.itemQuantity = value;
    quantityTemp = value;
  }
  if (row.totalSourceQuantity < quantityTemp) {
    proxy.$modal.msgWarning('调拨数量不可超出源库存数量');
    row.itemQuantity = 0;
    row.itemQuantityDisplay = 0;
    return;
  }
  row.totalPrice = ((row.price * quantityTemp) / row.partPercent).toFixed(2);
  // 更新总数据中对应的记录
  const totalIndex = totalIncentoryInfoList.value.findIndex((item) => item.id === row.id);
  if (totalIndex !== -1) {
    totalIncentoryInfoList.value[totalIndex].itemQuantity = quantityTemp;
  }
}

// 计算总价
function handleTotalPrice(index) {
  form.purchaseinventoryList[index].olditemQuantity =
    form.purchaseinventoryList[index].itemQuantity * row.partPercent;
  form.purchaseinventoryList[index].itemMaxQuantity =
    form.purchaseinventoryList[index].itemQuantity;
  let purchaseItem = form.purchaseinventoryList[index];
  if (purchaseItem.price > 0 && purchaseItem.itemQuantity > 0) {
    form.purchaseinventoryList[index].totalPrice = purchaseItem.price * purchaseItem.itemQuantity;
    form.purchaseinventoryList[index].totalPrice =
      form.purchaseinventoryList[index].totalPrice.toFixed(2);
  }
  if (form.purchaseinventoryList[index].itemQuantity == 0) {
    form.purchaseinventoryList[index].totalPrice = 0;
  }
  editBatchTransfer(index);
}
//批量调拨修改备注
function remakeBlur(row, index) {
  editBatchTransfer(index);
}
function handleSave() {
  // if (form.purchaseinventoryList.length == 0) {
  //   proxy.$message.warning('请先生成批量调拨单在进行批量保存！');
  //   return;
  // }
  addTransferProductBatch(totalIncentoryInfoList.value).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('保存成功');
      data.isEdit = false;
    }
  });
}

function deleteSelectedRows() {
  let length = selectedRows.value.length;
  let ids = [];
  if (selectedRows.value[0].id) {
    ids = selectedRows.value.map((item) => {
      return item.id;
    });
  }
  if (selectedRows.value[length - 1].isSave) {
    delTransferProduct(ids).then((res) => {
      if (res.code == 200) {
        proxy.$message.success('删除成功');
      }
    });
  } else {
    if (length > 1 && ids && ids.length > 0) {
      delTransferProduct(ids).then((res) => {
        if (res.code == 200) {
          proxy.$message.success('删除成功');
        }
      });
    }
  }
  form.purchaseinventoryList = form.purchaseinventoryList.filter(
    (row) => !selectedRows.value.includes(row)
  );

  if (form.purchaseinventoryList && form.purchaseinventoryList.length > 0) {
    data.isEdit = true;
  } else {
    data.isEdit = false;
  }

  data.isAdding = false;
}

/**计算合计金额 */
function handleTotalAmount() {
  totalAmount.value = form.purchaseinventoryList.reduce((accumulator, currentRow) => {
    return accumulator + (Number(currentRow.totalPrice) || 0);
  }, 0);
}
function handleScan(row, index) {
  rowData.value = row;
  rowData.value.locationId = receiptHeaderForm.sourceLocationId;
  rowData.value.itemType = receiptHeaderForm.medicationType;
  ypName.value = row.name;
  openTraceNoDialog.value = true;
  currentIndex.value = index;
}
function submit(value) {
  if (form.purchaseinventoryList[currentIndex.value].traceNo) {
    form.purchaseinventoryList[currentIndex.value].traceNo =
      form.purchaseinventoryList[currentIndex.value].traceNo + ',' + value;
  } else {
    form.purchaseinventoryList[currentIndex.value].traceNo = value;
  }
  openTraceNoDialog.value = false;
}

function handleBatchAdd() {
  proxy.$refs['receiptHeaderRef'].validate((valid) => {
    if (valid) {
      data.isEdit = true; // 设置标志位为 true，表示有未保存的
      getBatchList();
    }
  });
}

const filteredData = ref([]); // 筛选后的数据
const currentPage = ref(1);
// 计算属性
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handlePageChange = (page) => {
  currentPage.value = page;
};

function getBatchList(type) {
  getBusNoInit().then((response) => {
    receiptHeaderForm.busNo = response.data.busNo;
  });
  queryParams.value = receiptHeaderForm;
  queryParams.value.pageNo = 1;
  queryParams.value.pageSize = 1000;
  pageLoading.value = true;
  getTransferProductDetails(queryParams.value).then((res) => {
    totalIncentoryInfoList.value = res.data.records.map((item) => {
      return {
        ...item,
        busNo: receiptHeaderForm.busNo,
        sourceTypeEnum: receiptHeaderForm.sourceTypeEnum,
        sourceLocationId: receiptHeaderForm.sourceLocationId,
        purposeTypeEnum: receiptHeaderForm.purposeTypeEnum,
        purposeLocationId: receiptHeaderForm.purposeLocationId,
        itemTable:
          receiptHeaderForm.medicationType == 1
            ? 'med_medication_definition'
            : 'adm_device_definition',
        occurrenceTime: proxy.formatDateStr(
          receiptHeaderForm.occurrenceTime,
          'YYYY-MM-DD HH:mm:ss'
        ),
        applyTime: proxy.formatDateStr(item.applyTime, 'YYYY-MM-DD HH:mm:ss'),
        applicantId: userStore.id,
        startTime: proxy.formatDateStr(item.startTime, 'YYYY-MM-DD HH:mm:ss'),
        endTime: proxy.formatDateStr(item.endTime, 'YYYY-MM-DD HH:mm:ss'),
        totalPrice: ((item.itemQuantity * item.price) / item.partPercent).toFixed(2),
        totalSourceQuantityDisplay: formatInventory(
          item.totalSourceQuantity,
          item.partPercent,
          item.unitCode_dictText,
          item.minUnitCode_dictText
        ),
        totalPurposeQuantityDisplay: formatInventory(
          item.totalPurposeQuantity,
          item.partPercent,
          item.unitCode_dictText,
          item.minUnitCode_dictText
        ),
        itemQuantityDisplay: formatInventory(
          item.itemQuantity,
          item.partPercent,
          item.unitCode_dictText,
          item.minUnitCode_dictText
        ),
        // 维护一个大小单位的map，用来判断当前选中单位是大/小单位
        unitCodeMap: {
          [item.unitCode]: 'unit',
          [item.minUnitCode]: 'minUnit',
        },
        unitList: [
          { label: item.unitCode_dictText, value: item.unitCode },
          {
            label: item.minUnitCode_dictText,
            value: item.minUnitCode,
          },
        ],
      };
    });
    filteredData.value = [...totalIncentoryInfoList.value];
    total.value = res.data.total;
    pageLoading.value = false;
  });
}

function editTable(detailsList) {
  pageLoading.value = true;
  totalIncentoryInfoList.value = detailsList.map((item) => {
    return {
      ...item,
      busNo: receiptHeaderForm.busNo,
      sourceTypeEnum: receiptHeaderForm.sourceTypeEnum,
      sourceLocationId: receiptHeaderForm.sourceLocationId,
      purposeTypeEnum: receiptHeaderForm.purposeTypeEnum,
      purposeLocationId: receiptHeaderForm.purposeLocationId,
      itemTable:
        receiptHeaderForm.medicationType == 1
          ? 'med_medication_definition'
          : 'adm_device_definition',
      occurrenceTime: proxy.formatDateStr(receiptHeaderForm.occurrenceTime, 'YYYY-MM-DD HH:mm:ss'),
      applyTime: proxy.formatDateStr(item.applyTime, 'YYYY-MM-DD HH:mm:ss'),
      applicantId: userStore.id,
      startTime: proxy.formatDateStr(item.startTime, 'YYYY-MM-DD HH:mm:ss'),
      endTime: proxy.formatDateStr(item.endTime, 'YYYY-MM-DD HH:mm:ss'),
      totalSourceQuantityDisplay: formatInventory(
        item.totalSourceQuantity,
        item.partPercent,
        item.unitCode_dictText,
        item.minUnitCode_dictText
      ),
      totalPurposeQuantityDisplay: formatInventory(
        item.totalPurposeQuantity,
        item.partPercent,
        item.unitCode_dictText,
        item.minUnitCode_dictText
      ),
      itemQuantityDisplay: formatInventory(
        item.itemQuantity,
        item.partPercent,
        item.unitCode_dictText,
        item.minUnitCode_dictText
      ),
      // 维护一个大小单位的map，用来判断当前选中单位是大/小单位
      unitCodeMap: {
        [item.unitCode]: 'unit',
        [item.minUnitCode]: 'minUnit',
      },
      unitList: [
        { label: item.unitCode_dictText, value: item.unitCode },
        {
          label: item.minUnitCode_dictText,
          value: item.minUnitCode,
        },
      ],
    };
  });
  pageLoading.value = false;
  filteredData.value = [...totalIncentoryInfoList.value];
}

/**
 * 格式化库存数量显示(大单位情况)
 * @param quantity 小单位库存数量
 * @param partPercent 拆零比
 * @param unitCode 大单位
 * @param minUnitCode 小单位
 */
function formatInventory(quantity, partPercent, unitCode, minUnitCode) {
  // 处理负数情况
  const isNegative = quantity < 0;
  const absQuantity = Math.abs(quantity);

  if (absQuantity % partPercent !== 0) {
    const integerPart = Math.floor(absQuantity / partPercent);
    const decimalPart = absQuantity % partPercent;

    let result = integerPart.toString() + ' ' + unitCode;
    if (decimalPart > 0) {
      result += decimalPart.toString() + ' ' + minUnitCode;
    }

    return isNegative ? '-' + result : result;
  }

  // 整除情况
  const result = absQuantity / partPercent;
  return isNegative ? '-' + result : result;
}

// 选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 清空选择
const clearSelection = () => {
  proxy.$refs['tableRef'].clearSelection();
};

// 批量删除
const handleDelete = async () => {
  debugger;
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的项目');
    return;
  }

  // 获取要删除的ID列表
  const deleteIds = selectedRows.value.map((item) => item.id);

  // 从总数据中删除
  totalIncentoryInfoList.value = totalIncentoryInfoList.value.filter(
    (item) => !deleteIds.includes(item.id)
  );

  // 从筛选数据中删除
  filteredData.value = filteredData.value.filter((item) => !deleteIds.includes(item.id));

  // 清空选中行
  selectedRows.value = [];

  ElMessage.success(`成功删除 ${deleteIds.length} 个项目`);

  // 如果当前页没有数据了，且不是第一页，则跳转到前一页
  if (currentPageData.value.length === 0 && currentPage.value > 1) {
    currentPage.value -= 1;
  }
};

/** 删除按钮操作 */
// function handleDelete(row) {
//   const delId = row.id || ids.value;
//   proxy.$modal
//     .confirm('是否确认删除以上数据?')
//     .then(function () {
//       return delTransferProduct({ ids: delId.join(',') });
//     })
//     .then(() => {
//       proxy.$modal.msgSuccess('删除成功');
//     })
//     .catch(() => {});
// }
/** 调拨管理查询下拉树结构 */
function getTransferProductTypeList() {
  data.isAdding = false;
  getInit().then((response) => {
    categoryListOptions.value = response.data.categoryListOptions;
  });
}

getTransferProductTypeList();
// 导出
const exportRequiredParams = ref({
  pageNo: 1,
  pageSize: 10,
  busNo: route.query.supplyBusNo,
});
function handleExport() {
  proxy.downloadGet(
    '/inventory-manage/transfer/excel-out',
    {
      ...exportRequiredParams.value,
    },
    `批量调拨单据明细记录_${proxy.formatDateStr(new Date(), 'YYYY-MM-DD')}.xlsx`
  );
}
</script>
<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
}

.title {
  font-weight: bold;
  font-size: large;
  margin-bottom: 10px;
}

.error-border {
  border: 1px solid red;
}

.el-row.pagination {
  height: 100px;
}
.pagehand {
  height: 100px;
  line-height: 100px;
}
</style>