<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="申领编号" prop="warehouseApplyId">
                <el-input v-model="queryParams.warehouseApplyId" placeholder="请输入申领编号" 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-row :gutter="10" class="mb8">
            <!--  <el-col :span="1.5" v-hasPermi="['warehouseApply:warehouseApply:add']">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['warehouseApply:warehouseApply:edit']">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    >修改
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['warehouseApply:warehouseApply:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col> -->
            <el-col :span="1.5" v-hasPermi="['warehouseApply:warehouseApply:export']">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-card shadow="never">
            <el-table ref="tableRef" v-loading="loading" :data="WarehouseApplyList"
                @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
                <el-table-column type="expand" width="30">
                    <template #default="scope" :default-sort="defaultSort" @sort-change="handleSortChange">
                        <div class="padding">
                            <el-descriptions :column="1">
                                <!-- <el-descriptions-item label="申领编号">
                                {{ scope.row.warehouseApplyId }}
                            </el-descriptions-item> -->
                                <el-descriptions-item label="申领说明">
                                    {{ scope.row.warehouseApplyExplain }}
                                </el-descriptions-item>
                                <el-descriptions-item label="申领状态">
                                    <dict-tag :options="com_apply_state" :value="scope.row.warehouseApplyState"
                                        style="display:inline-block" />
                                </el-descriptions-item>
                                <el-descriptions-item label="创建者">
                                    {{ scope.row.nickName }}
                                </el-descriptions-item>
                                <el-descriptions-item label="创建时间">
                                    {{ parseTime(scope.row.createTime), "{y}-{m}-{d} {h}:{i}:{s}" }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column type="selection" width="55" align="center"
                    v-hasPermi="['warehouseApply:warehouseApply:query', 'warehouse:warehouse:apply', 'warehouseApply:warehouseApply:remove']" />
                <el-table-column label="序号" align="center" type="index" width="50" />
                <!-- <el-table-column label="申领编号" align="center" prop="warehouseApplyId" /> -->
                <el-table-column label="申领说明" align="center" prop="warehouseApplyExplain" />
                <el-table-column label="申领状态" align="center" prop="warehouseApplyState">
                    <template #default="scope">
                        <dict-tag :options="com_apply_state" :value="scope.row.warehouseApplyState" />
                    </template>
                </el-table-column>
                <el-table-column label="创建者" align="center" prop="nickName" />
                <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom"
                    :sort-orders="['descending', 'ascending']">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200"
                    fixed="right" v-hasPermi="['warehouseApply:warehouseApply:query', 'warehouse:warehouse:apply']">
                    <template #default="scope">
                        <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                            v-hasPermi="['warehouseApply:warehouseApply:query']">详细
                        </el-button>
                        <el-button link icon="SwitchButton" type="info" @click="handleRevoke(scope.row)"
                            v-if="scope.row.isWithdraw == '1'">撤回
                        </el-button>
                        <el-button link icon="Edit" type="success" @click="handleEidt(scope.row)"
                            v-else-if="scope.row.warehouseApplyState == '30' || scope.row.warehouseApplyState == '50'"
                            v-hasPermi="['warehouse:warehouse:apply']">编辑
                        </el-button>
                        <!-- <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['warehouseApply:warehouseApply:edit']">修改
                    </el-button>
                    <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['warehouseApply:warehouseApply:remove']">删除
                    </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改物料管理-申领记录对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="WarehouseApplyRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="申领说明" prop="warehouseApplyExplain">
                    <el-input v-model="form.warehouseApplyExplain" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-divider content-position="center">物料管理-申领详情信息</el-divider>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="Plus" @click="handleAddWarehouseApplyDetails">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteWarehouseApplyDetails">删除</el-button>
                    </el-col>
                </el-row>
                <el-table :data="warehouseApplyDetailsList" :row-class-name="rowWarehouseApplyDetailsIndex"
                    @selection-change="handleWarehouseApplyDetailsSelectionChange" ref="warehouseApplyDetails">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="序号" align="center" prop="index" width="50" />
                    <el-table-column label="物料名称" prop="warehouseName" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouseName" placeholder="请输入物料名称" />
                        </template>
                    </el-table-column>
                    <el-table-column label="出入库id" prop="warehouseApplyId" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouseApplyId" placeholder="请输入出入库id" />
                        </template>
                    </el-table-column>
                    <el-table-column label="物料编号" prop="warehouseNumber" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouseNumber" placeholder="请输入物料编号" />
                        </template>
                    </el-table-column>
                    <el-table-column label="物料规格" prop="warehouseSpecifications" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouseSpecifications" placeholder="请输入物料规格" />
                        </template>
                    </el-table-column>
                    <el-table-column label="物料申领数量" prop="warehouseApplyQuantity" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouseApplyQuantity" placeholder="请输入物料申领数量" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" placeholder="请输入备注" />
                        </template>
                    </el-table-column>
                    <el-table-column label="物料申领前数量" prop="warehouseQuantity" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouseQuantity" placeholder="请输入物料申领前数量" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <WarehouseApplyDetailDrawer ref="warehouseApplyDetailDrawerRef" :warehouseApplyId="warehouseApplyId" />

    </div>
</template>

<script setup name="WarehouseApply">
import WarehouseApplyDetailDrawer from "@/components/WarehouseApply/detail/drawer";
import { clearWarehouseApplyDetails, updateWarehouseApplyDetails as _updateWarehouseApplyDetails } from "@/utils/warehouseApplyDetails";
import { listWarehouseApply, getWarehouseApply, delWarehouseApply, addWarehouseApply, updateWarehouseApply, downloadWarehouseApply } from "@/api/WarehouseApply/WarehouseApply";
import {
    withdrawApply,
} from "@/api/workbench/apply";

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

const { com_apply_state } = proxy.useDict('com_apply_state');

const WarehouseApplyList = ref([]);
const warehouseApplyDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedWarehouseApplyDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const warehouseApplyId = ref(null)
const defaultSort = ref({ prop: "createTime", order: "descending" });

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseApplyId: null,
        warehouseApplyExplain: null,
    },
    rules: {
        warehouseApplyExplain: [
            {
                required: true, message: "申领说明不能为空", trigger: "blur"
            }
        ],
    }
})
    ;

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 查询物料管理-申领记录列表 */
function getList() {
    loading.value = true;
    queryParams.value.orderByColumn = queryParams.value.orderByColumn || defaultSort.value.prop;
    queryParams.value.isAsc = queryParams.value.isAsc || defaultSort.value.order;
    listWarehouseApply(queryParams.value).then(response => {
        WarehouseApplyList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

function addList() {
    loading.value = true;
    listWarehouseApply(queryParams.value)
        .then(response => {
            WarehouseApplyList.value.push(...response.rows);
            total.value = response.total;
            if (WarehouseApplyList.value.length >= total.value) finished.value = true;
            loading.value = false;
        })
        .catch(response => {
            loading.value = false;
        });
}

// 下拉刷新
function handlePullDownRefresh() {
    queryParams.value.pageNum = 1;
    WarehouseApplyList.value = [];
    addList();
}

// 滚动到底部的事件
function handleReachBottom() {
    queryParams.value.pageNum++;
    addList();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        warehouseApplyId: null,
        warehouseApplyExplain: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
    }
        ;
    warehouseApplyDetailsList.value = [];
    proxy.resetForm("WarehouseApplyRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
   queryParams.value.pageNum = 1;
   proxy.$refs["tableRef"].sort(defaultSort.value.prop, defaultSort.value.order);
   // handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.warehouseApplyId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加物料管理-申领记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const warehouseApplyId =
        row.warehouseApplyId || ids.value
    getWarehouseApply(warehouseApplyId).then(response => {
        form.value = response.data;
        warehouseApplyDetailsList.value = response.data.warehouseApplyDetailsList;
        open.value = true;
        title.value = "修改物料管理-申领记录";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["WarehouseApplyRef"].validate(valid => {
        if (valid) {
            form.value.warehouseApplyDetailsList = warehouseApplyDetailsList.value;
            if (form.value.warehouseApplyId != null) {
                updateWarehouseApply(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addWarehouseApply(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const warehouseApplyIds = row.warehouseApplyId || ids.value;
    proxy.$modal.confirm('是否确认删除物料管理-申领记录编号为"' + warehouseApplyIds + '"的数据项？').then(function () {
        return delWarehouseApply(warehouseApplyIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 物料管理-申领详情序号 */
function rowWarehouseApplyDetailsIndex({ row, rowIndex }) {
    row.index = rowIndex + 1;
}

/** 物料管理-申领详情添加按钮操作 */
function handleAddWarehouseApplyDetails() {
    let obj = {};
    obj.warehouseName = "";
    obj.warehouseApplyId = "";
    obj.warehouseNumber = "";
    obj.warehouseSpecifications = "";
    obj.warehouseApplyQuantity = "";
    obj.remark = "";
    obj.warehouseQuantity = "";
    warehouseApplyDetailsList.value.push(obj);
}

/** 物料管理-申领详情删除按钮操作 */
function handleDeleteWarehouseApplyDetails() {
    if (checkedWarehouseApplyDetails.value.length == 0) {
        proxy.$modal.msgError("请先选择要删除的物料管理-申领详情数据");
    } else {
        const warehouseApplyDetailss = warehouseApplyDetailsList.value;
        const checkedWarehouseApplyDetailss = checkedWarehouseApplyDetails.value;
        warehouseApplyDetailsList.value = warehouseApplyDetailss.filter(function (item) {
            return checkedWarehouseApplyDetailss.indexOf(item.index) == -1
        });
    }
}

/** 复选框选中数据 */
function handleWarehouseApplyDetailsSelectionChange(selection) {
    checkedWarehouseApplyDetails.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
    downloadWarehouseApply(queryParams.value)
}

/** 详细按钮操作 */
function handleView(row) {
    warehouseApplyId.value = row.warehouseApplyId
    proxy.$refs["warehouseApplyDetailDrawerRef"].show()
}

function handleRevoke(row) {
    proxy.$modal
        .confirm("是否撤回？")
        .then(() => {
            withdrawApply(row.warehouseApplyId).then(() => {
                proxy.$modal.msg("已撤回");
                getList();
            })
        })
        .catch(() => { });
}

function handleEidt(row) {
    getWarehouseApply(row.warehouseApplyId).then(response => {
        clearWarehouseApplyDetails(false);
        response.data.warehouseApplyDetailsList.map(item => _updateWarehouseApplyDetails(item, false))
        router.push("/warehouse/warehouse?showWarehouseApplySubmitDrawer=true");
    });
}

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
    queryParams.value.orderByColumn = column.prop;
    queryParams.value.isAsc = column.order;
    getList();
}

getList();
</script>

