<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'>
            <!-- <el-form-item label="表主键" prop="roId">
              <el-input v-model="queryParams.roId" placeholder="请输入表主键" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <!-- <el-form-item label="物料名称" prop="materialId">
              <el-input v-model="queryParams.materialId" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
<!--            <el-form-item label='物料大类' prop='materialCategoryId'>
              <el-select v-model='queryParams.materialCategoryId' placeholder='请选择物料大类' clearable>
                <el-option v-for='item in mategoryOptions'
                           :key='item.materialCategoryId'
                           :label='item.materialCategoryName'
                           :value='item.materialCategoryId'
                />
              </el-select>
            </el-form-item>-->
            <el-form-item label='批次条码' prop='batchCode'>
              <el-input v-model='queryParams.batchCode' placeholder='请输入批次条码' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>
            <!-- <el-form-item label="计划数量" prop="planAmount">
              <el-input v-model="queryParams.planAmount" placeholder="请输入计划数量" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
<!--            <el-form-item label='仓库' prop='warehouseId'>
              <el-select v-model='queryParams.warehouseId' placeholder='请选择所属仓库'>
                <el-option
                  v-for='item in baseStoreList'
                  :key='item.warehouseId'
                  :label='item.warehouseName'
                  :value='item.warehouseId'
                ></el-option>
              </el-select>
            </el-form-item>-->
<!--            <el-form-item label='计划库位' prop='planLocationCode'>
              <el-input v-model='queryParams.planLocationCode' placeholder='请输入计划退库库位' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>-->
            <el-form-item label='退库状态' prop='orderStatus'>
              <el-select v-model='queryParams.orderStatus' placeholder='请选择退库工单状态' clearable>
                <el-option v-for='dict in wms_return_status' :key='dict.value' :label='dict.label'
                           :value='dict.value' />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="实际数量" prop="returnAmount">
              <el-input v-model="queryParams.returnAmount" placeholder="请输入实际数量" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
<!--            <el-form-item label='实际库位' prop='returnLocationCode'>
              <el-input v-model='queryParams.returnLocationCode' placeholder='请输入实际退库库位' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>-->
            <!-- <el-form-item label="审核人" prop="auditBy">
              <el-input v-model="queryParams.auditBy" placeholder="请输入审核人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="审核时间" prop="auditTime">
              <el-date-picker clearable
                v-model="queryParams.auditTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择审核时间"
              />
            </el-form-item>
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态(0待审核,1审核通过,2审核未通过)" clearable >
                <el-option v-for="dict in approve_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="审核意见" prop="auditComments">
              <el-input v-model="queryParams.auditComments" placeholder="请输入审核意见" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
