<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" :rules="rules">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="purposeTypeEnum">
        <el-select
          v-model="queryParams.purposeTypeEnum"
          placeholder="请选择"
          clearable
          filterable
          style="width: 200px"
          @change="handleChangePurposeTypeEnum"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in warehous_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点仓库" prop="sourceLocationId">
        <el-select
          v-model="queryParams.sourceLocationId"
          placeholder="请选择"
          clearable
          filterable
          style="width: 200px"
          :disabled="!queryParams.purposeTypeEnum"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in purposeTypeListOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="货位" prop="purposeLocation">
        <el-select
          v-model="queryParams.purposeLocation"
          placeholder="请选择"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option v-for="item in []" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="请求日期" prop="applyTime">
        <el-date-picker
          v-model="queryParams.applyTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
        ></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 :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleSave()"
          :disabled="multiple"
          >批量保存</el-button
        >
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
      height="calc(100vh - 250px)"
    >
      <el-table-column type="selection" width="55" align="center" fixed></el-table-column>
      <el-table-column
        label="项目"
        align="center"
        key="name"
        prop="name"
        width="200"
        fixed
      ></el-table-column>
      <el-table-column label="规格" align="center" prop="totalVolume" />
      <el-table-column label="厂家/产地" align="center" prop="manufacturerText" show-overflow-tooltip />
      <el-table-column label="产品批号" align="center" prop="lotNumber" />
      <el-table-column label="单价(元)" align="center" key="unit" prop="unitPrice" />
      <el-table-column label="发放数量" align="center" prop="dispenseQuantity">
        <template #default="scope">
          {{ formatQuantityWithUnit(scope.row.dispenseQuantity, scope.row.minUnitCode_dictText) }}
        </template>
      </el-table-column>
      <el-table-column label="库存数量" align="center" prop="quantity">
        <template #default="scope">
          {{ formatQuantityWithUnit(scope.row.quantity, scope.row.minUnitCode_dictText) }}
        </template>
      </el-table-column>
      <el-table-column label="实盘数量" align="center" prop="stockTakeQuantity">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.stockTakeQuantity"
            :precision="0"
            :min="0"
            :input-style="{ textAlign: 'center' }"
            :controls="false"
            style="width: 100%"
            @keyup.enter="handleSave(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="盈亏数量" align="center" prop="profitLoss">
        <template #default="scope">
          {{ calcProfitLoss(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unitCode_dictText" />
      <el-table-column label="最小单位" align="center" prop="minUnitCode_dictText" />
      <el-table-column label="拆零比" align="center" prop="partPercent" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            icon="Check"
            @click="handleSave(scope.row)"
            v-hasPermi="['chkstock:partDeptDevice:edit']"
            >保存
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import {
  getStockTakeList,
  getPharmacyList,
  getDispensaryList,
  saveOrgDeviceSummary,
} from './components/api.js';
const { proxy } = getCurrentInstance();
const { warehous_type } = proxy.useDict('warehous_type');
const dataList = ref([]);
const queryParams = reactive({
  name: undefined,
  purposeTypeEnum: undefined,
  sourceLocationId: undefined,
  applyTime: [],
  applyTimeSTime: undefined,
  applyTimeETime: undefined,
});
const loading = ref(false);
const rules = ref({});
// 获取列表
const getList = () => {
  loading.value = true;
  const params = {
    ...queryParams,
    pageNo: queryParams.pageNo || 1,
    pageSize: queryParams.pageSize || 10,
    applyTime: undefined,
    applyTimeSTime: queryParams.applyTime[0] ? `${queryParams.applyTime[0]} 00:00:00` : undefined,
    applyTimeETime: queryParams.applyTime[1] ? `${queryParams.applyTime[1]} 23:59:59` : undefined,
  };
  getStockTakeList(params).then((res) => {
    loading.value = false;
    dataList.value = res.data;
  });
};
// 搜索
const handleQuery = () => {
  getList();
};

// 重置
const resetQuery = () => {
  Object.assign(queryParams, {
    name: undefined,
    purposeTypeEnum: undefined,
    sourceLocationId: undefined,
    applyTime: [],
  });
  handleQuery();
};

const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
// 多选
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const toNumber = (value) => {
  if (value === '' || value === null || value === undefined) return null;
  const num = Number(value);
  return Number.isNaN(num) ? null : num;
};
const formatQuantityWithUnit = (quantity, unitText) => {
  const num = toNumber(quantity);
  if (num === null) return '';
  return unitText ? `${num} ${unitText}` : `${num}`;
};
const calcProfitLoss = (row) => {
  const stockTakeQuantity = toNumber(row.stockTakeQuantity);
  const dispenseQuantity = toNumber(row.dispenseQuantity);
  if (stockTakeQuantity === null || dispenseQuantity === null) return '';
  const profitLoss = stockTakeQuantity - dispenseQuantity;
  return `${profitLoss} ${row.minUnitCode_dictText ?? ''}`;
};

const buildSummaryPayload = (rows) =>
  rows.map((item) => ({
    id: item.id,
    stockTakeQuantity: Number(item.stockTakeQuantity),
    useUnitCode: item.minUnitCode,
    ...item,
  }));

// 保存（单条/批量）
const handleSave = (row) => {
  const targetRows = row ? [row] : ids.value;

  if (!targetRows.length) {
    proxy.$modal.msgWarning('请选择需要保存的数据');
    return;
  }

  const invalidRow = targetRows.find(
    (item) =>
      item.stockTakeQuantity === '' ||
      item.stockTakeQuantity === null ||
      item.stockTakeQuantity === undefined
  );
  if (invalidRow) {
    proxy.$modal.msgWarning('实盘数量不能为空');
    return;
  }

  const payload = buildSummaryPayload(targetRows);
  proxy.$modal
    .confirm('确定保存吗？', '保存', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      saveOrgDeviceSummary(payload).then(() => {
        proxy.$modal.msgSuccess('保存成功');
        getList();
      });
    })
    .catch(() => {});
};
const purposeTypeListOptions = ref([]);
// 仓库类型切换
const handleChangePurposeTypeEnum = (val) => {
  // 药房
  if (val == '16') {
    getPharmacyList().then((res) => {
      purposeTypeListOptions.value = res.data;
    });
  } else if (val == '11') {
    getDispensaryList().then((res) => {
      purposeTypeListOptions.value = res.data;
    });
  }
  getList();
};

onMounted(() => {
  getList();
});
</script>
