<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-form ref="queryRef" :model="queryParams" label-width="100px" :inline="true">
        <!-- 库房类型 -->
        <el-form-item label="库房类型" prop="locationTypeEnum">
          <el-select
            v-model="queryParams.locationTypeEnum"
            placeholder="请选择库房类型"
            clearable
            style="width: 240px"
            filterable
            @change="getList"
          >
            <el-option
              v-for="item in warehouseTypeOption || []"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 库房 -->
        <el-form-item label="库房" prop="locationId">
          <el-select
            v-model="queryParams.locationId"
            placeholder="请选择库房"
            clearable
            style="width: 240px"
            :disabled="!queryParams.locationTypeEnum"
            @change="getList"
          >
            <el-option
              v-for="item in currentLocationOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 单据类型 -->
        <el-form-item label="单据类型" prop="typeEnum">
          <el-select
            v-model="queryParams.typeEnum"
            placeholder="请选择单据类型"
            clearable
            style="width: 240px"
            :disabled="!queryParams.locationTypeEnum"
            @change="getList"
          >
            <el-option
              v-for="item in currentOrderOptions"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态" prop="statusEnum">
          <el-select
            v-model="queryParams.statusEnum"
            placeholder="请选择单据类型"
            clearable
            style="width: 240px"
            @change="getList"
          >
            <el-option
              v-for="item in supplyStatusOptions"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 制单日期 -->
        <el-form-item label="制单日期" prop="orderDate">
          <el-date-picker
            v-model="orderDateRange"
            type="daterange"
            clearable
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <!-- 审核日期 -->
        <el-form-item label="审核日期" prop="approvalDate">
          <el-date-picker
            v-model="auditDateRange"
            type="daterange"
            clearable
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-table :data="orderList" v-loading="loading" style="width: 100%">
      <el-table-column label="订单编号" prop="supplyBusNo" align="center" />
      <el-table-column label="申请人" prop="applicantId_dictText" align="center" />
      <el-table-column label="申请时间" prop="applyTime" align="center" />
      <el-table-column label="批准时间" prop="approvalTime" align="center" />
      <el-table-column label="批准人" prop="approverId_dictText" align="center" />
      <el-table-column label="仓库" prop="locationId_dictText" align="center" />
      <el-table-column label="状态" prop="statusEnum_enumText" align="center">
        <template #default="scope">
          <el-tag :type="statusEnumTagOptions[scope.row.statusEnum]?.type || 'info'">
            {{ scope.row.statusEnum_enumText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="供应商" prop="supplierId_dictText" align="center" />
      <el-table-column label="单据类型" prop="typeEnum_enumText" align="center">
        <template #default="scope">
          <el-tag :type="typeEnumTagOptions[scope.row.typeEnum]?.type || 'info'">
            {{ scope.row.typeEnum_enumText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-if="isTypeEnumTagOptions(scope.row.typeEnum)"
            >查看</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"
    />
  </div>
</template>
<script setup>
import {computed, ref, watch} from 'vue';
import {useRouter} from 'vue-router';
import {getInit, getOrderList} from './components/api';
import {parseTime} from '@/utils/openhis';

const router = useRouter();
// 制单日期
const orderDateRange = ref([]);
// 审核日期
const auditDateRange = ref([]);
// 查询参数
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  locationTypeEnum: null,
  typeEnum: null,
  locationId: null,
});
// tag列表
const typeEnumTagOptions = ref({
  13: { value: 13, label: '采购订货', type: 'primary' },
  1: { value: 1, label: '采购入库', type: 'success' },
  5: { value: 5, label: '采购退货', type: 'danger' },
  7: { value: 7, label: '领用出库', type: 'warning' },
  9: { value: 9, label: '领用退货', type: 'success' },
  6: { value: 6, label: '报损单', type: 'info' },
  4: { value: 4, label: '商品盘点', type: 'warning' },
  // 2: { value: 2, label: '商品调拨', type: 'info' },
});
// tag列表
const statusEnumTagOptions = ref({
  1: { value: 1, label: '待审核', type: 'warning' },
  2: { value: 2, label: '审核中', type: 'primary' },
  3: { value: 3, label: '同意', type: 'success' },
  4: { value: 4, label: '驳回', type: 'danger' },
  9: { value: 9, label: '已撤回', type: 'info' },
  10: { value: 10, label: '待审请', type: 'warning' },
});
// 判断单据类型是否在 typeEnumTagOptions 中
const isTypeEnumTagOptions = (type) => {
  return Number(type) in typeEnumTagOptions.value;
};
// 当前选中的库房类型对应的单据类型选项
const currentOrderOptions = computed(() => {
  if (!queryParams.value.locationTypeEnum || !warehouseTypeOption.value.length) {
    return [];
  }
  const currentType = warehouseTypeOption.value.find(
    (item) => item.value === queryParams.value.locationTypeEnum
  );
  return currentType ? currentType.orderOption || [] : [];
});

// 当前选中的库房类型对应的库房选项
const currentLocationOptions = computed(() => {
  if (!queryParams.value.locationTypeEnum || !warehouseTypeOption.value.length) {
    return [];
  }
  const currentType = warehouseTypeOption.value.find(
    (item) => item.value === queryParams.value.locationTypeEnum
  );
  return currentType ? currentType.locationOption || [] : [];
});
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  orderDateRange.value = [];
  auditDateRange.value = [];
  queryParams.value.locationTypeEnum = null;
  queryParams.value.typeEnum = null;
  queryParams.value.locationId = null;
  handleQuery();
};
// 下拉框数据
const warehouseTypeOption = ref([]);
// 单据状态
const supplyStatusOptions = ref([]);
// 初始化
const init = async () => {
  try {
    const res = await getInit();
    warehouseTypeOption.value = res.data.warehouseTypeOption;
    supplyStatusOptions.value = res.data.supplyStatusOptions;
  } catch (error) {
    console.error('初始化失败:', error);
  }
};
// 订单列表
const orderList = ref([]);
const total = ref(0);
// 加载状态
const loading = ref(false);
// 获取列表
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams.value,
      applyTimeSTime:
        orderDateRange.value && parseTime(orderDateRange.value[0], '{y}-{m}-{d}')
          ? parseTime(orderDateRange.value[0], '{y}-{m}-{d}')
          : null,
      applyTimeETime:
        orderDateRange.value && parseTime(orderDateRange.value[1], '{y}-{m}-{d}')
          ? parseTime(orderDateRange.value[1], '{y}-{m}-{d}')
          : null,
      approvalTimeSTime:
        auditDateRange.value && parseTime(auditDateRange.value[0], '{y}-{m}-{d}')
          ? parseTime(auditDateRange.value[0], '{y}-{m}-{d}')
          : null,
      approvalTimeETime:
        auditDateRange.value && parseTime(auditDateRange.value[1], '{y}-{m}-{d}')
          ? parseTime(auditDateRange.value[1], '{y}-{m}-{d}')
          : null,
    };
    const res = await getOrderList(params);
    // 赋值
    orderList.value = res.data.records;
    // 总数
    total.value = res.data.total;
  } catch (error) {
    console.error('获取列表失败:', error);
  } finally {
    loading.value = false;
  }
};
// 查看
const handleView = (row) => {
  switch (Number(row.typeEnum)) {
    case 13:
      // 采购订货
      router.push({ path: '/medicineStorage/purchaseOrder/', query: { busNo: row.supplyBusNo } });
      break;
    case 1:
      // 采购入库
      router.push({ path: '/medicineStorage/stockInOrder/', query: { busNo: row.supplyBusNo } });
      break;
    case 5:
      // 采购退货
      router.push({ path: '/medicineStorage/returnOrder/', query: { busNo: row.supplyBusNo } });
      break;
    case 7:
      // 领用出库
      router.push({ path: '/medicineStorage/stockOutOrder/', query: { busNo: row.supplyBusNo } });
      break;
    case 9:
      // 领用退货
      router.push({
        path: '/medicineStorage/returnToWarehouseOrder/',
        query: { busNo: row.supplyBusNo },
      });
      break;
    case 6:
      // 报损单
      router.push({ path: '/medicineStorage/profitLossOrder/', query: { busNo: row.supplyBusNo } });
      break;
    case 4:
      // 商品盘点
      router.push({
        path: '/medicineStorage/stocktakingOrder/',
        query: { busNo: row.supplyBusNo },
      });
      break;
    default:
      console.log('未知的单据类型:', row.typeEnum);
      break;
  }
};

// 监听库房类型变化，清空相关选项
watch(
  () => queryParams.value.locationTypeEnum,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      queryParams.value.typeEnum = null;
      queryParams.value.locationId = null;
    }
  }
);

init();
getList();
</script>