<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <div class="left-container">
      <el-form
        style="margin-top:20px;margin-left:20px;"
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="90px"
      >
        <el-form-item label="开始时间：">
          <el-date-picker
            v-model="queryParams.dispenseDateSTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px;"
            :clearable="false"
            @change="handleTimeChange('start')"
          />
        </el-form-item>
        <el-form-item label="结束时间：">
          <el-date-picker
            v-model="queryParams.dispenseDateETime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px;"
            :clearable="false"
            @change="handleTimeChange('end')"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleQuery"
          >查询</el-button>
          <el-button
            type="warning"
            icon="CircleClose"
            @click="handleClear"
          >重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        style="padding:0 20px;width:100%;margin-top:20px;"
        v-loading="leftLoading"
        :data="leftTableData"
        @row-click="handleRowClick"
      >
        <el-table-column label="科室名" prop="orgName" :show-overflow-tooltip="true" />
        <el-table-column label="耗材和药品总金额" prop="totalMoney" :show-overflow-tooltip="true">
          <template #default="scope">
            <span class="link" @click.stop="handleRowClick(scope.row)">{{ scope.row.totalMoney }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
      </el-col>
      <el-col :span="20">
            <div class="right-container">
      <el-form
        style="margin-top:20px;margin-left:20px;"
        :model="rightQueryParams"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="项目名：">
          <el-input
            v-model="rightQueryParams.name"
            placeholder="请输入项目名称"
            clearable
            style="width: 200px;"
            @keyup.enter="handleRightQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleRightQuery"
          >查询</el-button>
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              :disabled="!rightQueryParams.orgId"
              >导出Excel</el-button
            >
        </el-form-item>
      </el-form>

      <el-table
        style="padding:0 20px;margin-top:20px;"
        v-loading="rightLoading"
        :data="rightTableData"
      >
        <el-table-column label="项目名" prop="name" width="180" :show-overflow-tooltip="true" />
        <el-table-column label="规格" prop="totalVolume" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="产品型号" prop="lotNumber" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="生产厂家" prop="manufacturerText" width="500" :show-overflow-tooltip="true" />
        <el-table-column label="数量" prop="totalQuantity" width="100" :show-overflow-tooltip="true" />
        <el-table-column label="单位" prop="unitCode_dictText" width="100" :show-overflow-tooltip="true" />
        <el-table-column label="单价" prop="unitPrice" width="100" :show-overflow-tooltip="true" />
        <el-table-column label="项目总价" prop="totalMoney" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="所属科室" prop="orgId_dictText" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="发放时间" prop="dispenseTime" width="240" :show-overflow-tooltip="true">
          <template #default="scope">
            <span>{{ formatIsoDate(scope.row.dispenseTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加右侧分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="rightQueryParams.pageNo"
          v-model:page-size="rightQueryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="rightTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
      </el-col>
    </el-row>


  </div>
</template>

<script setup name="pharmacyStatisticsDetails">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getMedDevInfo, getMedDevAll } from './statisticalManagent';

const router = useRouter();
const { proxy } = getCurrentInstance();

// 左侧列表数据
const leftTableData = ref([]);
const leftLoading = ref(false);
const selectedRow = ref(null);

// 右侧列表数据
const rightTableData = ref([]);
const rightLoading = ref(false);
// 添加右侧总条数
const rightTotal = ref(0);

// 查询参数
// 初始化时就设置默认时间，防止被清空
const today = new Date();
const lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
const data = reactive({
  queryParams: {
    dispenseDateSTime: formatDate(lastMonth),
    dispenseDateETime: formatDate(today),
  },
  rightQueryParams: {
    name: '',
    orgId: '',
    dispenseDateSTime: '',
    dispenseDateETime: '',
    // 添加分页参数
    pageNo: 1,
    pageSize: 20
  },
});

const { queryParams, rightQueryParams } = toRefs(data);

// 添加时间变化处理函数
function handleTimeChange(type) {
  if (type === 'start' && !queryParams.value.dispenseDateSTime) {
    queryParams.value.dispenseDateSTime = formatDate(lastMonth);
  } else if (type === 'end' && !queryParams.value.dispenseDateETime) {
    queryParams.value.dispenseDateETime = formatDate(today);
  }
}

// 获取左侧统计数据
function getLeftList() {
  leftLoading.value = true;
  getMedDevAll(queryParams.value).then((res) => {
    leftTableData.value = res.data.data || [];
    leftLoading.value = false;
  }).catch(() => {
    leftLoading.value = false;
  });
}

// 获取右侧详情数据
function getRightList() {
  rightLoading.value = true;
  getMedDevInfo(rightQueryParams.value).then((res) => {
    console.log(res)
    rightTableData.value = res.data.records || [];
    // 设置总条数
    rightTotal.value = res.data.total || 0;
    rightLoading.value = false;
  }).catch(() => {
    rightLoading.value = false;
  });
}

// 左侧列表查询
function handleQuery() {
  getLeftList();
}

// 左侧列表清空 - 修改为不清空时间
function handleClear() {
  // 不再清空时间字段
  proxy.resetForm("queryRef", ['dispenseDateSTime', 'dispenseDateETime']);
  getLeftList();
}

// 点击左侧行
function handleRowClick(row) {
  selectedRow.value = row;
  // 设置右侧查询参数
  rightQueryParams.value.orgId = row.orgId;
  rightQueryParams.value.dispenseDateSTime = queryParams.value.dispenseDateSTime;
  rightQueryParams.value.dispenseDateETime = queryParams.value.dispenseDateETime;
  // 重置页码
  rightQueryParams.value.pageNo = 1;
  // 查询右侧数据
  getRightList();
}

// 右侧列表查询
function handleRightQuery() {
  getRightList();
}

// 初始加载
onMounted(() => {
  // 设置默认时间为近一个月
  const endDate = new Date();
  const startDate = new Date();
  startDate.setMonth(startDate.getMonth() - 1);
  queryParams.value.dispenseDateSTime = formatDate(startDate);
  queryParams.value.dispenseDateETime = formatDate(endDate);
  getLeftList();
});

// 格式化日期为YYYY-MM-DD HH:mm:ss
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 格式化ISO日期字符串为YYYY-MM-DD HH:mm:ss
function formatIsoDate(isoString) {
  if (!isoString) return '';
  try {
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('Invalid ISO date string:', isoString);
    return isoString;
  }
}

// 分页处理函数
function handleSizeChange(val) {
  rightQueryParams.value.pageSize = val;
  getRightList();
}

function handleCurrentChange(val) {
  rightQueryParams.value.pageNo = val;
  getRightList();
}
/** 导出按钮操作 */
function handleExport() {
  proxy.$download.downloadGet("/report-manage/medication-device/excel-out", {
    ...rightQueryParams.value,
  }, `config_${new Date().getTime()}.xlsx`);
}
</script>

<style scoped>
.app-container {
  display: flex;
  gap: 20px;
  height: 100%;
}

.left-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.left-container .el-table {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden; /* 添加这行来隐藏水平滚动条 */
  margin-top: 20px;
  width: 100%; /* 确保表格宽度适应容器 */
}

.right-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.right-container .el-table {
  flex: 1;
  overflow: auto;
}

.link {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
  margin-right: 20px;
}
</style>