<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label="申领编号" prop="sparePartApplyId">
                <el-input maxlength="100" v-model="queryParams.sparePartApplyId" placeholder="请输入申领编号" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="申领说明" prop="sparePartApplyExplain">
                <el-input maxlength="100" v-model="queryParams.sparePartApplyExplain" placeholder="请输入申领说明" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="state">
                <el-select v-model="queryParams.state" placeholder="请选择状态" clearable @change="handleQuery">
                    <template v-for="dict in com_apply_state" :key="dict.value">
                        <el-option :label="dict.label" :value="dict.value"
                            v-if="['10', '20', '30', '50'].includes(dict.value)" />
                    </template>
                </el-select>
            </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" style="min-height:32px">
            <!-- <el-col :span="1.5" v-hasPermi="['sparePartApply:sparePartApply:add']" v-hasRole="['admin','root']">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['sparePartApply:sparePartApply:edit']" v-hasRole="['admin','root']">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['sparePartApply:sparePartApply:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col> -->
            <el-col :span="1.5" v-hasPermi="['sparePartApply:sparePartApply: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="sparePartApplyList"
                @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
                <!-- <el-table-column type="selection" width="55" align="center"
                v-hasPermi="['sparePartApply:sparePartApply:edit', 'sparePartApply:sparePartApply:remove']" /> -->
                <el-table-column type="expand" width="30">
                    <template #default="scope">
                        <div class="padding">
                            <el-descriptions :column="1">
                                <!-- <el-descriptions-item label="申领编号">
                                {{ scope.row.sparePartApplyId }}
                            </el-descriptions-item> -->
                                <el-descriptions-item label="申领说明">
                                    {{ scope.row.sparePartApplyExplain }}
                                </el-descriptions-item>
                                <el-descriptions-item label="申领状态">
                                    <dict-tag :options="com_apply_state" :value="scope.row.sparePartApplyState"
                                        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 label="序号" align="center" type="index" width="50" />
                <!-- <el-table-column label="申领编号" align="center" prop="sparePartApplyId" width="300px" /> -->
                <el-table-column label="申领说明" align="center" prop="sparePartApplyExplain"
                    :show-overflow-tooltip="true" />
                <el-table-column label="申领状态" align="center" prop="sparePartApplyState">
                    <template #default="scope">
                        <dict-tag :options="com_apply_state" :value="scope.row.sparePartApplyState" />
                    </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), "{y}-{m}-{d} {h}:{i}:{s}" }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200"
                    fixed="right"
                    v-hasPermi="['sparePartApply:sparePartApply:query', 'sparePartApply:sparePartApply:remove']">
                    <template #default="scope">
                        <!-- <el-button link type="primary" icon="Operation"
                        v-hasPermi="['sparePartApply:sparePartApply:query']">进度
                    </el-button> -->
                        <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                            v-hasPermi="['sparePartApply:sparePartApply: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.sparePartApplyState == '30' || scope.row.sparePartApplyState == '50'"
                            v-hasPermi="['sparePart:sparePart:apply']">编辑
                        </el-button>
                        <!-- <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['sparePartApply:sparePartApply:edit']">修改
                    </el-button>
                    <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['sparePartApply:sparePartApply: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="sparePartApplyRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="申领说明" prop="sparePartApplyExplain">
                    <el-input maxlength="300" v-model="form.sparePartApplyExplain" type="textarea"
                        placeholder="请输入申领说明" />
                </el-form-item>
                <el-divider content-position="center">备件管理-申购详情信息</el-divider>
                <el-row :gutter="10" class="mb8" style="min-height:32px">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="Plus" @click="handleAddSparePartApplyDetails">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteSparePartApplyDetails">删除</el-button>
                    </el-col>
                </el-row>
                <el-table :data="sparePartApplyDetailsList" :row-class-name="rowSparePartApplyDetailsIndex"
                    @selection-change="handleSparePartApplyDetailsSelectionChange" ref="sparePartApplyDetails">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="序号" align="center" prop="index" width="50" />
                    <el-table-column label="备件名称" prop="sparePartName" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.sparePartName" placeholder="请输入备件名称" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备件id" prop="sparePartId" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.sparePartId" placeholder="请输入备件id" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备件编号" prop="sparePartNumber" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.sparePartNumber" placeholder="请输入备件编号" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备件规格" prop="sparePartSpecifications" width="150">
                        <template #default="scope">
                            <el-input maxlength="300" v-model="scope.row.sparePartSpecifications"
                                placeholder="请输入备件规格" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备件品牌" prop="sparePartBrand" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.sparePartBrand" placeholder="请输入备件品牌" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备件申购数量" prop="sparePartApplyQuantity" width="150">
                        <template #default="scope">
                            <el-input-number v-model="form.sparePartApplyQuantity" :precision="0" :step="1"
                                placeholder="请输入备件申购数量" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" width="150">
                        <template #default="scope">
                            <el-input maxlength="300" v-model="scope.row.remark" placeholder="请输入备注" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备件申领前数量" prop="sparePartQuantity" width="150">
                        <template #default="scope">
                            <el-input-number v-model="form.sparePartQuantity" :precision="0" :step="1"
                                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>



        <SparePartApplyDetailDrawer ref="sparePartApplyDetailDrawerRef" :sparePartApplyId="sparePartApplyId" />

    </div>





</template>

<script setup name="SparePartApply">
import SparePartApplyDetailDrawer from "@/components/SparePartApply/detail/drawer";
import { clearSparePartApplyDetails, updateSparePartApplyDetails as _updateSparePartApplyDetails } from "@/utils/sparePartApplyDetails";
import { listSparePartApply, getSparePartApply, delSparePartApply, addSparePartApplyDetails, updateSparePartApplyDetails, downloadSparePartApply } from "@/api/sparePartApply/sparePartApply";
import {
    withdrawApply,
} from "@/api/workbench/apply";
const router = useRouter();
const { proxy } = getCurrentInstance();
const { com_apply_state } = proxy.useDict('com_apply_state');

const sparePartApplyList = ref([]);
const sparePartApplyDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedSparePartApplyDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sparePartApplyId = ref(null)
const defaultSort = ref({ prop: "createTime", order: "descending" });

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        sparePartApplyExplain: null,
    },
    rules: {
        sparePartApplyExplain: [
            {
                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;
    listSparePartApply(queryParams.value).then(response => {
        sparePartApplyList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

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

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

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

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

// 表单重置
function reset() {
    form.value = {
        sparePartApplyId: null,
        sparePartApplyExplain: null,
        sparePartApplyState: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
    }
        ;
    sparePartApplyDetailsList.value = [];
    proxy.resetForm("sparePartApplyRef");
}

/** 搜索按钮操作 */
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.sparePartApplyId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

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

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const sparePartApplyId =
        row.sparePartApplyId || ids.value
    getSparePartApply(sparePartApplyId).then(response => {
        form.value = response.data;
        sparePartApplyDetailsList.value = response.data.sparePartApplyDetailsList;
        open.value = true;
        title.value = "修改备件管理-申领记录";
    });
}

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

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

/** 备件管理-申购详情序号 */
function rowSparePartApplyDetailsIndex({ row, rowIndex }) {
    row.index = rowIndex + 1;
}

/** 备件管理-申购详情添加按钮操作 */
function handleAddSparePartApplyDetails() {
    let obj = {};
    obj.sparePartName = "";
    obj.sparePartId = "";
    obj.sparePartNumber = "";
    obj.sparePartSpecifications = "";
    obj.sparePartBrand = "";
    obj.sparePartApplyQuantity = "";
    obj.remark = "";
    obj.sparePartQuantity = "";
    sparePartApplyDetailsList.value.push(obj);
}

/** 备件管理-申购详情删除按钮操作 */
function handleDeleteSparePartApplyDetails() {
    if (checkedSparePartApplyDetails.value.length == 0) {
        proxy.$modal.msgError("请先选择要删除的备件管理-申购详情数据");
    } else {
        const sparePartApplyDetailss = sparePartApplyDetailsList.value;
        const checkedSparePartApplyDetailss = checkedSparePartApplyDetails.value;
        sparePartApplyDetailsList.value = sparePartApplyDetailss.filter(function (item) {
            return checkedSparePartApplyDetailss.indexOf(item.index) == -1
        });
    }
}

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

/** 导出按钮操作 */
function handleExport() {
    downloadSparePartApply(queryParams.value)
    // proxy.download('sparePartApply/sparePartApply/export', {
    //   ...queryParams.value
    // }, `sparePartApply_${new Date().getTime()}.xlsx`)
}

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

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

function handleEidt(row) {
    getSparePartApply(row.sparePartApplyId).then(response => {
        clearSparePartApplyDetails(false);
        response.data.sparePartApplyDetailsList.map(item => _updateSparePartApplyDetails(item, false))
        router.push("/sparePart/sparePart?showSparePartApplySubmitDrawer=true");
    });
}

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

function initialData() {
    getList();
}

onActivated(() => {
    //// console.log("onActivated")
    initialData();
})
onMounted(() => {
    //// console.log("onMounted")
    initialData();
})

</script>

