<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label="维保申请编号" prop="maintenanceApplyId">
                <el-input v-model="queryParams.maintenanceApplyId" placeholder="请输入维保申请编号" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="申请说明" prop="maintenanceApplyExplain">
                <el-input v-model="queryParams.maintenanceApplyExplain" 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="['maintenanceApply:maintenanceApply:add']">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['maintenanceApply:maintenanceApply: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="['maintenanceApply:maintenanceApply:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col>-->
            <el-col :span="1.5" v-hasPermi="['maintenanceApply:maintenanceApply: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="maintenanceApplyList"
                @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
                <!-- <el-table-column type="selection" width="55" align="center"
                v-hasPermi="['maintenanceApply:maintenanceApply:edit', 'maintenanceApply:maintenanceApply:remove']" /> -->
                <el-table-column type="expand" width="30">
                    <template #default="scope">
                        <div class="padding">
                            <el-descriptions :column="1">
                                <!-- <el-descriptions-item label="申请编号">
                                {{ scope.row.maintenanceApplyId }}
                            </el-descriptions-item> -->
                                <el-descriptions-item label="申请说明">
                                    {{ scope.row.maintenanceApplyExplain }}
                                </el-descriptions-item>
                                <el-descriptions-item label="申请状态">
                                    <dict-tag :options="com_apply_state" :value="scope.row.state"
                                        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="maintenanceApplyId" width="300px" /> -->
                <el-table-column label="申请说明" align="center" prop="maintenanceApplyExplain"
                    :show-overflow-tooltip="true" />
                <!-- <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
                <el-table-column label="状态" align="center" prop="state">
                    <template #default="scope">
                        <dict-tag :options="com_apply_state" :value="scope.row.state" />
                    </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="['maintenanceApply:maintenanceApply:query', 'maintenanceApply:maintenanceApply:edit', 'maintenanceApply:maintenanceApply:remove']">
                    <template #default="scope">
                        <el-button text type="primary" icon="View" @click="handleView(scope.row)"
                            v-hasPermi="['maintenanceApply:maintenanceApply: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.state == '50' || scope.row.state == '30'"
                            v-hasPermi="['maintenanceProject:maintenanceProject:apply']">编辑
                        </el-button>
                        <!--  <el-button text type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['maintenanceApply:maintenanceApply:edit']" v-hasRole="['admin', 'root']">修改
                    </el-button>
                    <el-button text type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['maintenanceApply:maintenanceApply: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="1000px" append-to-body>
            <el-form ref="maintenanceApplyRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="备注" prop="remark">
                    <el-input maxlength="300" v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="申请说明" prop="maintenanceApplyExplain">
                    <el-input maxlength="300" v-model="form.maintenanceApplyExplain" placeholder="请输入申请说明" />
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-select v-model="form.state" placeholder="请选择状态">
                        <el-option v-for="dict in com_apply_state" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </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="handleAddMaintenanceApplyDetails">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteMaintenanceApplyDetails">删除
                        </el-button>
                    </el-col>
                </el-row>
                <el-table :data="maintenanceApplyDetailsList" :row-class-name="rowMaintenanceApplyDetailsIndex"
                    @selection-change="handleMaintenanceApplyDetailsSelectionChange" ref="maintenanceApplyDetails">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="序号" align="center" prop="index" width="50" />
                    <el-table-column label="维保项目" prop="maintenanceProjectName" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.maintenanceProjectName"
                                placeholder="请输入维保项目" />
                        </template>
                    </el-table-column>
                    <el-table-column label="维保项目标准" prop="maintenanceProjectStandard" width="150">
                        <template #default="scope">
                            <el-input maxlength="300" v-model="scope.row.maintenanceProjectStandard"
                                placeholder="请输入维保项目标准" />
                        </template>
                    </el-table-column>
                    <el-table-column label="维保项目责任人" prop="maintenanceProjectPersonLiable" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.maintenanceProjectPersonLiable"
                                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>
            </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>





        <MaintenanceApplyDetailDrawer ref="maintenanceApplyDetailDrawerRef" :maintenanceApplyId="maintenanceApplyId" />
    </div>





</template>

<script setup name="MaintenanceApply">
import { listMaintenanceApply, getMaintenanceApply, delMaintenanceApply, addMaintenanceApply, updateMaintenanceApply, downloadMaintenanceApply } from "@/api/maintenanceApply/maintenanceApply";
import MaintenanceApplyDetailDrawer from "@/components/MaintenanceApply/detail/drawer";
import {
    withdrawApply,
} from "@/api/workbench/apply";
import { clearMaintenanceApplyDetails, updateMaintenanceApplyDetails as _updateMaintenanceApplyDetails } from "@/utils/maintenanceApplyDetails";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { com_apply_state } = proxy.useDict('com_apply_state');
const maintenanceApplyList = ref([]);
const maintenanceApplyDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMaintenanceApplyDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const maintenanceApplyId = ref(null)
const defaultSort = ref({ prop: "createTime", order: "descending" });


const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        maintenanceApplyId: null,
        maintenanceApplyExplain: null,
        state: null
    },
    rules: {
    }
})
    ;

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