<!--            <el-form-item label='erp同步状态' prop='erpSynchronousStatus'>-->
<!--              <el-select v-model='queryParams.erpSynchronousStatus' placeholder='请选择erp同步状态' clearable>-->
<!--                <el-option v-for='dict in erp_synchronous_status' :key='dict.value' :label='dict.label'-->
<!--                           :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <!-- <el-form-item label="erp同步数量" prop="erpSynchronousQty">
              <el-input v-model="queryParams.erpSynchronousQty" placeholder="请输入erp同步数量" clearable @keyup.enter="handleQuery" />
            </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="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:returnOrder:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:returnOrder:remove']">删除</el-button>
          </el-col>
          -->
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleAdd' v-hasPermi="['system:returnOrder:add']">
              创建退库单
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='warning' plain icon='Download' @click='handleExport'
                       v-hasPermi="['system:returnOrder: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' :data='returnOrderList' @selection-change='handleSelectionChange'>
        <el-table-column type='selection' width='55' align='center' />
        <!-- <el-table-column label="表主键" align="center" prop="roId" v-if="columns[0].visible"/> -->
        <el-table-column label='物料名称' align='center' prop='materialName' v-if='columns[6].visible' width='100'/>
        <el-table-column label='物料大类' align='center' prop='materialCategoryName' v-if='columns[7].visible' />
        <el-table-column label='批次条码' align='center' prop='batchCode' v-if='columns[8].visible' width='120'/>
        <el-table-column label='计划数量' align='center' prop='planAmount' v-if='columns[9].visible' width='100'/>
        <!-- <el-table-column label="仓库" align="center" prop="warehouseCode" v-if="columns[10].visible"/> -->
        <el-table-column label='计划退库库位' align='center' prop='planLocationCode' v-if='columns[11].visible' width='120'/>
        <el-table-column label='退库工单状态' align='center' prop='orderStatus' v-if='columns[12].visible' width='120'>
          <template #default='scope'>
            <dict-tag :options='wms_return_status' :value='scope.row.orderStatus' />
          </template>
        </el-table-column>
        <el-table-column label='实际数量' align='center' prop='returnAmount' v-if='columns[13].visible' />
        <el-table-column label='实际退库库位' align='center' prop='returnLocationCode' v-if='columns[14].visible' width='120'/>
        <el-table-column label='退库原因' align='center' prop='returnReason' v-if='columns[21].visible' width='120'/>
        <el-table-column label='审核人' align='center' prop='auditBy' v-if='columns[15].visible' />
        <el-table-column label='审核时间' align='center' prop='auditTime' width='180' v-if='columns[16].visible'>
          <template #default='scope'>
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label='审核状态' align='center' prop='auditStatus' v-if='columns[17].visible' >
          <template #default='scope'>
            <dict-tag :options='approve_status' :value='scope.row.auditStatus' />
          </template>
        </el-table-column>
        <el-table-column label='审核意见' align='center' prop='auditComments' v-if='columns[18].visible' />
        <el-table-column label='erp同步状态' align='center' prop='erpSynchronousStatus' v-if='columns[19].visible'>
          <template #default='scope'>
            <dict-tag :options='erp_synchronous_status' :value='scope.row.erpSynchronousStatus' />
          </template>
        </el-table-column>
        <el-table-column label='erp同步数量' align='center' prop='erpSynchronousQty' v-if='columns[20].visible' />
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
<!--            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:returnOrder:edit']"></el-button>
            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:returnOrder:remove']"></el-button>
            </el-tooltip>-->
            <el-tooltip content="审批" placement="top">
              <el-button
                size="small"
                type="success"
                icon="Check"
                @click="handleAudit(scope.row)"
                :disabled="scope.row.auditStatus == '1' || scope.row.auditStatus == '2' || scope.row.orderStatus === '1'"
              >审批</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='500px' append-to-body>
      <el-form ref='returnOrderFormRef' :model='form' :rules='rules' label-width='130px'>
<!--        <el-form-item label='物料大类' prop='materialCategoryId'>-->
<!--          <el-select v-model='form.materialCategoryId' placeholder='请选择物料大类'>-->
<!--            <el-option v-for='item in mategoryOptions'-->
<!--                       :key='item.materialCategoryId'-->
<!--                       :label='item.materialCategoryName'-->
<!--                       :value='item.materialCategoryId'-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label='物料名称' prop='materialId'>-->
<!--          <el-input v-model='form.materialName' placeholder='请点击检索物料' @click='handleMaterialAdd' readonly>-->
<!--            <template #append>-->
<!--              <el-icon class='el-input__icon'>-->
<!--                <search />-->
<!--              </el-icon>-->
<!--            </template>-->
<!--          </el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label='批次条码' prop='batchCode'>-->
<!--          <el-input v-model='form.batchCode' placeholder='请输入批次条码' />-->
<!--        </el-form-item>-->
        <el-form-item label='出库单号' prop='batchCode'>
          <el-input v-model='form.batchCode' placeholder='请点击检索出库单号' @click='handleOutstockDetailAdd' readonly>
            <template #append>
              <el-icon class='el-input__icon'>
                <search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label='物料编码' prop='materialCode'>
          <el-input v-model='form.materialCode' disabled/>
        </el-form-item>
        <el-form-item label='物料名称' prop='materialName'>
          <el-input v-model='form.materialName' disabled/>
        </el-form-item>
        <el-form-item label='出库数量' prop='outstockQty'>
          <el-input-number v-model='form.outstockQty' style="width: 220px;" disabled/>
        </el-form-item>
        <el-form-item label='可退数量' prop='returnAmount'>
          <el-input-number v-model='form.returnAmount' style="width: 220px;" disabled/>
        </el-form-item>
        <el-form-item label='计划数量' prop='planAmount'>
          <el-input-number v-model='form.planAmount' placeholder='请输入计划数量' style="width: 220px;"/>
        </el-form-item>
        <el-form-item label='仓库名称' prop='warehouseId'>
          <el-select v-model='form.warehouseId' placeholder='请选择所属仓库'>
            <el-option
              v-for='item in baseStoreList'
              :key='item.warehouseId'
              :label='item.warehouseName'
              :value='item.warehouseId'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='计划退库库位' prop='planLocationCode'>
          <el-select v-model='form.planLocationCode' placeholder='请选择所属仓库'>
            <el-option
              v-for='item in locationList'
              :key='item.locationCode'
              :label='item.locationCode'
              :value='item.locationCode'
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='退库原因' prop='returnReason'>
          <el-input v-model='form.returnReason' type='textarea' placeholder='请输入退库原因' />
        </el-form-item>
        <!-- <el-form-item label="退库工单状态" prop="orderStatus">
          <el-radio-group v-model="form.orderStatus">
            <el-radio
              v-for="dict in wms_return_status"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
