<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="药品调价" name="1">
          <el-form-item label="申请人" prop="applicationName" label-width="100px">
            <el-input v-model="applicationName" placeholder="" disabled />
          </el-form-item>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                :disabled="!isAdjustPrice"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                @click="handleDelete"
                v-if="selectedRows.length > 0"
              >
                删除选中行
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Check"
                @click="handleSave"
                v-if="definitionList1.length > 0"
                >保存</el-button
              >
              <el-button
                type="success"
                plain
                icon="Check"
                @click="handleSubmitForReview(definitionList1)"
                v-if="definitionList1.length > 0"
                style="margin-left: 10px"
                >提审</el-button
              >
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList1"
            tooltip-effect="dark"
            :show-overflow-tooltip="true"
            ref="tableRef"
            @selection-change="handleSelectionChange"
            style="width: 100% !important"
          >
            <el-table-column type="selection" width="40" align="center" fixed="left" />
            <el-table-column label="名称" prop="name" align="center">
              <template #default="scope">
                <span v-if="scope.row.isEdit == undefined || !scope.row.isEdit">{{
                  scope.row.name
                }}</span>
                <PopoverList
                  v-else
                  @search="handleSearch"
                  :width="1000"
                  :modelValue="scope.row.name"
                >
                  <template #popover-content>
                    <medicineList
                      ref="medicineListRef"
                      @selectRow="(row) => selectRow(row, scope.$index)"
                      :searchKey="medicineSearchKey"
                      :supplierId="queryParams.supplierId"
                      :categoryEnum="24"
                    />
                  </template>
                </PopoverList>
              </template>
            </el-table-column>
            <el-table-column label="编码" prop="busNo" align="center">
              <template #default="scope">
                {{ scope.row.busNo ? scope.row.busNo : '-' }}
              </template>
            </el-table-column>

            <el-table-column label="规格" prop="volume" align="center">
              <template #default="scope">
                {{ scope.row.volume ? scope.row.volume : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="当前进货价" prop="originBuyingPrice" align="center">
              <template #default="scope">
                {{ scope.row.originBuyingPrice ? scope.row.originBuyingPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后进货价" prop="newBuyingPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.newBuyingPrice" type="number" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="当前零售价" prop="originRetailPrice" align="center">
              <template #default="scope">
                {{ scope.row.originRetailPrice ? scope.row.originRetailPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后零售价" prop="newRetailPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.newRetailPrice" type="numbefr" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="调价理由" prop="reason" align="center">
              <template #default="scope">
                <el-input
                  type="textarea"
                  v-model="scope.row.reason"
                  :rows="1"
                  maxlength="255"
                  autosize
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
        <el-tab-pane label="耗材调价" name="2">
          <el-form-item label="申请人" prop="applicationName" label-width="100px">
            <el-input v-model="applicationName" placeholder="" disabled />
          </el-form-item>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                :disabled="!isAdjustPrice"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                @click="handleDelete"
                v-if="selectedRows.length > 0"
              >
                删除选中行
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Check"
                @click="handleSave"
                v-if="definitionList2.length > 0"
                >保存</el-button
              >
              <el-button
                type="success"
                plain
                icon="Check"
                @click="handleSubmitForReview(definitionList2)"
                v-if="definitionList2.length > 0"
                style="margin-left: 10px"
                >提审</el-button
              >
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList2"
            tooltip-effect="dark"
            :show-overflow-tooltip="true"
            ref="tableRef"
            @selection-change="handleSelectionChange"
            style="width: 100% !important"
          >
            <el-table-column type="selection" width="40" align="center" fixed="left" />
            <el-table-column label="名称" prop="name" align="center">
              <template #default="scope">
                <span v-if="scope.row.isEdit == undefined || !scope.row.isEdit">{{
                  scope.row.name
                }}</span>
                <PopoverList
                  v-else
                  @search="handleSearch"
                  :width="1000"
                  :modelValue="scope.row.name"
                >
                  <template #popover-content>
                    <medicineList
                      ref="medicineListRef"
                      @selectRow="(row) => selectRow(row, scope.$index)"
                      :searchKey="deviceSearchKey"
                      :supplierId="queryParams.supplierId"
                      :categoryEnum="25"
                    />
                  </template>
                </PopoverList>
              </template>
            </el-table-column>
            <el-table-column label="编码" prop="busNo" align="center">
              <template #default="scope">
                {{ scope.row.busNo ? scope.row.busNo : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="规格" prop="volume" align="center">
              <template #default="scope">
                {{ scope.row.volume ? scope.row.volume : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="当前进货价" prop="originBuyingPrice" align="center">
              <template #default="scope">
                {{ scope.row.originBuyingPrice ? scope.row.originBuyingPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后进货价" prop="newBuyingPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.newBuyingPrice" type="number" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="当前零售价" prop="originRetailPrice" align="center">
              <template #default="scope">
                {{ scope.row.originRetailPrice ? scope.row.originRetailPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后零售价" prop="newRetailPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.newRetailPrice" type="numbefr" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="调价理由" prop="reason" align="center">
              <template #default="scope">
                <el-input
                  type="textarea"
                  v-model="scope.row.reason"
                  :rows="1"
                  maxlength="255"
                  autosize
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
        <el-tab-pane label="诊疗调价" name="3">
          <el-form-item label="申请人" prop="applicationName" label-width="100px">
            <el-input v-model="applicationName" placeholder="" disabled />
          </el-form-item>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                :disabled="!isAdjustPrice"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                @click="handleDelete"
                v-if="selectedRows.length > 0"
              >
                删除选中行
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Check"
                @click="handleSave"
                v-if="definitionList3.length > 0"
                >保存</el-button
              >
              <el-button
                type="success"
                plain
                icon="Check"
                @click="handleSubmitForReview(definitionList3)"
                v-if="definitionList3.length > 0"
                style="margin-left: 10px"
                >提审</el-button
              >
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList3"
            tooltip-effect="dark"
            :show-overflow-tooltip="true"
            ref="tableRef"
            @selection-change="handleSelectionChange"
            style="width: 100% !important"
          >
            <el-table-column type="selection" width="40" align="center" fixed="left" />
            <el-table-column label="名称" prop="name" align="center">
              <template #default="scope">
                <span v-if="scope.row.isEdit == undefined || !scope.row.isEdit">{{
                  scope.row.name
                }}</span>
                <PopoverList
                  v-else
                  @search="handleSearch"
                  :width="1000"
                  :modelValue="scope.row.name"
                >
                  <template #popover-content>
                    <medicineList
                      ref="medicineListRef"
                      @selectRow="(row) => selectRow(row, scope.$index)"
                      :searchKey="medicineSearchKey"
                      :supplierId="queryParams.supplierId"
                      :categoryEnum="26"
                    />
                  </template>
                </PopoverList>
              </template>
            </el-table-column>
            <el-table-column label="编码" prop="busNo" align="center">
              <template #default="scope">
                {{ scope.row.busNo ? scope.row.busNo : '-' }}
              </template>
            </el-table-column>

            <el-table-column label="当前零售价" prop="originRetailPrice" align="center">
              <template #default="scope">
                {{ scope.row.originRetailPrice ? scope.row.originRetailPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后零售价" prop="newRetailPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.newRetailPrice" type="numbefr" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="调价理由" prop="reason" align="center">
              <template #default="scope">
                <el-input
                  type="textarea"
                  v-model="scope.row.reason"
                  :rows="1"
                  maxlength="255"
                  autosize
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
        <el-tab-pane label="挂号调价" name="4">
          <el-form-item label="申请人" prop="applicationName" label-width="100px">
            <el-input v-model="applicationName" placeholder="" disabled />
          </el-form-item>
          <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                :disabled="!isAdjustPrice"
                >新增</el-button
              >
            </el-col> -->
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                @click="handleDelete"
                v-if="selectedRows.length > 0"
              >
                删除选中行
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Check"
                @click="handleSave"
                v-if="definitionList4.length > 0"
                >保存</el-button
              >
              <el-button
                type="success"
                plain
                icon="Check"
                @click="handleSubmitForReview(definitionList4)"
                v-if="definitionList4.length > 0"
                style="margin-left: 10px"
                >提审</el-button
              >
            </el-col>
          </el-row>

          <!-- 科室下拉框单独显示 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="6">
              <el-form-item label="选择科室" label-width="80px">
                <el-select
                  v-model="selectedOrgId"
                  placeholder="请选择科室"
                  clearable
                  style="width: 200px"
                  @change="handleSelectOrg"
                  filterable
                  :disabled="!isAdjustPrice"
                >
                  <el-option
                    v-for="org in orgDataList"
                    :key="org.orgId"
                    :label="org.orgName"
                    :value="org.orgId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList4"
            tooltip-effect="dark"
            :show-overflow-tooltip="true"
            ref="tableRef"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="40" align="center" fixed="left" />
            <el-table-column label="名称" prop="orgName" align="center">
              <template #default="scope">
                <span>
                  {{ scope.row.orgName ? scope.row.orgName : '-' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="类型" min-width="120" align="center">
              <template #default="scope">
                <el-select
                  v-model="scope.row.targetId"
                  placeholder="请选择类型"
                  clearable
                  style="width: 100px"
                  v-if="scope.row.isEdit && scope.row.orgId"
                  @change="handleTypeChange(scope.row)"
                >
                  <el-option
                    v-for="item in healthDataList"
                    :key="item.targetId"
                    :label="item.name"
                    :value="item.targetId"
                  />
                </el-select>
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="当前零售价" prop="originRetailPrice" align="center">
              <template #default="scope">
                {{ scope.row.originRetailPrice ? scope.row.originRetailPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后零售价" prop="newRetailPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.newRetailPrice" type="numbefr" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="调价理由" prop="reason" align="center">
              <template #default="scope">
                <el-input
                  type="textarea"
                  v-model="scope.row.reason"
                  :rows="1"
                  maxlength="255"
                  autosize
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>
<script setup>
import {
  listDefinition,
  initOption,
  commitChangePriceData,
  commitExamineChangePriceData,
  searchAllOrgData,
  searchHealthData,
  checkMedApprovalExist,
  checkDeviceApprovalExist,
  checkActivityApprovalExist,
  getInitAdjustPriceSwitchState,
} from './components/api';
import PopoverList from '@/components/OpenHis/popoverList/index.vue';
import medicineList from './components/medicineList.vue';
import useUserStore from '@/store/modules/user';
import { ref, watch } from 'vue';
import { da } from 'element-plus/es/locales.mjs';
const activeName = ref('1');
const router = useRouter();
const showSearch = ref(true);
const loading = ref(true);
const refreshTable = ref(true);
const definitionList1 = ref([]);
const definitionList2 = ref([]);
const definitionList3 = ref([]);
const definitionList4 = ref([]);
const total = ref(0);
const tableRef = ref(null);
const selectedRows = ref([]);
// 挂号调价相关数据
const orgDataList = ref([]); // 科室数据列表
const healthDataList = ref([]); // 类型数据列表
// 选中的科室ID
const selectedOrgId = ref(null);
const orgLoading = ref(false); // 科室数据加载状态
const healthLoading = ref(false); // 类型数据加载状态
// 获取 pinia 中用户信息
const userInfo = useUserStore();
// 申请人
const applicationName = ref(userInfo.nickName);
const { proxy } = getCurrentInstance();
const options = ref([]);

const data = reactive({
  queryParams: {
    search: '',
    definitionType: '',
    chargeItem: '',
    searchKey: '',
    pageNo: 1,
    pageSize: 10,
  },
});

const { queryParams, form } = toRefs(data);
// 切换tab
const handleClick = (tab, event) => {
  activeName.value = tab.props.name;
  queryParams.value.pageNo = 1;
  reset();
  handleInit();
};

/** 查询委托单信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.chargeItemContext = activeName.value;
  listDefinition(queryParams.value)
    .then((response) => {
      if (Array.isArray(response.data)) {
        definitionList1.value = response.data;
        total.value = response.data.length;
      } else {
        definitionList1.value = response.data.records || [];
        total.value = response.data.total || 0;
      }
      loading.value = false;
    })
    .catch((error) => {
      loading.value = false;
    });
}

// 品名搜索
const medicineSearchKey = ref('');
const deviceSearchKey = ref('');

/** 搜索按钮操作 */
function handleInit() {
  queryParams.value.definitionType = activeName.value;
  loading.value = true;
  initOption(queryParams.value).then((response) => {
    options.value = response.data.publicationStatusOptions;
    loading.value = false;
  });
}

// 表格多选与删除
function handleSelectionChange(selection) {
  selectedRows.value = selection || [];
}
// 删除选中行
function handleDelete() {
  if (!selectedRows.value.length) {
    proxy.$message.warning('请选择要删除的行');
    return;
  }

  // 根据当前激活的标签页删除对应列表中的选中行
  if (activeName.value === '1') {
    definitionList1.value = definitionList1.value.filter(
      (row) => !selectedRows.value.includes(row)
    );
  } else if (activeName.value === '2') {
    definitionList2.value = definitionList2.value.filter(
      (row) => !selectedRows.value.includes(row)
    );
  } else if (activeName.value === '3') {
    definitionList3.value = definitionList3.value.filter(
      (row) => !selectedRows.value.includes(row)
    );
  } else if (activeName.value === '4') {
    definitionList4.value = definitionList4.value.filter(
      (row) => !selectedRows.value.includes(row)
    );
  }

  selectedRows.value = [];
  nextTick(() => {
    tableRef.value && tableRef.value.clearSelection && tableRef.value.clearSelection();
  });
}

// 弹出选择器引用与交互
const medicineListRef = ref(null);
function handleSearch(keyword) {
  medicineSearchKey.value = keyword || '';
}
function selectRow(row, index) {
  // 根据当前激活的标签页更新对应列表的数据
  if (activeName.value === '1' && definitionList1.value[index]) {
    //验证当前药品是否已经提交申请
    checkMedApprovalExist(row.targetId).then((res) => {
      if (res.code !== 200) {
        proxy.$message.warning('【该药品已存在未审核的调价申请，请勿重复添加】' + res.msg);
        return;
      } else {
        // 药品调价
        definitionList1.value[index] = {
          ...definitionList1.value[index],
          ...row,
        };
      }
    });
  }
  if (activeName.value === '2' && definitionList2.value[index]) {
    checkDeviceApprovalExist(row.targetId).then((res) => {
      if (res.code !== 200) {
        proxy.$message.warning('【该耗材已存在未审核的调价申请，请勿重复添加】' + res.msg);
        return;
      } else {
        // 耗材调价
        definitionList2.value[index] = {
          ...definitionList2.value[index],
          ...row,
        };
      }
    });
  }
  if (activeName.value === '3' && definitionList3.value[index]) {
    checkActivityApprovalExist(row.targetId).then((res) => {
      if (res.code !== 200) {
        proxy.$message.warning('【该诊疗已存在未审核的调价申请，请勿重复添加】' + res.msg);
        return;
      } else {
        // 诊疗调价
        definitionList3.value[index] = {
          ...definitionList3.value[index],
          ...row,
        };
      }
    });
  }
  // 强制刷新，确保保存按钮状态正确更新
  nextTick(() => {
    refreshTable.value = false;
    setTimeout(() => {
      refreshTable.value = true;
    }, 0);
  });
}

// 获取科室数据
async function loadOrgData() {
  if (orgDataList.value.length === 0) {
    orgLoading.value = true;
    try {
      const response = await searchAllOrgData();
      if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
        orgDataList.value = response.data;
      } else {
        proxy.$message.warning('获取科室数据失败');
        orgDataList.value = [];
      }
    } catch (error) {
      proxy.$message.error('获取科室数据失败，请重试');
      orgDataList.value = [];
    } finally {
      orgLoading.value = false;
    }
  }
}

// 获取类型数据
async function loadHealthData(orgId) {
  if (!orgId) return;
  healthLoading.value = true;
  try {
    const response = await searchHealthData({ orgId });
    if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
      healthDataList.value = response.data;
    } else {
      proxy.$message.warning('获取类型数据失败');
      healthDataList.value = [];
    }
  } catch (error) {
    proxy.$message.error('获取类型数据失败，请重试');
    healthDataList.value = [];
  } finally {
    healthLoading.value = false;
  }
}

// 科室下拉框选择处理函数
function handleSelectOrg(orgId) {
  // 清空列表
  definitionList4.value = [];
  if (orgId) {
    // 加载该科室的挂号类型数据
    loadHealthData(orgId).then(() => {
      // 为每个类型创建一行数据并追加到列表
      definitionList4.value = [...healthDataList.value];
    });
  }
}

// 类型选择变化处理
function handleTypeChange(row) {
  if (row.targetId) {
    const selectedItem = healthDataList.value.find((item) => item.targetId === row.targetId);
    if (selectedItem) {
      row.orgName = selectedItem.orgName;
      row.originRetailPrice = selectedItem.price;
    }
  }
}

// 新增按钮操作
function handleAdd() {
  // 根据当前激活的标签页决定向哪个列表添加新行
  const newRow = {
    isEdit: true,
  };
  if (activeName.value === '1') {
    // 药品调价
    definitionList1.value.push(newRow);
  } else if (activeName.value === '2') {
    // 耗材调价
    definitionList2.value.push(newRow);
  } else if (activeName.value === '3') {
    definitionList3.value.push(newRow);
  } else if (activeName.value === '4') {
    let orgName = '';
    if (definitionList4.value.length !== 0) {
      orgName = definitionList4.value[0].orgName;
    }
    // 挂号调价 - 直接添加新行
    definitionList4.value.push({
      ...newRow,
      // 挂号调价特殊字段
      orgId: selectedOrgId.value,
      orgName,
    });
  }
}
// 保存按钮操作校验
function validateList(currentList, categoryType) {
  let isValid = true;
  for (let i = 0; i < currentList.length; i++) {
    const row = currentList[i] || {};
    const rowIndex = i + 1;
    console.log(categoryType);
    if (categoryType !== 2 && categoryType !== 3) {
      if (!row.newBuyingPrice || row.newBuyingPrice <= 0) {
        proxy.$message.error(`第${rowIndex}行：请输入正确的调后进货价`);
        isValid = false;
        break;
      }
    }

    if (!row.newRetailPrice || row.newRetailPrice <= 0) {
      proxy.$message.error(`第${rowIndex}行：请输入正确的调后零售价`);
      isValid = false;
      break;
    }
    if (!row.reason || String(row.reason).trim() === '') {
      proxy.$message.error(`第${rowIndex}行：请输入调价理由`);
      isValid = false;
      break;
    }
  }
  return isValid;
}
// 保存前校验与保存
function handleSave() {
  let currentList = [];
  let categoryType = 0;

  // 根据当前激活的标签页选择对应的数据列表和类别类型
  if (activeName.value === '1') {
    currentList = definitionList1.value;
    categoryType = 0; // 药品
  } else if (activeName.value === '2') {
    currentList = definitionList2.value;
    categoryType = 1; // 耗材
  } else if (activeName.value === '3') {
    currentList = definitionList3.value;
    categoryType = 2; // 诊疗
  } else if (activeName.value === '4') {
    currentList = definitionList4.value;
    categoryType = 3; // 挂号
  }

  // 至少一行
  if (!currentList || !currentList.length) {
    proxy.$message.warning('请先新增行再保存');
    return;
  }

  // 按行校验
  let isValid = validateList(currentList, categoryType);

  if (!isValid) {
    return;
  }

  // 构造请求数据
  let requestData = (currentList || []).map((item) => {
    return {
      itemId: item.targetId,
      categoryType,
      newBuyingPrice: item.newBuyingPrice,
      newRetailPrice: item.newRetailPrice,
      reason: item.reason,
      unitCode: item.unitCode,
    };
  });

  // 调用保存接口
  commitChangePriceData(requestData)
    .then((res) => {
      if (res && res.code === 200) {
        proxy.$message.success('保存成功');
        // 重置数据
        reset();
        // 强制刷新表格状态
        refreshTable.value = false;
        setTimeout(() => {
          refreshTable.value = true;
        }, 0);
      } else {
        proxy.$message.error(res?.message || '保存失败');
      }
    })
    .catch((error) => {
      console.error('保存接口调用失败:', error);
      proxy.$message.error('保存失败，请重试');
    });
}

// 提交审核前校验与保存
function handleSubmitForReview(dataList) {
  let currentList = dataList;
  let categoryType = 0;

  // 根据当前激活的标签页设置类别类型
  if (activeName.value === '1') {
    categoryType = 0; // 药品
  } else if (activeName.value === '2') {
    categoryType = 1; // 耗材
  } else if (activeName.value === '3') {
    categoryType = 2; // 诊疗
  } else if (activeName.value === '4') {
    categoryType = 3; // 挂号
  }

  // 至少一行
  if (!currentList || !currentList.length) {
    proxy.$message.warning('请先新增行再提审');
    return;
  }

  // 按行校验
  let isValid = validateList(currentList, categoryType);

  if (!isValid) {
    proxy.$message.success('校验未通过');
    return;
  }

  // 所有校验通过

  // 构造请求数据
  let requestData = (currentList || []).map((item) => {
    return {
      itemId: item.targetId,
      categoryType,
      newBuyingPrice: item.newBuyingPrice,
      newRetailPrice: item.newRetailPrice,
      reason: item.reason,
      unitCode: item.unitCode,
    };
  });
  // 调用提审接口
  commitExamineChangePriceData(requestData)
    .then((res) => {
      if (res && res.code === 200) {
        proxy.$message.success('提审成功');
        // 重置数据
        reset();
        // 强制刷新表格状态
        refreshTable.value = false;
        //保存成功后跳转到审核管理页面
        router.push(
          '/medicationmanagement/priceAdjustmentManagement/priceAdjustmentApprovalManagement'
        );
        setTimeout(() => {
          refreshTable.value = true;
        }, 0);
      } else {
        proxy.$message.error(res?.message || '提审失败');
      }
    })
    .catch((error) => {
      proxy.$message.error('提审失败，请重试');
    });
}
function reset() {
  definitionList1.value = [];
  definitionList2.value = [];
  definitionList3.value = [];
  definitionList4.value = [];
  selectedRows.value = [];
}
const isAdjustPrice = ref(true);
function getAdjustPriceSwitchState() {
  loading.value = true;
  getInitAdjustPriceSwitchState().then((res) => {
    // true 可以调价
    // false 不可以调价
    isAdjustPrice.value = res.data;
  });
}
getAdjustPriceSwitchState();
handleInit();
// 获取供应商列表
//getList();

// 监听activeName变化，当切换到挂号调价标签时加载科室数据
watch(
  () => activeName.value,
  (newVal) => {
    if (newVal === '4') {
      loadOrgData();
    }
  }
);
</script>
<style lang="scss" scoped>
:deep(.demo-tabs > .el-tabs__content) {
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
:deep(.el-input__wrapper) {
  height: 32px;
}
:deep(.el-input__inner) {
  height: 30px;
}
:deep(.el-tabs__content) {
  height: 80vh;
}
.el-select {
  width: 150px !important;
}
</style>
