<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="supplierId">
            <el-select v-model="queryParams.supplierId" placeholder="请选择" clearable filterable>
              <el-option
                v-for="item in supplierIDList"
                :key="item.supplyId"
                :label="item.supplyName"
                :value="item.supplyId"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <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">新增</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="definitionList.length > 0"
                >保存</el-button
              >
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList"
            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="itemName" align="center">
              <template #default="scope">
                <PopoverList @search="handleSearch" :width="1000" :modelValue="scope.row.itemName">
                  <template #popover-content>
                    <medicineList
                      ref="medicineListRef"
                      @selectRow="(row) => selectRow(row, scope.$index)"
                      :searchKey="medicineSearchKey"
                      :supplierId="queryParams.supplierId"
                    />
                  </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="totalVolume" align="center">
              <template #default="scope">
                {{ scope.row.totalVolume ? scope.row.totalVolume : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="当前价格" prop="retailPrice" align="center">
              <template #default="scope">
                {{ scope.row.retailPrice ? scope.row.retailPrice : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后价格" prop="afterPrice" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.afterPrice" type="number" step="0.01" />
              </template>
            </el-table-column>
            <el-table-column label="调价理由" prop="price" align="center">
              <template #default="scope">
                <el-input
                  type="textarea"
                  v-model="scope.row.adjustReason"
                  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-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList"
            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="编码" width="200" prop="chargeName" align="center">
              <template #default="scope">
                {{ scope.row.chargeName ? scope.row.chargeName : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="名称" width="200" prop="orgId_dictText" align="center">
              <template #default="scope">
                <PopoverList @search="handleSearch" :width="1000" :modelValue="scope.row.itemName">
                  <template #popover-content>
                    <medicineList
                      ref="medicineListRef"
                      @selectRow="(row) => selectRow(row, scope.$index)"
                      :searchKey="medicineSearchKey"
                      :supplierId="queryParams.supplierId"
                    />
                  </template>
                </PopoverList>
              </template>
            </el-table-column>
            <el-table-column label="规格" width="200" prop="typeCode_dictText" align="center">
              <template #default="scope">
                {{ scope.row.typeCode_dictText ? scope.row.typeCode_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="当前价格" width="200" prop="ybType_dictText" align="center">
              <template #default="scope">
                {{ scope.row.ybType_dictText ? scope.row.ybType_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后价格" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调价理由" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调整时间" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="290"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template #default="scope">
                <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
              </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-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList"
            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="编码" width="200" prop="chargeName" align="center">
              <template #default="scope">
                {{ scope.row.chargeName ? scope.row.chargeName : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="名称" width="200" prop="orgId_dictText" align="center">
              <template #default="scope">
                {{ scope.row.orgId_dictText ? scope.row.orgId_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="规格" width="200" prop="typeCode_dictText" align="center">
              <template #default="scope">
                {{ scope.row.typeCode_dictText ? scope.row.typeCode_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="当前价格" width="200" prop="ybType_dictText" align="center">
              <template #default="scope">
                {{ scope.row.ybType_dictText ? scope.row.ybType_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后价格" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调价理由" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调整时间" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="290"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template #default="scope">
                <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
              </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-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
          </el-row>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="definitionList"
            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="编码" width="200" prop="chargeName" align="center">
              <template #default="scope">
                {{ scope.row.chargeName ? scope.row.chargeName : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="名称" width="200" prop="orgId_dictText" align="center">
              <template #default="scope">
                {{ scope.row.orgId_dictText ? scope.row.orgId_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="规格" width="200" prop="typeCode_dictText" align="center">
              <template #default="scope">
                {{ scope.row.typeCode_dictText ? scope.row.typeCode_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="当前价格" width="200" prop="ybType_dictText" align="center">
              <template #default="scope">
                {{ scope.row.ybType_dictText ? scope.row.ybType_dictText : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调后价格" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调价理由" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="调整时间" width="200" prop="price" align="center">
              <template #default="scope">
                {{ scope.row.price ? thousandNumber(scope.row.price) : '-' }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="290"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template #default="scope">
                <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
              </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>
    <el-dialog :title="title" v-model="openDetails" width="600px" append-to-body>
      <el-table
        v-loading="detailLoading"
        :data="definitionDetailList"
        tooltip-effect="dark"
        :show-overflow-tooltip="true"
      >
        <el-table-column label="条件" prop="conditionCode_enumText" align="center">
          <template #default="scope">
            {{ scope.row.conditionCode_enumText ? scope.row.conditionCode_enumText : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="价格" width="200" prop="amount" align="center">
          <template #default="scope">
            {{ scope.row.amount ? scope.row.amount : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <edit
      :title="title"
      :open="open"
      :formData="form"
      @submit="submitForm"
      @update:open="handleOpenChange"
      @update:form="handleFormChange"
    />
  </div>
</template>
<script setup>
import { listDefinition, initOption, updateDefinition, getSupplierList } from './components/api';
import PopoverList from '@/components/OpenHis/popoverList/index.vue';
import medicineList from './components/medicineList.vue';
import { thousandNumber } from '@/utils/his.js';
import useUserStore from '@/store/modules/user';
const activeName = ref('1');
const showSearch = ref(true);
const loading = ref(true);
const detailLoading = ref(true);
const refreshTable = ref(true);
const definitionList = ref([]);
const definitionDetailList = ref([]);
const total = ref(0);
const tableRef = ref(null);
const selectedRows = ref([]);
// 获取 pinia 中用户信息
const userInfo = useUserStore();
// 申请人
const applicationName = ref(userInfo.nickName);
const { proxy } = getCurrentInstance();
const options = ref([]);
const title = ref('');
const open = ref(false);
const openDetails = ref(false);

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

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

/** 查询委托单信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.chargeItemContext = activeName.value;
  listDefinition(queryParams.value).then((response) => {
    definitionList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    itemNo: null,
    chargeName: null,
    totalVolume: null,
    unitCode: null,
    partPercent: null,
    conditionYbCode: null,
    price: null,
    amount: null,
    partMinUnitCode: null,
    partConditionPrice: null,
    partPrice: null,
    description: null,
    statusEnum: null,
    itemId: null,
  };
  proxy.resetForm('einfoRef');
}
// 品名搜索
const medicineSearchKey = ref('');
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = row;
  open.value = true;
  title.value = '修改项目定价';
}
/** 搜索按钮操作 */
function handleInit() {
  queryParams.value.definitionType = activeName.value;
  loading.value = true;
  initOption(queryParams.value).then((response) => {
    options.value = response.data.publicationStatusOptions;
    loading.value = false;
  });
}

const handleOpenChange = (value) => {
  open.value = value;
};

const handleFormChange = (newForm) => {
  form.value = { ...newForm };
};

// 表格多选与删除
function handleSelectionChange(selection) {
  selectedRows.value = selection || [];
}
// 删除选中行
function handleDelete() {
  if (!selectedRows.value.length) {
    proxy.$message.warning('请选择要删除的行');
    return;
  }
  definitionList.value = definitionList.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) {
  console.log('选中行数据：', row);
  if (!definitionList.value[index]) return;
  // 根据业务字段同步选中行信息
  definitionList.value[index] = {
    ...definitionList.value[index],
    itemId: row.id,
    itemName: row.itemName || row.name || '',
    ...row,
  };
}

// 新增按钮操作
function handleAdd() {
  // if (!queryParams.value.supplierId) {
  //   proxy.$message.error('请选择供应商！');
  //   return;
  // }
  reset();
  // 新增一行
  definitionList.value.push({
    id: null,
    itemNo: null,
    chargeName: null,
    totalVolume: null,
    unitCode: null,
    partPercent: null,
    conditionYbCode: null,
    price: null,
    amount: null,
    partMinUnitCode: null,
    partConditionPrice: null,
    partPrice: null,
    description: null,
    statusEnum: null,
    itemId: null,
  });
}

/** 提交按钮 */
function submitForm(form) {
  updateDefinition(form).then((response) => {
    proxy.$modal.msgSuccess('操作成功');
    open.value = false;
    getList();
  });
}

// 保存前校验与保存
function handleSave() {
  console.log(queryParams.value.supplierId, 'queryParams.value.supplierId');
  // 供应商必选
  if (!queryParams.value.supplierId) {
    proxy.$message.error('请选择供应商');
    return;
  }
  // 至少一行
  if (!definitionList.value || !definitionList.value.length) {
    proxy.$message.warning('请先新增行再保存');
    return;
  }
  // 按行校验
  for (let i = 0; i < definitionList.value.length; i++) {
    const row = definitionList.value[i] || {};
    const rowIndex = i + 1;
    // 名称/项目必填
    if (!row.itemId && !row.itemName) {
      proxy.$message.error(`第${rowIndex}行：请选择名称`);
      return;
    }
    // 调后价格校验（数字且>=0）
    const priceNum = Number(row.afterPrice);
    if (!Number.isFinite(priceNum) || priceNum < 0) {
      proxy.$message.error(`第${rowIndex}行：请输入有效的调后价格（>=0）`);
      return;
    }
    // 与当前价格相同给出提示（但不强制）
    if (Number(row.retailPrice) === priceNum) {
      proxy.$message.warning(`第${rowIndex}行：调后价格与当前价格相同`);
    }
    // 调价理由必填
    if (!row.adjustReason || String(row.adjustReason).trim() === '') {
      proxy.$message.error(`第${rowIndex}行：请输入调价理由`);
      return;
    }
    // 调整时间必选
    if (!row.adjustTime) {
      proxy.$message.error(`第${rowIndex}行：请选择调整时间`);
      return;
    }
    // 价格规范化为两位小数（不改变展示，仅在保存前处理）
    row.afterPrice = Number(priceNum.toFixed(2));
  }
  // 所有校验通过
  proxy.$message.success('校验通过');
  // TODO: 在此调用保存接口（当前仅打印）
  console.log('保存数据：', definitionList.value);
}
// 供应商列表
const supplierIDList = ref([]);
// 获取供应商列表
function getSupplierIDList() {
  loading.value = true;
  getSupplierList().then((res) => {
    supplierIDList.value = res.data;
    loading.value = false;
  });
}
handleInit();
// 获取供应商列表
getSupplierIDList();
//getList();
</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>