<!--        <el-form-item label='实际数量' prop='returnAmount'>-->
<!--          <el-input-number v-model='form.returnAmount' placeholder='请输入实际数量' style="width: 220px;"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label='实际退库库位' prop='returnLocationCode'>-->
<!--          <el-input v-model='form.returnLocationCode' placeholder='请输入实际退库库位' />-->
<!--        </el-form-item>-->
        <el-form-item label='审核状态' prop='auditStatus'>
          <el-radio-group v-model='form.auditStatus'>
            <el-radio
              v-for="dict in approve_status"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='审核意见' prop='auditComments'>
          <el-input v-model='form.auditComments' type='textarea' 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 v-model="auditOpen" title="退库工单审批" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="form.auditStatus">
            <el-radio value="1">审核通过</el-radio>
            <el-radio value="2">审核未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComments">
          <el-input
            v-model="form.auditComments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAudit">取 消</el-button>
          <el-button type="primary" @click="submitAudit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" v-model="materialOpen" width='1200px' append-to-body>
      <MaterialSelectInWMS
        @selection="handleSelection"
        ref="materialSelectRef"
        v-if="materialOpen"
        :materialCategoryId="form.materialCategoryId"
      ></MaterialSelectInWMS>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择出库单号" v-model="outstockDetailOpen" width='1200px' append-to-body>
      <SelectOutstockDetail
        @selection="handleOutstockDetailSelection"
        ref="outstockDetailSelectRef"
        v-if="outstockDetailOpen"
      ></SelectOutstockDetail>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOutstockDetailForm">确 定</el-button>
        <el-button @click="outstockDetailOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name='ReturnOrder' lang='ts'>
import {
  listReturnOrder,
  getReturnOrder,
  delReturnOrder,
  addReturnOrder,
  updateReturnOrder,
  auditReturnOrder
} from '@/api/wms/returnOrder';
import { ReturnOrderVO, ReturnOrderForm, ReturnOrderQuery } from '@/api/wms/returnOrder/types';
import { getBaseWarehouseList } from '@/api/wms/baseWarehouse';

import { getBaseMaterialCategoryListInWMS } from '@/api/wms/baseMaterialCategory';
import MaterialSelectInWMS from '@/views/mes/baseMaterialInfo/addMaterialInWMS.vue';
import SelectOutstockDetail from '@/views/wms/outstockDetail/selectOutstockDetail.vue';
import { getBaseDeviceTypeList } from '@/api/mes/baseDeviceType';
import { getWmsBaseLocationVoList } from '@/api/wms/baseLocation';
import { getOutstockDetailList } from '@/api/wms/outstockDetail';
import { OutstockDetailQuery } from '@/api/wms/outstockDetail/types';
import { FormRules } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  wms_return_status,
  erp_synchronous_status,
  approve_status
} = toRefs<any>(proxy?.useDict('wms_return_status', 'erp_synchronous_status', 'approve_status'));
const returnOrderList = ref<ReturnOrderVO[]>([]);
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 auditOpen = ref(false);
const auditFormRef = ref<ElFormInstance>();

// 审批表单验证规则
const auditRules = reactive<FormRules<ReturnOrderForm>>({
  auditStatus: [{ required: true, message: '请选择审核状态', trigger: 'change' }]
});

const baseStoreList = ref([]);
const queryFormRef = ref<ElFormInstance>();
const returnOrderFormRef = ref<ElFormInstance>();

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

