<template>
	<el-card shadow="never" class="list-card">
		<template #header>
			<div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-form-item prop="blurry">
                        <el-input
                            v-model="queryParams.blurry"
                            placeholder="搜索关键词"
                            clearable
                            @keyup.enter="handleQuery"
                            prefix-icon="Search"
                        />
                    </el-form-item>
                    <el-form-item prop="orderStatus">
                        <SelectDict v-model="queryParams.orderStatus" placeholder="工单状态" dictCode="order_status"></SelectDict>
                    </el-form-item>
                    <el-form-item prop="workOrderCategoryId">
                        <SelectDict v-model="queryParams.workOrderCategoryId" placeholder="工单类型" dictCode="work_order_category_id"></SelectDict>
                    </el-form-item>
                    <el-form-item prop="urgentStatus">
                        <SelectDict v-model="queryParams.urgentStatus" placeholder="紧急状态" dictCode="urgent_status"></SelectDict>
                    </el-form-item>
                    <el-form-item prop="dataCode">
                        <SelectDict placeholder="等待时间" dictCode="order_wait_time"></SelectDict>
                    </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>
            </div>
		</template>

		<Table
			ref="orderTable"
			:tableParams="tableParams"
			:btnRole="btnRole"
			@handleAdd="handleAdd"
			@selection-change="selectionChange"
		>
			<template #left>
				<el-button @click="distribution" v-hasPermi="[`order:${ props.perPrefix }:fpgd`]">分配工单</el-button>
			</template>
		</Table>
	</el-card>

	<!-- 添加工单对话框 -->
	<AddOrder ref="addOrderRef" @refresh="handleQuery" />

	<!-- 分配工单 -->
	<Distribution ref="distributionRef" @refresh="handleQuery" />
</template>

<script setup name="Order" lang="ts">
    import { listOrder, delOrder, distributionOrder } from '@/api/order';
    import { OrderVO, OrderQuery } from '@/api/order/types';
    import auth from '@/plugins/auth'
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'

    import AddOrder from '@/components/common/addOrder.vue'
    import Distribution from '@/components/common/distribution.vue'
    import { useDictCache } from '@/hooks/web/useDict'

    const { queryDictDetailByCodes } = useDictCache(['order_status', 'work_order_category_id', 'urgent_status', 'order_wait_time'])
    queryDictDetailByCodes()

    const props = defineProps({
        perPrefix: {
            type: String,
            required: true
        },
        queryRangeType: {
            type: Number
        }
    })

    const router = useRouter();
    const btnRole = ref([
        { type: 'add', hasPermi: `order:${ props.perPrefix }:add` },
        { type: 'remove', hasPermi: `order:${ props.perPrefix }:remove` },
        { type: 'import', hasPermi: `order:${ props.perPrefix }:import` },
        { type: 'export', hasPermi: `order:${ props.perPrefix }:export` }
    ])

    const queryFormRef = ref<ElFormInstance>();

    const tableParams = reactive<tableTypes<OrderQuery, OrderVO>>({
        cloumnCode: props.perPrefix,
        menuId: router.currentRoute.value?.meta?.menuId,
        tableColumn: [
            { show: true, label: '工单编号', prop: 'id', sortable: true },
            { show: true, label: '工单标题', prop: 'title', sortable: true },
            { show: true, label: '工单类型', prop: 'workOrderCategoryName', sortable: true },
            { show: true, label: '处理人员', prop: 'ownerByName', sortable: true },
            { show: true, label: '发起时间', prop: 'createTime', sortable: true },
            { show: true, label: '工单状态', prop: 'orderStatusName', sortable: true },
            { show: true, label: '紧急程度', prop: 'urgentStatusName', sortable: true },
            { show: false, label: '关联客户ID', prop: 'customerId', sortable: true },
            { show: false, label: '关联订单id', prop: 'orderFormId', sortable: true },
            { show: false, label: '期望完成时间', prop: 'expectTime', sortable: true },
            { show: false, label: '实际完成时间', prop: 'actualTime', sortable: true },
            { show: false, label: '提醒用户id，逗号隔开', prop: 'remindUserIds', sortable: true },
            { show: false, label: '最后处理人', prop: 'currentUserId', sortable: true },
            { show: false, label: '订单发起次数', prop: 'orderCount', sortable: true },
            { show: false, label: '退回原因备注', prop: 'remark', sortable: true },
            { show: false, label: '撤销、拒绝时间', prop: 'revokeTime', sortable: true },
            { show: false, label: '工单来源', prop: 'orderFrom', sortable: true },
            { show: false, label: '再次发起说明', prop: 'orderAgain', sortable: true },
            { show: false, label: '创建时间', prop: 'createTime', sortable: true },
            { show: false, label: '修改时间', prop: 'updateTime', sortable: true },
            { show: false, label: '创建者', prop: 'createBy', sortable: true },
            { show: false, label: '拥有者', prop: 'ownerBy', sortable: true },
            { show: false, label: '更新者', prop: 'updateBy', sortable: true },
            { show: false, label: '显示顺序', prop: 'sort', sortable: true },
            {
                show: true, label: '操作', width: 150, prop: 'operation', disabledMove: true, render: ({ column }: { column: OrderVO }) => {
                    return [
                        auth.hasPermi(`order:${ props.perPrefix }:xq`) ?
                        h(ElButton, { link: true, type: 'primary', onClick: () => { handleDetail(column) } }, '详情') : ''
                    ]
                }
            },
        ],
        queryParams: {
            blurry: undefined,
            orderStatus: undefined,
            workOrderCategoryId: undefined,
            urgentStatus: undefined,
            queryRangeType: props.queryRangeType
        },
        listFn: listOrder,
        delFn: delOrder,
        keyId: 'id',
        importCode: 'IMPORT_WORK_ORDER_EXCEL',
        exportCode: 'EXPORT_WORK_ORDER_EXCEL'
    })

    const { queryParams } = toRefs(tableParams);

    const orderTable = ref()
    /** 搜索按钮操作 */
    const handleQuery = () => {
        orderTable.value.getData()
    }

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

    /** 新增按钮操作 */
    const addOrderRef = ref()
    const handleAdd = () => {
        addOrderRef.value.open({ type: 'add' })
    }

    const selectionData = ref<OrderVO[]>([])
    const selectionChange = (selection: OrderVO[]) => {
        selectionData.value = selection
    }

    // 分配工单
    const distributionRef = ref()
    const distribution = () => {
        if(selectionData.value.length == 0) {
            ElMessage.error('请选择工单')
            return false
        }
        if(!selectionData.value.find(a => a.orderStatus == 4)) {
            let params = {
                typeName: '工单',
                handleFn: distributionOrder,
                query: { workOrderIds: selectionData.value.map(item => item.id).join(",") }
            }
            distributionRef.value.open(params)
        }else {
            ElMessage.error('仅未完结工单支持分配')
        }
    }

    // 工单详情
    const handleDetail = (data: OrderVO) => {
        router.push('./detail?id=' + data.id)
    }
</script>
