<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="出库仓库" prop="warehouseId">
              <el-select v-model="queryParams.warehouseId" placeholder="请选择出库仓库" clearable @keyup.enter="handleQuery">
                <el-option v-for="item in warehouseInfoList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable @keyup.enter="handleQuery" filterable>
                <el-option
                  v-for="item in projectInfoList"
                  :key="item.projectId"
                  :label="`${item.projectCode} - ${item.projectName}`"
                  :value="item.projectId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物料名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="queryParams.customerId" placeholder="请选择客户" clearable @keyup.enter="handleQuery" filterable>
                <el-option v-for="item in customerInfoList" :key="item.customerId" :label="item.customerName" :value="item.customerId" />
              </el-select>
            </el-form-item>

            <el-form-item label="是否需要归还" prop="isReturn">
              <el-select v-model="queryParams.isReturn" placeholder="是/否" clearable @keyup.enter="handleQuery" filterable>
                <el-option v-for="item in sys_yes_no" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="样品状态" prop="sampleState">
              <el-select v-model="queryParams.sampleState" placeholder="请选择样品状态" clearable @keyup.enter="handleQuery" filterable>
                <el-option v-for="item in wms_sample_state" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 340px">
              <el-date-picker
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:sampleLedger:add']">新增 </el-button>
          </el-col>

          <!--<el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wms:sampleLedger:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wms:sampleLedger:remove']"
              >删除
            </el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:sampleLedger:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        border
        :data="sampleLedgerList"
        @selection-change="handleSelectionChange"
        @expand-change="handleExpandChange"
        :row-key="(row) => row.sampleLedgerId"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table v-loading="row.loading" border :data="row.data" :style="{ width: '95%', margin: '0 auto' }">
              <el-table-column label="处置类型" align="center" prop="disposalType">
                <template #default="scope">
                  <dict-tag :options="wms_disposal_type" :value="scope.row.disposalType" />
                </template>
              </el-table-column>
              <el-table-column label="时间" align="center" prop="createTime">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="处置数量" align="center" prop="disposalQty" />
              <el-table-column label="单位" align="center" prop="unitName" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="样品台账ID" align="center" prop="sampleLedgerId" v-if="columns[0].visible" />
        <el-table-column label="出库仓库" align="center" prop="warehouseId" v-if="columns[2].visible">
          <template #default="scope">
            <span>{{ getWarehouseName(scope.row.warehouseId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目编号" align="center" prop="projectCode" v-if="columns[3].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" v-if="columns[3].visible" />
        <el-table-column label="物料编码" align="center" prop="productCode" v-if="columns[4].visible" />
        <el-table-column label="物料名称" align="center" prop="productName" v-if="columns[4].visible" />
        <el-table-column label="物料描述" align="center" prop="productSpe" v-if="columns[4].visible" />
        <el-table-column label="批次号" align="center" prop="batchNumber" v-if="columns[5].visible" />
        <el-table-column label="借出数量" align="center" prop="lentQty" v-if="columns[6].visible" width="80" />
        <el-table-column label="未处理" align="center" prop="returnQty" v-if="columns[8].visible" width="80" />
        <el-table-column label="单位" align="center" prop="unitName" v-if="columns[7].visible" width="60" />
        <el-table-column label="客户" align="center" prop="customerId" v-if="columns[9].visible" width="120">
          <template #default="scope">
            <span>{{ getCustomerName(scope.row.customerId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="customerUser" v-if="columns[10].visible" width="70" />
        <el-table-column label="联系电话" align="center" prop="customerNumber" v-if="columns[11].visible" />
        <el-table-column label="用途" align="center" prop="lentRemark" v-if="columns[12].visible" />
        <el-table-column label="是否需要归还" align="center" prop="isReturn" v-if="columns[13].visible" width="80">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isReturn" />
          </template>
        </el-table-column>
        <el-table-column label="样品状态" align="center" prop="sampleState" v-if="columns[13].visible" width="80">
          <template #default="scope">
            <dict-tag :options="wms_sample_state" :value="scope.row.sampleState" />
          </template>
        </el-table-column>
        <el-table-column label="创建部门" align="center" prop="createDept" v-if="columns[15].visible" />
        <el-table-column label="创建人" align="center" prop="createBy" v-if="columns[16].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" v-if="columns[17].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updateBy" v-if="columns[18].visible" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="120" v-if="columns[19].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="处置样品" placement="top">
              <el-button link type="primary" icon="document" @click="handleUpdate(scope.row)" v-hasPermi="['wms:sampleLedger:edit']"></el-button>
            </el-tooltip>

            <!--<el-tooltip content="修改" placement="top">-->
            <!--  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:sampleLedger:edit']"></el-button>-->
            <!--</el-tooltip>-->
            <!--<el-tooltip content="删除" placement="top">-->
            <!--  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:sampleLedger:remove']"></el-button>-->
            <!--</el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改样品管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
      <el-form ref="sampleLedgerFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择出库仓库" clearable>
                <el-option v-for="item in warehouseInfoList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" filterable clearable>
                <el-option
                  v-for="item in projectInfoList"
                  :key="item.projectId"
                  :label="`${item.projectCode} - ${item.projectName}`"
                  :value="item.projectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" filterable clearable>
                <el-option v-for="item in customerInfoList" :key="item.customerId" :label="item.customerName" :value="item.customerId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否归还" prop="isReturn">
              <el-select v-model="form.isReturn" placeholder="请选择是否归还">
                <el-option v-for="item in sys_yes_no" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="customerUser">
              <el-input v-model="form.customerUser" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="customerNumber">
              <el-input v-model="form.customerNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="用途" prop="lentRemark">
          <el-input v-model="form.lentRemark" placeholder="请输入用途" type="textarea" row="3" />
        </el-form-item>
        <div>
          <el-card>
            <template #header>
              <div>添加出库物料</div>
            </template>
            <el-button type="primary" @click="openInventorySelect">选择物料</el-button>

            <div v-if="selectInventorys.length > 0" style="margin-top: 20px">
              <h4>已选择的物料：</h4>
              <el-table border :data="selectInventorys">
                <el-table-column label="批次号" align="center" prop="batchNumber" />
                <el-table-column label="物料编码" align="center" prop="productCode" />
                <el-table-column label="物料名称" align="center" prop="productName" />
                <el-table-column label="当前库存" align="center" prop="inventoryAmount" width="90" />
                <el-table-column label="借出数量" align="center" prop="outStockAmount" width="140">
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.lentQty"
                      :min="0"
                      :precision="2"
                      :step="1"
                      :max="scope.row.inventoryAmount"
                      controls-position="right"
                      size="small"
                      placeholder="请输入出库数量"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" prop="unitName" width="80" />
                <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="60">
                  <template #default="scope">
                    <el-button link type="danger" icon="Delete" @click="removeOutDetail(scope.$index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
          <wms-inventory-select ref="inventorySelectRef" :multiple="true" :warehouse-id="form.warehouseId" @confirmCallBack="handleInventorySelect" />
        </div>
        <!--        <el-form-item label="物料ID" prop="materielId">-->
        <!--          <el-input v-model="form.materielId" placeholder="请输入物料ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="批次号" prop="batchNumber">-->
        <!--          <el-input v-model="form.batchNumber" placeholder="请输入批次号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="借出数量" prop="lentQty">-->
        <!--          <el-input v-model="form.lentQty" placeholder="请输入借出数量" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="单位" prop="unitName">-->
        <!--          <el-input v-model="form.unitName" placeholder="请输入单位" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="未处理数量" prop="returnQty">-->
        <!--          <el-input v-model="form.returnQty" placeholder="请输入未处理数量" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 处置样品 -->
    <el-dialog title="处置样品" v-model="disposalDialog.visible" width="50%" append-to-body>
      <el-form ref="sampleLedgerFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库仓库">
              <el-select v-model="form.warehouseId" placeholder="请选择出库仓库" :disabled="true">
                <el-option v-for="item in warehouseInfoList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="true">
                <el-option
                  v-for="item in projectInfoList"
                  :key="item.projectId"
                  :label="`${item.projectCode} - ${item.projectName}`"
                  :value="item.projectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户">
              <el-select v-model="form.customerId" placeholder="请选择客户" :disabled="true">
                <el-option v-for="item in customerInfoList" :key="item.customerId" :label="item.customerName" :value="item.customerId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否归还" prop="isReturn">
              <el-select v-model="form.isReturn" placeholder="是否归还" :disabled="true">
                <el-option v-for="item in sys_yes_no" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="借出数量" prop="lentQty">
              <el-input v-model="form.lentQty" placeholder="请输入借出数量" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未处理数量" prop="returnQty">
              <el-input v-model="form.returnQty" placeholder="请输入未处理数量" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-card>
          <template #header>
            <div>样品处置结果</div>
          </template>
          <el-row>
            <el-col :span="12">
              <el-form-item label="处置类型" prop="disposalType">
                <el-select v-model="form.disposalType" placeholder="请选择处置类型">
                  <el-option v-for="dict in wms_disposal_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处置数量" prop="disposalQty">
                <el-input-number
                  v-model="form.disposalQty"
                  placeholder="请输入处置数量"
                  :min="0"
                  :precision="2"
                  :step="1"
                  :max="form.returnQty || 0"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!--        <el-form-item label="物料ID" prop="materielId">-->
        <!--          <el-input v-model="form.materielId" placeholder="请输入物料ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="批次号" prop="batchNumber">-->
        <!--          <el-input v-model="form.batchNumber" placeholder="请输入批次号" />-->
        <!--        </el-form-item>-->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SampleLedger" lang="ts">
import { addSampleLedger, delSampleLedger, getSampleLedger, listSampleLedger, updateSampleLedger } from '@/api/wms/sampleLedger';
import { SampleLedgerForm, SampleLedgerQuery, SampleLedgerVO } from '@/api/wms/sampleLedger/types';
import { getErpProjectInfoList } from '@/api/oa/erp/projectInfo';
import { getCrmCustomerInfoList } from '@/api/oa/crm/customerInfo';
import { getWmsWarehouseInfoList } from '@/api/wms/warehouseInfo';
import { ElMessage } from 'element-plus';
import WmsInventorySelect from '@/components/WmsInventorySelect/index.vue';
import { ref } from 'vue';
import { addSampleDisposalRecord, getWmsSampleDisposalRecordList } from '@/api/wms/sampleDisposalRecord';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_sample_state, sys_yes_no, wms_disposal_type } = toRefs<any>(proxy?.useDict('wms_sample_state', 'sys_yes_no', 'wms_disposal_type'));
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const sampleLedgerList = ref<SampleLedgerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// 项目列表
const projectInfoList = ref([]);
// 客户列表
const customerInfoList = ref([]);
// 仓库列表
const warehouseInfoList = ref([]);
// 库存选择器
const inventorySelectRef = ref();
// 选中的库存列表
const selectInventorys = ref([]);
const queryFormRef = ref<ElFormInstance>();
const sampleLedgerFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const disposalDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `样品台账ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `出库仓库`, visible: true },
  { key: 3, label: `项目ID`, visible: true },
  { key: 4, label: `物料ID`, visible: true },
  { key: 5, label: `批次号`, visible: true },
  { key: 6, label: `借出数量`, visible: true },
  { key: 7, label: `单位`, visible: true },
  { key: 8, label: `未处理数量`, visible: true },
  { key: 9, label: `客户ID`, visible: true },
  { key: 10, label: `联系人`, visible: true },
  { key: 11, label: `联系电话`, visible: true },
  { key: 12, label: `用途`, visible: true },
  { key: 13, label: `样品状态`, visible: true },
  { key: 14, label: `删除标志`, visible: false },
  { key: 15, label: `创建部门`, visible: false },
  { key: 16, label: `创建人`, visible: false },
  { key: 17, label: `创建时间`, visible: true },
  { key: 18, label: `更新人`, visible: false },
  { key: 19, label: `更新时间`, visible: false }
]);

const initFormData: SampleLedgerForm = {
  sampleLedgerId: undefined,
  warehouseId: undefined,
  projectId: undefined,
  materielId: undefined,
  batchNumber: undefined,
  lentQty: undefined,
  unitName: undefined,
  returnQty: undefined,
  customerId: undefined,
  customerUser: undefined,
  customerNumber: undefined,
  lentRemark: undefined,
  sampleState: undefined,
  isReturn: 'Y',
  disposalType: undefined,
  disposalQty: 1
};
const data = reactive<PageData<SampleLedgerForm, SampleLedgerQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseId: undefined,
    projectId: undefined,
    productName: undefined,
    batchNumber: undefined,
    customerId: undefined,
    isReturn: undefined,
    sampleState: undefined,
    orderByColumn: 'createTime',
    isAsc: 'desc',
    params: {}
  },
  rules: {
    sampleLedgerId: [{ required: true, message: '样品台账ID不能为空', trigger: 'blur' }],
    warehouseId: [{ required: true, message: '出库仓库不能为空', trigger: 'blur' }],
    customerId: [{ required: true, message: '客户ID不能为空', trigger: 'blur' }],
    customerUser: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    customerNumber: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    lentRemark: [{ required: true, message: '样品用途不能为空', trigger: 'blur' }]
    // disposalType: [{ required: true, message: '处置类型不能为空', trigger: 'blur' }],
    // disposalQty: [{ required: true, message: '处置数量不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取项目列表 */
const getProjectInfoList = async () => {
  const res = await getErpProjectInfoList({});
  projectInfoList.value = res.data || [];
};

/** 获取客户列表 */
const getCustomerInfoList = async () => {
  const res = await getCrmCustomerInfoList(null);
  customerInfoList.value = res.data || [];
};

/** 获取仓库列表 */
const getWarehouseInfoList = async () => {
  const res = await getWmsWarehouseInfoList();
  warehouseInfoList.value = res.data || [];
};

/** 根据项目ID获取项目名称 */
const getProjectName = (projectId) => {
  const project = projectInfoList.value.find((item) => item.projectId === projectId);
  return project ? project.projectCode : projectId;
};

/** 根据客户ID获取客户名称 */
const getCustomerName = (customerId) => {
  console.log('客户列表=' + customerInfoList.value);
  const customer = customerInfoList.value.find((item) => item.customerId === customerId);
  return customer ? customer.customerName : customerId;
};

/** 根据仓库ID获取仓库名称 */
const getWarehouseName = (warehouseId) => {
  const warehouse = warehouseInfoList.value.find((item) => item.warehouseId === warehouseId);
  return warehouse ? warehouse.warehouseName : warehouseId;
};
/** 打开库存选择器 */
const openInventorySelect = () => {
  if (!form.value.warehouseId) {
    ElMessage.warning('请先选择仓库');
    return;
  }
  inventorySelectRef.value.warehouseId = form.value.warehouseId;
  inventorySelectRef.value.open();
};
/** 处理库存选择器确认选择 */
const handleInventorySelect = (selectedInventorys) => {
  selectInventorys.value = selectedInventorys;
  console.log(selectedInventorys);
};
/** 删除选中的出库明细 */
const removeOutDetail = (index) => {
  selectInventorys.value.splice(index, 1);
};
/** 查询样品管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSampleLedger(queryParams.value);
  sampleLedgerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  disposalDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  sampleLedgerFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SampleLedgerVO[]) => {
  ids.value = selection.map((item) => item.sampleLedgerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 展开子表*/
const handleExpandChange = async (row, expandRows) => {
  if (expandRows.length && !row.data) {
    row.loading = true;
    const recordList = await getWmsSampleDisposalRecordList({
      sampleLedgerId: row.sampleLedgerId
    });
    row.data = recordList.data;
    row.loading = false;
  }
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  selectInventorys.value = [];
  dialog.visible = true;
  dialog.title = '样品借出';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SampleLedgerVO) => {
  if (row?.returnQty === 0 || row?.sampleState === '2') {
    ElMessage.warning('当前样品已处置完成');
    return;
  }
  reset();
  const _sampleLedgerId = row?.sampleLedgerId || ids.value[0];
  const res = await getSampleLedger(_sampleLedgerId);
  Object.assign(form.value, res.data);
  disposalDialog.visible = true;
};

/** 提交按钮 */
const submitForm = () => {
  sampleLedgerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.sampleLedgerId) {
        // 判断disposalType不为空
        if (!form.value.disposalType) {
          ElMessage.warning('处置类型不能为空');
          buttonLoading.value = false;
          return;
        }
        // 验证处置数量不能超过未处理数量
        if (form.value.disposalQty > form.value.returnQty) {
          ElMessage.error('处置数量不能超过未处理数量');
          buttonLoading.value = false;
          return;
        }
        const result = await updateSampleLedger(form.value).finally(() => (buttonLoading.value = false));
        // console.log('提交返回结果' + result.value);
        // if (!(result.data.code !== 200)) {
        //   proxy?.$modal.msgError('操作失败');
        //   return;
        // }
        await addSampleDisposalRecord(form.value).finally(() => (buttonLoading.value = false));
      } else {
        const returnFlag = form.value.isReturn;
        const submitFlowData = selectInventorys.value.map((item) => ({
          warehouseId: form.value.warehouseId,
          projectId: form.value.projectId,
          materielId: item.materielId,
          batchNumber: item.batchNumber,
          lentQty: item.lentQty,
          returnQty: returnFlag == 'N' ? 0 : item.lentQty,
          unitName: item.unitName,
          customerId: form.value.customerId,
          customerUser: form.value.customerUser,
          customerNumber: form.value.customerNumber,
          lentRemark: form.value.lentRemark,
          inventoryDetailsId: item.inventoryDetailsId,
          isReturn: returnFlag,
          sampleState: returnFlag == 'N' ? '2' : '0'
        }));

        await addSampleLedger(submitFlowData).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      disposalDialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SampleLedgerVO) => {
  const _sampleLedgerIds = row?.sampleLedgerId || ids.value;
  await proxy?.$modal.confirm('是否确认删除样品管理编号为"' + _sampleLedgerIds + '"的数据项？').finally(() => (loading.value = false));
  await delSampleLedger(_sampleLedgerIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'wms/sampleLedger/export',
    {
      ...queryParams.value
    },
    `sampleLedger_${new Date().getTime()}.xlsx`
  );
};

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