<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="customerName">
                        <el-input
                            v-model="queryParams.customerName"
                            placeholder="搜索客户"
                            clearable
                            @keyup.enter="handleQuery"
                            prefix-icon="Search"
                        />
                    </el-form-item>
                    <el-form-item prop="title">
                        <el-input
                            v-model="queryParams.title"
                            placeholder="搜索标题"
                            clearable
                            @keyup.enter="handleQuery"
                            prefix-icon="Search"
                        />
                    </el-form-item>
                    <el-form-item prop="orderTypeDictValue">
                        <SelectDict v-model="queryParams.orderTypeDictValue" placeholder="订单类型" dictCode="order_type"></SelectDict>
                    </el-form-item>
                    <el-form-item prop="continent">
                        <el-cascader  placeholder="区域名称" :options="region" v-model="regionValue" clearable filterable @change="getRegion"/>
                    </el-form-item>
                    <el-form-item prop="signingDate">
                        <el-date-picker
                            v-model="queryParams.signingDate"
                            type="date"
                            placeholder="签单日期"
                        />
                    </el-form-item>
                    <el-form-item prop="ownerByIds">
                        <SelectUser multiple v-model="queryParams.ownerByIds" placeholder="归属人员"></SelectUser>
                    </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="orderFormTableRef" :tableParams="tableParams" :btnRole="btnRole" @handleAdd="handleAdd('add')"
			@handleEdit="handleAdd('edit', $event)" @selectionChange="handleSelectionChange">
			<template #left>
				<el-button v-for="item in leftBtn" :key="item.value" @click="openDialog(item.value)" v-hasPermi="[item.hasPermi]">
                    {{ item.label }}
                </el-button>
			</template>
			<!-- <template #right>
				<el-checkbox>跟进模式</el-checkbox>
                <el-popover :width="250" placement="top-start" content="当对列表客户写跟进时，会自动将刚刚写过跟进的客户排到最后。">
                    <template #reference>
                        <i-ep-QuestionFilled style="margin-left: 5px;" />
                    </template>
                </el-popover>
			</template> -->
		</Table>
	</el-card>

    <!-- 左侧按钮弹窗 -->
    <component
		:is="dialogComponent"
		:ref="($event: any) => setItemRef($event)"
		v-bind="componentProps"
		@refresh="handleQuery"
	></component>
</template>