const materialOpen = ref(false);//物料选择对话框显示

const outstockDetailOpen = ref(false);

const selectedMaterial = ref(null); // 存储选中的物料完整信息
const selectedOutstockDetail = ref(null); // 存储选中的物料完整信息

/** 处理从MaterialSelect组件接收到的选择 */
const handleSelection = (row) => {
  selectedMaterial.value = row;
};

/** 处理从MaterialSelect组件接收到的选择 */
const handleOutstockDetailSelection = (row) => {
  selectedOutstockDetail.value = row;
};

const materialSelectRef = ref();//物料选择对话框绑定
const outstockDetailSelectRef = ref();

// 获取仓库
const getSelectBaseWarehouseList = async () => {
  let res = await getBaseWarehouseList({ deviceCategoryId: 1 });
  baseStoreList.value = res.data;
};





// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `表主键`, visible: true },
  { key: 1, label: `租户号`, visible: true },
  { key: 2, label: `工单创建人`, visible: true },
  { key: 3, label: `工单创建时间`, visible: true },
  { key: 4, label: `实际退库人`, visible: true },
  { key: 5, label: `实际退库时间`, visible: true },
  { key: 6, label: `物料名称`, visible: true },
  { key: 7, label: `物料大类`, visible: false },
  { key: 8, label: `批次条码`, visible: true },
  { key: 9, label: `计划数量`, visible: true },
  { key: 10, label: `仓库名称`, visible: false },
  { key: 11, label: `计划退库库位`, visible: true },
  { key: 12, label: `退库工单状态`, visible: true },
  { key: 13, label: `实际数量`, visible: true },
  { key: 14, label: `实际退库库位`, visible: true },
  { key: 15, label: `审核人`, visible: true },
  { key: 16, label: `审核时间`, visible: true },
  { key: 17, label: `审核状态`, visible: true },
  { key: 18, label: `审核意见`, visible: true },
  { key: 19, label: `erp同步状态`, visible: true },
  { key: 20, label: `erp同步数量`, visible: true },
  { key: 21, label: `退库原因`, visible: true },
]);

const initFormData: ReturnOrderForm = {
  roId: undefined,
  materialId: undefined,
  materialCategoryId: undefined,
  materialCategoryName: undefined,//字段映射
  batchCode: undefined,
  planAmount: undefined,
  warehouseId: undefined,
  planLocationCode: undefined,
  orderStatus: undefined,
  returnAmount: undefined,
  returnLocationCode: undefined,
  auditBy: undefined,
  auditTime: undefined,
  auditStatus: undefined,
  auditComments: undefined,
  erpSynchronousStatus: undefined,
  erpSynchronousQty: undefined
};
const data = reactive<PageData<ReturnOrderForm, ReturnOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roId: undefined,
    materialId: undefined,
    materialCategoryId: undefined,
    materialCategoryName: undefined,//字段映射
    batchCode: undefined,
    planAmount: undefined,
    warehouseId: undefined,
    planLocationCode: undefined,
    orderStatus: undefined,
    returnAmount: undefined,
    returnLocationCode: undefined,
    auditBy: undefined,
    auditTime: undefined,
    auditStatus: undefined,
    auditComments: undefined,
    erpSynchronousStatus: undefined,
    erpSynchronousQty: undefined,
    params: {}
  },
  rules: {
    materialId: [
      { required: true, message: '物料名称不能为空', trigger: 'blur' }
    ],
    materialCategoryId: [
      { required: true, message: '物料大类不能为空', trigger: 'blur' }
    ],
    batchCode: [
      { required: true, message: '批次条码不能为空', trigger: 'blur' }
    ],
    planAmount: [
      { required: true, message: '计划数量不能为空', trigger: 'blur' }
    ],
    warehouseId: [
      { required: true, message: '仓库名称不能为空', trigger: 'blur' }
    ],
    planLocationCode: [
      { required: true, message: '计划退库库位不能为空', trigger: 'blur' }
    ],
    orderStatus: [
      { required: true, message: '退库工单状态不能为空', trigger: 'change' }
    ],
  }
});

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

