<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="工单编号" prop="applyNo">
                <el-input v-model="queryParams.applyNo" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="applyType">
                <el-select v-model="queryParams.applyType" placeholder="请选择类型" clearable @change="handleQuery">
                    <el-option v-for="dict in apply_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="applyState">
                <el-select v-model="queryParams.applyState" 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 label="申请人" prop="applyEstablishUser">
                <el-select v-model="queryParams.applyEstablishUser" placeholder="请选择申请人" clearable filterable
                    @change="handleQuery">
                    <el-option :label="`${$store.state.user.user.nickName}(我)`" :value="$store.state.user.user.userId" />
                    <template v-for="dict in userList" :key="dict.userId">
                        <el-option :label="dict.nickName" :value="dict.userId"
                            v-if="$store.state.user.user.userId != dict.userId" />
                    </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-card shadow="never">
            <el-table v-loading="loading" :data="applyList" :default-sort="defaultSort" @sort-change="handleSortChange">
                <el-table-column label="序号" align="center" type="index" width="50" />
                <el-table-column label="工单编号" align="center" prop="applyNo" width="300px" />
                <el-table-column label="类型" align="center" prop="applyType">
                    <template #default="scope">
                        <dict-tag :options="apply_type" :value="scope.row.applyType" />
                    </template>
                </el-table-column>
                <el-table-column label="当前环节" align="center" prop="applyLink" />
                <el-table-column label="申请人" align="center" prop="userNickName">
                    <template #default="scope">
                        <span>{{ scope.row.userNickName }}</span>
                        <span v-if="scope.row.jobUser == $store.state.user.user.userId">(我)</span>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" align="center" prop="applyEstablishTime" width="180" sortable="custom"
                    :sort-orders="['descending', 'ascending']">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.applyEstablishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="结束时间" align="center" prop="applyCompleteTime" width="180" sortable="custom"
                    :sort-orders="['descending', 'ascending']">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.applyCompleteTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="applyState">
                    <template #default="scope">
                        <dict-tag :options="com_apply_state" :value="scope.row.applyState" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button text type="primary" icon="View" @click="handleView(scope.row)"
                            v-hasPermi="['apply:apply:query']">
                            详情</el-button>
                        <el-button link icon="SwitchButton" type="success" @click="handleRevoke(scope.row)"
                            v-if="scope.row.applyState == '10'">撤回
                        </el-button>
                        <el-button link icon="Edit" type="success" @click="handleEidt(scope.row)"
                            v-else-if="scope.row.applyState == '30' || scope.row.applyState == '50'"
                            v-hasPermi="['sparePart:sparePart:apply']">编辑
                        </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" />


        <ApplyDetailDrawer ref="applyDetailDrawerRef" :applyId="applyId" @update="getList" api="getAlreadyApply" />

    </div>
</template>

<script setup>
import {
    getAlreadyApply,
    listAlreadyApply,
    updateApply,
    getApply,
    withdrawApply,

} from "@/api/workbench/apply";


import { listUser } from "@/api/system/user";
import { clearApplyPurchaseDetails, updateApplyPurchaseDetails as _updateApplyPurchaseDetails } from "@/utils/applyPurchaseDetails";
import { clearSparePartApplyDetails, updateSparePartApplyDetails as _updateSparePartApplyDetails } from "@/utils/sparePartApplyDetails";
import { clearMaintenanceApplyDetails, updateMaintenanceApplyDetails as _updateMaintenanceApplyDetails } from "@/utils/maintenanceApplyDetails";
import { clearWarehouseApplyDetails, updateWarehouseApplyDetails as _updateWarehouseApplyDetails } from "@/utils/warehouseApplyDetails";


const router = useRouter();
const { proxy } = getCurrentInstance();
const { com_apply_state, apply_type } = proxy.useDict('com_apply_state', 'apply_type');


const applyList = ref([]);
const userList = ref([]);

const loading = ref(true);
const showSearch = ref(true);
const applyId = ref(null);
const total = ref(0);
const defaultSort = ref({ prop: "applyEstablishTime", order: "descending" });

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyState: null,
        applyLink: null,
        applyType: null,
        applyEstablishUser: null,
        applyEstablishTime: null,
        applyCompleteTime: null,
        isMine: null,
        userName: null,
    },
    rules: {},
});
const { queryParams, form, rules } = toRefs(data);

function getList() {
    loading.value = true;
    queryParams.value.applyType == '' ? queryParams.value.applyType = null : null
    listAlreadyApply(queryParams.value).then((response) => {
        applyList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

function handleView(row) {
    // console.log(row)
    // console.log(row.value)
    // console.log(row.applyId)
    applyId.value = row.applyId;
    proxy.$refs["applyDetailDrawerRef"].show();

    // getApply(row.applyId);
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryForm");
    handleQuery();
}

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

const handleEidt = (row) => {
    getAlreadyApply(row.applyId).then(response => {
        switch (row.applyType) {
            case 10:
            case "10":
                // 物料申购
                clearApplyPurchaseDetails(false);
                response.data.applyPurchase.applyPurchaseDetailsList.map(item => _updateApplyPurchaseDetails(item, false))
                router.push("/warehouse/warehouse?showApplyPurchaseDrawerSubmit=true");
                break;
            case 20:
            case "20":
                // 备件申领
                clearSparePartApplyDetails(false);
                response.data.sparePartApply.sparePartApplyDetailsList.map(item => _updateSparePartApplyDetails(item, false))
                router.push("/sparePart/sparePart?showSparePartApplySubmitDrawer=true");
                break;
            case 30:
            case "30":
                // 维保申请	
                clearMaintenanceApplyDetails(false);
                response.data.maintenanceApply.maintenanceApplyDetailsList.map(item => _updateMaintenanceApplyDetails(item, false))
                router.push("/maintentance/maintentance?showMaintenanceApplySubmitDrawer=true");
                break;
            case 40:
            case "40":
                // 维保申领	
                clearWarehouseApplyDetails(false);
                response.data.warehouseApply.warehouseApplyDetailsList.map(item => _updateWarehouseApplyDetails(item, false))
                router.push("/warehouse/warehouse?showWarehouseApplySubmitDrawer=true");
                break;
        }
    });
}

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

function initialData() {
    listUser(proxy.addDateRange({
        pageNum: 1,
        pageSize: 9999,
    }, undefined)).then(response => {
        userList.value = response.rows;
    });
    getList();
}

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

</script>