<script setup name="OrderForm" lang="ts">
    import { listOrderForm, delOrderForm } from '@/api/orderForm';
    import { OrderFormVO, OrderFormQuery } from '@/api/orderForm/types';
    import auth from '@/plugins/auth'
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import CreateTask from '@/components/common/createTask.vue'
    import TransferClue from '@/components/common/transferClue.vue'
    import Follow from '@/components/Follow/add.vue'
    import AddCollaborate from '@/components/common/addCollaborate.vue'
    import { useDictCache } from '@/hooks/web/useDict'
    import {region} from '@/utils/region';

    const { queryDictDetailByCodes } = useDictCache(['order_type'])
    queryDictDetailByCodes()

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

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

    const queryFormRef = ref<ElFormInstance>();

    const tableParams = reactive<tableTypes<OrderFormQuery, OrderFormVO>>({
        cloumnCode: props.perPrefix,
        menuId: router.currentRoute.value?.meta?.menuId,
        tableColumn: [
            { show: true, label: '订单编号', prop: 'id', sortable: false },
            { show: true, label: '订单标题', prop: 'title', sortable: true, render: ({ column }: { column: OrderFormVO }) => {
                return h('span', { class: 'link', onClick: () => { detail(column.id) } }, column.title)
            } },
            { show: true, label: '关联客户', prop: 'customerName', sortable: false },
            { show: true, label: '归属人员', prop: 'ownerByName', sortable: false },
            { show: true, label: '订单总金额', prop: 'quotation.totalOrderAmt', sortable: true, render: ({ column }: { column: OrderFormVO }) => {
                return column.quotation?.totalOrderAmt.toFixed(2)
            } },
            // { show: true, label: '已回款金额', prop: '', sortable: false },
            // { show: true, label: '已开票金额', prop: '', sortable: false },
            { show: true, label: '订单类型', prop: 'orderTypeName', sortable: false },
            { show: true, label: '签单日期', prop: 'signingDate', sortable: true },
            { show: false, label: '关联商机', prop: 'businessName', sortable: false },
            { show: false, label: '关联币种', prop: 'currencyName', sortable: false },
            { show: false, label: '预计生产日期', prop: 'expectedProductionDate', sortable: false },
            { show: false, label: '预计发货日期', prop: 'expectedDeliveryDate', sortable: false },
            { show: false, label: '客户签约人', prop: 'customerSignatory', sortable: false },
            { show: false, label: '我方签约人', prop: 'ourSignatory', sortable: false },
            { show: false, label: '备注信息', prop: 'remark', sortable: false },
            { show: false, label: '创建时间', prop: 'createTime', sortable: false },
            {
                show: true, label: '操作', width: 200, prop: 'operation', disabledMove: true, render: ({ column }: { column: OrderFormVO }) => {
                    let followBtn = auth.hasPermi(`orderForm:${ props.perPrefix }:gj`) ?
                        h(ElButton, { link: true, type: 'primary', onClick: () => { openDialog('follow', column) } }, '跟进') : ''
                    let toppingBtn = auth.hasPermi(`orderForm:${ props.perPrefix }:zd`) ?
                        h(ElButton, { link: true, type: 'primary' }, '置顶'): ''
                    return [
                        followBtn,
                        // toppingBtn,
                    ]
                }
            },
        ],
        keyId: 'id',
        queryParams: {
            blurry: undefined,
            orderTypeDictValue: undefined,
            signingDate: undefined,
            ownerByIds: undefined,
            queryRangeType: props.queryRangeType,
            customerName: undefined,
            title: undefined,
            country: undefined,
        },
        listFn: listOrderForm,
        delFn: delOrderForm,
        importCode: 'IMPORT_ORDER_EXCEL',
        exportCode: 'EXPORT_ORDER_EXCEL',
        commonQueryOrderBy: 'signingDate'
    })

    let leftBtn = [
        { label: '转移订单', value: 'transfer', hasPermi: `orderForm:${ props.perPrefix }:zydd` },
        { label: '添加协作', value: 'cooperation', hasPermi: `orderForm:${ props.perPrefix }:tjxz` },
        { label: '新建任务', value: 'task', hasPermi: `orderForm:${ props.perPrefix }:xjrw` },
    ]

    const { queryParams } = toRefs(tableParams);

    const regionValue = ref([])
    const getRegion = (value) => {
        tableParams.queryParams.country = value?value[1]:''
    }

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

    /** 重置按钮操作 */
    const resetQuery = () => {
        regionValue.value = []
        tableParams.queryParams.country = ''
        queryFormRef.value?.resetFields();
        handleQuery();
    }

    /** 多选框选中数据 */
    const ids = ref<(string | number)[]>([]);
    const handleSelectionChange = (selection: OrderFormVO[]) => {
        ids.value = selection.map(item => item.id);
    }

    /** 新增按钮操作 */
    const handleAdd = (type: string, data?: OrderFormVO) => {
        router.push('./add?type=' + type + '&id=' + data?.id)
    }

    // 左侧按钮弹窗
    const dialogComponent = shallowRef()
    const componentProps = shallowRef()
    const dialogRef = ref()
    const setItemRef = (el: any) => {
        if (el) {
            dialogRef.value = el
        }
    }
    const openDialog = (val: string, data?: OrderFormVO) => {
        if(val == 'email') {
            return false
        }
        if(val != 'follow' && ids.value.length == 0) {
            ElMessage.error("请选择数据")
            return false
        }
        let query = {}
        switch (val) {
            case 'transfer': // 转移订单
                dialogComponent.value = TransferClue
                query = {
                    resourceType: '40',
                    typeName: '订单',
                    idList: ids.value
                }
                break;
            case 'cooperation': // 添加协作
                dialogComponent.value = AddCollaborate
                query = {
                    resourceType: 40,
                    resourceIdList: ids.value
                }
                break;
            case 'task': // 新建任务
                dialogComponent.value = CreateTask
                componentProps.value = { isCorrelation: false }
                query = { type: 'add', obj: { resourceType: '40', resourceTypeIdls: ids.value } }
                break;
            case 'follow': // 跟进
                dialogComponent.value = Follow
                query = {
                    type: 'add',
                    resourceType: '40',
                    customerId: data?.customerId,
                    customerName: data?.customerName,
                    resourceTypeId: data?.id,
                    resourceName: data?.title,
                }
                break;
        }
        nextTick(() => {
            dialogRef.value.open(query)
        })
    }

    const detail = (id: string | number) => {
        router.pushTarget('/order/detail?id=' + id + '&scopeMenuId=' + router.currentRoute.value?.meta?.menuId)
    }
</script>