/** 获取库位下拉列表 */
let locationList = ref([]);
const getBaseLocationList = async (warehouseId: any) => {
  if (!warehouseId) {
    locationList.value = [];
    return;
  }
  try {
    const res = await getWmsBaseLocationVoList({ warehouseId });
    locationList.value = res.data || [];
  } catch (error) {
    console.error('获取库位列表失败:', error);
    locationList.value = [];
  }
};

watch(
  () => form.value.warehouseId,
  (newVal) => {
    getBaseLocationList(newVal);
  }
);

/** 查询退库工单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listReturnOrder(queryParams.value);
  returnOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ReturnOrderVO[]) => {
  ids.value = selection.map((item) => item.roId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 创建退库单按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '创建退库工单';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ReturnOrderVO) => {
  reset();
  const _roId = row?.roId || ids.value[0];
  const res = await getReturnOrder(_roId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改退库工单';
};

/** 提交按钮 */
const submitForm = () => {
  if (form.value.returnAmount < form.value.planAmount){
    proxy?.$modal.msgWarning('计划数量不可大于可退数量！');
    return;
  }
  returnOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.roId) {
        await updateReturnOrder(form.value).finally(() => buttonLoading.value = false);
      } else {
        form.value.returnAmount = null
        await addReturnOrder(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ReturnOrderVO) => {
  const _roIds = row?.roId || ids.value;
  await proxy?.$modal.confirm('是否确认删除退库工单编号为"' + _roIds + '"的数据项？').finally(() => loading.value = false);
  await delReturnOrder(_roIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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


let mategoryOptions = ref([]);
const getMaterialCategorySelect = async () => {
  const res = await getBaseMaterialCategoryListInWMS(null);
  mategoryOptions.value = res.data;
};

/** 新增按钮操作 */
const handleMaterialAdd = (type, index) => {
  materialOpen.value = true;
}

/** 新增按钮操作 */
const handleOutstockDetailAdd = (type, index) => {
  outstockDetailOpen.value = true;
}

/** 提交物料BOM信息按钮 */
const submitMaterialForm = () => {
  selectedMaterial.value = materialSelectRef.value.tableRef.store.states.currentRow.value;
  form.value.materialId = selectedMaterial.value.materialId;
  form.value.materialName = selectedMaterial.value.materialName;
  // 重置选中的物料信息和关闭对话框
  selectedMaterial.value = null;
  materialOpen.value = false;
};

const submitOutstockDetailForm = async () => {
  selectedMaterial.value = outstockDetailSelectRef.value.tableRef.store.states.currentRow.value;
  form.value.batchCode = selectedMaterial.value.outstockCode;
  form.value.materialId = selectedMaterial.value.materialId;
  form.value.materialCode = selectedMaterial.value.materialCode;
  form.value.materialName = selectedMaterial.value.materialName;
  form.value.materialCtegories = selectedMaterial.value.materialCategories;
  form.value.outstockQty = selectedMaterial.value.outstockQty;

  const selectData: ReturnOrderQuery = {
    batchCode: form.value.batchCode,
    materialId: form.value.materialId,
    pageNum: 1, // 必需属性
    pageSize: 10 // 必需属性
  };
  const res = await listReturnOrder(selectData);
  let returnAmount = 0;
  res.rows.forEach(item => {
    returnAmount += Number(item.planAmount);
  })
  console.log(returnAmount);
  form.value.returnAmount = Number(form.value.outstockQty) - returnAmount;

  // 重置选中的物料信息和关闭对话框
  selectedOutstockDetail.value = null;
  outstockDetailOpen.value = false;
};

/** 打开审批对话框 */
const handleAudit = (row?: ReturnOrderVO) => {
  if (row?.roId) {
    form.value.roId = row.roId;
    form.value.auditStatus = '';
    form.value.auditComments = '';
    auditOpen.value = true;
  }
};

/** 取消审批 */
const cancelAudit = () => {
  auditOpen.value = false;
  form.value.auditStatus = '';
  form.value.auditComments = '';
  auditFormRef.value?.resetFields();
};

/** 提交审批 */
const submitAudit = async () => {
  if (!auditFormRef.value) return;

  const valid = await auditFormRef.value.validate().catch(() => false);
  if (!valid) return;

  try {
    await auditReturnOrder(form.value);
    proxy?.$modal.msgSuccess('审批成功');
    auditOpen.value = false;
    await getList();
  } catch (error) {
    console.error('审批失败:', error);
  }
};

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