/** 查询维保申请列表 */
function getList() {
    loading.value = true;
    listMaintenanceApply(queryParams.value).then(response => {
        maintenanceApplyList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

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

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

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

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

// 表单重置
function reset() {
    form.value = {
        maintenanceApplyId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        maintenanceApplyExplain: null,
        state: null
    }
        ;
    maintenanceApplyDetailsList.value = [];
    proxy.resetForm("maintenanceApplyRef");
}

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

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加维保申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const maintenanceApplyId =
        row.maintenanceApplyId || ids.value
    getMaintenanceApply(maintenanceApplyId).then(response => {
        form.value = response.data;
        maintenanceApplyDetailsList.value = response.data.maintenanceApplyDetailsList;
        open.value = true;
        title.value = "修改维保申请";
    });
}

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

/** 删除按钮操作 */
function handleDelete(row) {
    const maintenanceApplyIds = row.maintenanceApplyId || ids.value;
    proxy.$modal.confirm('是否确认删除维保申请编号为"' + maintenanceApplyIds + '"的数据项？').then(function () {
        return delMaintenanceApply(maintenanceApplyIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 维保申请详情序号 */
function rowMaintenanceApplyDetailsIndex({ row, rowIndex }) {
    row.index = rowIndex + 1;
}

/** 维保申请详情添加按钮操作 */
function handleAddMaintenanceApplyDetails() {
    let obj = {};
    obj.maintenanceProjectName = "";
    obj.maintenanceProjectStandard = "";
    obj.maintenanceProjectPersonLiable = "";
    obj.maintenanceProjectFile = "";
    obj.remark = "";
    maintenanceApplyDetailsList.value.push(obj);
}

/** 维保申请详情删除按钮操作 */
function handleDeleteMaintenanceApplyDetails() {
    if (checkedMaintenanceApplyDetails.value.length == 0) {
        proxy.$modal.msgError("请先选择要删除的维保申请详情数据");
    } else {
        const maintenanceApplyDetailss = maintenanceApplyDetailsList.value;
        const checkedMaintenanceApplyDetailss = checkedMaintenanceApplyDetails.value;
        maintenanceApplyDetailsList.value = maintenanceApplyDetailss.filter(function (item) {
            return checkedMaintenanceApplyDetailss.indexOf(item.index) == -1
        });
    }
}

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

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

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

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

function handleEidt(row) {
    getMaintenanceApply(row.maintenanceApplyId).then(response => {
        clearMaintenanceApplyDetails(false);
        response.data.maintenanceApplyDetailsList.map(item => _updateMaintenanceApplyDetails(item, false))
        router.push("/maintentance/maintentance?showMaintenanceApplySubmitDrawer=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>

