<template>
    <el-row :gutter="12">
        <el-col :span="6">
            <div class="flex items-center gap-2">
                <el-select
                    v-model="filterVariable.customer"
                    placeholder="选择客户"
                    size="large"
                    multiple
                    filterable
                    collapse-tags
                    collapse-tags-tooltip
                    @change="startFilter"
                     :disabled="disabled"
                >
                    <el-option v-for="customer in customer_list" :label="customer_name(customer)" :value="customer.id" :key="customer.id" />
                </el-select>
                <el-input v-model.trim="filterVariable.code" placeholder="订单包含件号" size="large" @change="startFilter" :disabled="disabled" />
            </div>
        </el-col>
        <el-col :span="3">
            <div class="flex items-center gap-2">
                <el-select
                    v-if="userStore.userArray.length > 1"
                    v-model="filterVariable.operator"
                    placeholder="业务主办"
                    size="large"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    @change="startFilter"
                    :disabled="disabled"
                >
                    <el-option v-for="item in userStore.userArray" :label="userStore.shopMember[item]" :value="item" :key="item" />
                </el-select>
                <el-select v-model="filterVariable.status" placeholder="状态节点" size="large" @change="startFilter" :disabled="disabled">
                    <el-option label="所有询盘单" :value="0"/>
                    <el-option label="待处理" :value="1"/>
                    <el-option label="已建询函" :value="2"/>
                    <el-option label="询函已检" :value="3"/>
                    <el-option label="已建报价" :value="4"/>
                    <el-option label="报价已批" :value="5"/>
                    <el-option label="待付款" :value="6"/>
                </el-select>
            </div>
        </el-col>
        <el-col :span="4">
            <div class="flex items-center gap-2">
                <el-date-picker
                    v-model="filterVariable.date"
                    type="daterange"
                    unlink-panels
                    range-separator="到"
                    start-placeholder="开始日期"
                    end-placeholder="终到日期"
                    size="large"
                    value-format="YYYY-MM-DD"
                    @change="startFilter"
                    :disabled="disabled"
                />
                <el-button @click="resetFilter" type="success" class="hover:(bg-red-400 text-white)"><i class="fa fa-eraser pr-2"></i>重置筛选</el-button>
                <el-button @click="handleCurrentChange" type="primary" class="ml-2"><i class="fa fa-bolt pr-2"></i>列表刷新</el-button>
            </div>
        </el-col>
        <el-col :span="4" :offset="1" class="flex items-center">
            <el-button @click="router.push({path:'/inquiry/create'})" type="danger"><i class="fa fa-plus pr-2"></i>手动建单</el-button>
            <el-button color="#00828a" @click="handleMerge" :disabled="selectionRows.length<2" class="ml-2 pr-2"><i class="fa fa-chain"></i>合并询单</el-button>
        </el-col>
    </el-row>

    <el-table
        ref="orderTableRef"
        v-loading="loading"
        :data="order_list"
        :height="tableHeight"
        stripe
        style="width: 100%;"
        size="large"
        row-class-name="no-expand-icon"
        row-key="id"
        @expand-change="expandChange"
        class="mt-2"
        :expand-row-keys="expandRowKeys"
        :select-on-indeterminate="false"
        :default-expand-all="false"
        @selection-change="handleTableSelectionChange"
    >
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column
            label="建单时间"
            width="120"
            header-align="center"
            align="center"
        >
            <template #default="{row}">
                <el-tooltip
                    class="cursor-pointer"
                    effect="dark"
                    :content="`${row.id}`"
                    placement="top-start"
                >
                    <el-text size="small">{{ dayjs(row.create_time).format('YY-MM-DD HH:mm') }}</el-text>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="order_no" label="尾号" header-align="center" align="center" width="86px">
            <template #default="{row,$index}">
                <el-button
                    text
                    @click="row.creator==userStore.userId||userStore.partner.find(id=>id==row.creator)?router.push({path:`/inquiry/edit/${row.id}`}):handleInquiryResult(row,$index,$event)"
                    :disabled="row.is_del != 0"
                >
                    <el-text size="small" tag="b" class="hover:(bg-transparent text-red-900)">{{ row.order_no.slice(12) }}</el-text>
                </el-button>
            </template>
        </el-table-column>
        <el-table-column label="客户名称" :show-overflow-tooltip="true" width="180px" header-align="center">
            <template #default="{row}">
                <el-popover
                    placement="right"
                    title="客户联系"
                    :width="240"
                    trigger="hover"
                >
                    <template #default>
                        <hr>
                        <div class="mt-2" v-if="row.mobile2 || row.email">
                            <div class="pl-2" v-if="row.mobile2">
                                <el-text size="small" tag="b">手机：</el-text>
                                <el-text size="small" tag="span">{{ row.mobile2 }}</el-text>
                            </div>
                            <div class="pl-2" v-if="row.email">
                                <el-text size="small" tag="b">邮箱：</el-text>
                                <el-text size="small" tag="span" v-if="row.email">{{ row.email }}</el-text>
                            </div>
                        </div>
                        <el-text size="small" tag="span" v-else>无联系方式</el-text>
                    </template>
                    <template #reference>
                        <el-text size="small">{{ row.true_name ? row.true_name : row.user_name }}</el-text>
                    </template>
                </el-popover>
            </template>
        </el-table-column>
        <el-table-column label="订单摘要" header-align="center" width="200px" show-overflow-tooltip>
            <template #default="{row}">
                <el-text v-if="userStore.isAdmin || userStore.userId==row.creator || userStore.partner.find(id=>id==row.creator)" size="small" type="warning" class="mx-2 cursor-pointer" @click="handleSubject(row)"><i class="fa fa-pencil"></i></el-text>
                <el-text size="small" type="info" tag="b">{{ row.subject }}</el-text>
            </template>
        </el-table-column>
        <el-table-column label="订单商品" header-align="center" width="90px" align="center">
            <template #default="{row,$index}">
                <el-button
                    size="small"
                    circle
                    @click="editable(row) ? handleBaseInfo(row,$index,$event) : () => {}"
                    :type="editable(row) ? 'primary' : 'warning'"
                >
                    {{ row.products.length }}
                </el-button>
            </template>
        </el-table-column>
        <el-table-column prop="note" label="订单备注" show-overflow-tooltip width="200px" header-align="center">
            <template #default="{row}">
                <el-text size="small" tag="b" type="danger">{{ row.note }}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="creator" label="主办" width="160" show-overflow-tooltip header-align="center" align="center" v-if="userStore.userArray.length > 1">
            <template #default="{row}">
                {{ userStore.shopMember[row.creator] || `ID-${row.creator}` }}
            </template>
        </el-table-column>
        <el-table-column label="工作节点" align="center" header-align="center" width="140px">
            <template #default="{row}">
                <el-popover
                     v-if="row.is_del==2 || row.is_del==3"
                    :content="row.reason"
                    placement="right-end"
                >
                    <template #reference>
                        <el-tag effect="dark" color="#b23b2f" size="large" v-if="row.is_del==2 || row.is_del==3">
                            {{ row.is_del == 2 ? '业务中止' : '客户中止'}}
                        </el-tag>
                    </template>
                </el-popover>
                <el-tag effect="dark" :type="row.status==0 ? 'danger' : row.status==5 ? 'success' : 'primary'" size="large" v-else>
                    {{ row.status==0 ? (row.products.length == 0 ? '添加商品' : (row.inquiry_status.total == 0 ? '制询价函' : (row.inquiry_status.checked > 0 ? '等待报价' : '回函处理'))) : orderStatus(row.status,row.is_del) }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="询价状态" align="center" header-align="center" width="100px">
            <template #default="{row,$index}">
                <el-tag
                    size="large"
                    effect="dark"
                    :type="row.inquiry_status.checked > 0 ? 'success' : row.inquiry_status.receice > 0 ? 'primary' : 'warning'"
                    @click="editable(row) ? handleCheckSupply(row,$index,$event) : () => {}"
                    :class="editable(row) ? 'cursor-pointer' : ''"
                >
                    {{ `${row.inquiry_status.checked}/${row.inquiry_status.receive}` }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="询盘报价" align="right" header-align="center" prop="total_price" width="160">
            <template #default="{row}">
                <el-text :type="row.total_price==0?'danger':'primary'">{{`￥${row.total_price.toFixed(2)}`}}</el-text>
            </template>
        </el-table-column>
        <el-table-column label="" header-align="center">
            <template #default="scope">
                <el-button
                    size="default"
                    type="default"
                    @click="handleWorkflow(scope.row)"
                >
                    <i class="fa fa-history pr-2"></i>工作流
                </el-button>
                <el-button
                    type="primary"
                    @click="handleBaseInfo(scope.row,scope.$index,$event)"
                    :disabled="!editable(scope.row)"
                    class="px-2"
                >
                    品
                </el-button>
                <el-button
                    type="primary"
                    @click="handleCheckSupply(scope.row,scope.$index,$event)"
                    :disabled="!editable(scope.row)"
                    class="px-2"
                >
                    询
                </el-button>
                <!-- <el-button
                    type="primary"
                    @click="handleOfferEdit(scope.row,scope.$index,$event)"
                    :disabled="+scope.row.inquiry_status.checked <= 0 || !editable(scope.row) || +scope.row.is_del != 0"
                    class="px-2"
                >
                    报
                </el-button> -->
                <el-popconfirm
                    width="220"
                    confirm-button-text="删除"
                    cancel-button-text="取消"
                    :icon="InfoFilled"
                    icon-color="#626AEF"
                    title="确定要删除这个订单?"
                    @confirm="handleDelete(scope.$index, scope.row)"
                    @cancel="() => {}"
                >
                    <template #reference>
                        <el-button
                            size="default"
                            type="danger"
                            :disabled="scope.row.status!='0' || scope.row.is_del == 2 || scope.row.is_del == 3"
                            :icon="Delete"
                        />
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>

    <div class="pages">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[20,30,40,50]"
            :disabled="false"
            size="small"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @update:current-page="handleCurrentChange"
            @update:page-size="handleSizeChange"
        />
    </div>

    <el-dialog
        v-model="workflowDialogVisible"
        title="订单工作流"
        width="30%"
        destroy-on-close
        center
        :draggable="true"
    >
        <div style="max-height: 50vh;overflow: auto;">
            <el-card class="box-card-edit">
                <el-timeline>
                    <el-timeline-item
                        v-for="(activity, index) in workflow"
                        :key="index"
                        :timestamp="activity.addtime"
                        placement="top"
                    >
                        <el-card>
                            <h4>{{ activity.action }}</h4>
                            <p>{{ activity.user }}在{{ activity.addtime }}提交</p>
                        </el-card>
                    </el-timeline-item>
                </el-timeline>
            </el-card>
        </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="workflowDialogVisible=false" :icon="Share">知道了!</el-button>
                </span>
                </template>
    </el-dialog>

    <el-drawer v-model="showInquiryDrawer" :direction="direction" size="49%">
        <template #header>
            <el-text tag="b" type="primary" size="large">询盘详情</el-text>
        </template>
        <template #default>
            <div class="w-full p-2 flex overflow-auto justify-center">
                <el-table
                    size="small"
                    fit
                    :data="inquiry_result"
                    class="text-xs w-auto"
                    style="border: 1px solid black;"
                    :header-cell-style="{background: '#e0f2fe', color: 'black',borderColor: 'black'}"
                    :cell-style="{borderColor: 'black'}"
                    :max-height="subTableHeight - 40"
                    border
                >
                    <el-table-column type="index" label="#" width="50" align="center" header-align="center"/>
                    <el-table-column prop="b_name" label="品牌" show-overflow-tooltip width="100" align="left" header-align="center"/>
                    <el-table-column prop="code" label="件号" show-overflow-tooltip width="120" align="left" header-align="center"/>
                    <el-table-column prop="new_code" label="更新件号" show-overflow-tooltip width="100" align="left" header-align="center"/>
                    <el-table-column prop="name" label="品名" show-overflow-tooltip width="120" align="left" header-align="center"/>
                    <el-table-column prop="price" label="面价" show-overflow-tooltip width="100" align="right" header-align="center">
                        <template #default="{row}">
                            {{ (Math.round(row.price * 100) / 100.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sell_price" label="预计售价" show-overflow-tooltip width="100" align="right" header-align="center">
                        <template #default="{row}">
                            {{ (Math.round(row.sell_price * 100) / 100.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="goods" label="商城状况" show-overflow-tooltip width="120" header-align="center" align="center">
                        <template #default="{row}">
                            <el-tag v-if="row.goods?.length>0" type="danger">有货({{ row.goods?.length }})</el-tag>
                            <el-tag v-else type="primary">无货</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="客户采购" header-align="center">
                        <el-table-column prop="amount" label="采购数" show-overflow-tooltip width="80" align="right" header-align="center"/>
                        <el-table-column prop="note" label="客户备注" show-overflow-tooltip width="120" align="left" header-align="center"/>
                    </el-table-column>
                    <el-table-column label="销售报价" width="120" align="center" header-align="center" v-if="inquiry_result_status == 3">
                        <el-table-column label="供应品牌" show-overflow-tooltip width="100" align="left" header-align="center">
                            <template #default="{row}">
                                {{ row.g_bname }}
                            </template>
                        </el-table-column>
                        <el-table-column label="商品品相" show-overflow-tooltip width="80" align="left" header-align="center">
                            <template #default="{row}">
                                {{ row.g_quality }}
                            </template>
                        </el-table-column>
                        <el-table-column label="销售价" width="100" align="right" header-align="center">
                            <template #default="{row}">
                                {{ (+row.g_sell_price).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="加急服务" width="100" align="right" header-align="center">
                            <template #default="{row}">
                                {{ (+row.g_sell_price2).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="销售数" width="80" align="right" header-align="center">
                            <template #default="{row}">
                                {{ row.g_nums }}
                            </template>
                        </el-table-column>
                        <el-table-column label="销售备注" show-overflow-tooltip width="120" align="left" header-align="center">
                            <template #default="{row}">
                                {{ row.g_note }}
                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
            </div>
        </template>
    </el-drawer>

    <el-drawer v-model="toggleEditDrawer" :direction="direction" size="49%">
        <template #header>
            <el-text tag="b" type="primary" size="large">{{edit_tabs[editDrawer]?.label}}</el-text>
        </template>
        <template #default>
            <Suspense>
                <component
                    @status-change="handleStatusChange"
                    :is="edit_tabs[editDrawer]?.component"
                    :order-id="+editRow.id"
				    :order-status="+editRow.status"
                    :key="editRow.id"
                >
                    <!-- <template #nogo>
                        <el-button color="#b23b2f" @click="nogo" size="large" class="ml-4"><i class="fa fa-stop pr-2"></i>业务中止</el-button>
                    </template>
                    <template #rollback>
                        <span v-if="editRow?.id && editRow?.status!=0 && editDrawer != 'inquiry'">
                            <el-button
                                type="warning"
                                @click="rollback"
                                size="large"
                                class="ml-4"
                            >
                                <i class="fa fa-reply pr-2"></i>流程回滚
                            </el-button>
                        </span>
                    </template> -->
                </component>
                <!-- <template #fallback>
                    功能加载中，请稍候...
                </template> -->
            </Suspense>
        </template>
        <template #footer>
            <div style="flex: auto">
                <span v-if="editRow?.id && editRow?.status!=0 && editDrawer != 'inquiry'">
                    <el-button
                        type="warning"
                        @click="rollback"
                        size="large"
                        class="mx-6"
                    >
                        <i class="fa fa-reply pr-2"></i>流程回滚
                    </el-button>
                </span>
                <el-button color="#b23b2f" @click="nogo" size="large" class="mx-6"><i class="fa fa-stop pr-2"></i>业务中止</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
    import { ref,onMounted,computed, onUnmounted,defineAsyncComponent,markRaw,reactive,toRaw,toRefs } from 'vue'
    import { useRouter } from 'vue-router'
    import dayjs from 'dayjs'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { customerList,supplierList,sellerList,addLog,getLog }  from '@/api'
    import { inquiryList,inquiryStatus,createInquiry,addInquiryGoods,removeInquiry,update,inquiry,removeSupplyInquiry}  from '@/api/inquiry'
    import { status_name }  from '@/utils'
    import { storeToRefs } from 'pinia'
    import { useUserStore,useInquiryListStore } from '@/store'
    import { Share,Delete,InfoFilled,HomeFilled,Search,EditPen,Flag } from '@element-plus/icons-vue'
    // import EditInquiry from '@/components/Base.vue'
    // import EditSupply from '@/components/Inquiry.vue'
    // import EditOffer from '@/components/Offer.vue'

    const timer = ref(null)
    onMounted(async () => {
        tableHeight.value = window.innerHeight - 180
        const { data:customer } = await customerList()
        if(customer.error == 0) {
            customer_list.value = customer.data
        }
        await get_order_list()
        timer.value = setInterval(async() => {
            await get_inquiry_status()
        },60000)
        const {data:supplier} = await supplierList()
        supplier_list.value = supplier.data.map(item => ({id:item.sid,name:item.sname,mobile:item.mobile}))
        const {data:seller} = await sellerList()
        seller_list2.value = seller.data.map(item => ({id:`G${item.id}`,name:`*商城*${item.seller_name}`,mobile:item.mobile}))
    })

    onUnmounted(() => {
        if(timer.value)
            clearInterval(timer.value)
    })

    const userStore = useUserStore()
    const router = useRouter()
    const inquiryStore = useInquiryListStore()
    const { currentPage,pageSize,keys: filterVariable } = storeToRefs(inquiryStore)

    const order_list = ref([])
    const total = ref(0)
    const orderTableRef = ref()
    const orderIds = ref([])
    const customer_list = ref([])

    const seller_list2 = ref([])
    const supplier_list = ref([])

    const background = ref(false)
    const workflowDialogVisible = ref(false)
    const tableHeight = ref(0)
    const subTableHeight = ref(480)
    const loading = ref(false)

    const orderStatus = computed(() => (status,isdel) => status_name(status,isdel))
    const editable = computed(() => (row) => row.creator == userStore.userId || userStore.partner.includes(row.creator))

    const get_order_list = async () => {
        loading.value = true
        const { data:res } = await inquiryList(userStore.userArray,filterVariable.value,currentPage.value,pageSize.value)
        order_list.value = res.data
        total.value = res.total
        orderIds.value = []
        order_list.value.forEach(async (item) => {
            item.expand = +item.status <= 1 ? true : false
            item.result = item.products
            let total = 0
            item.offer.forEach(g => total += g.amount * parseFloat(g.sell_price))
            item['total_price'] = total
            orderIds.value.push(item.id)
        })
        loading.value = false
    }

    const loadInquiryRow = async (id) => {
        const {data:res} = await inquiry(id)
        if(res.error == 0 && res.data.id && +res.data.id == id) {
            let row = order_list.value.find(item => item.id == id)
            if(row) {
                let item = res.data
                item.expand = +item.status <= 1 ? true : false
                item.result = item.products
                let total = 0
                item.offer.forEach(g => total += g.amount * parseFloat(g.sell_price))
                item['total_price'] = total
                Object.assign(row,item)
            }
        }
    }
    const get_inquiry_status = async () => {
        let ids = order_list.value.map(item => item.id)
        const {data:status} = await inquiryStatus(ids)
        if(status.error == 0) {
            order_list.value.forEach(item => {
                let status_item = status.data.find(s => s.id == item.id)
                if(status_item) {
                    item.inquiry_status = status_item.inquiry
                    item.status = status_item.status
                    item.is_del = status_item.is_del
                }
            })
        }
    }

    const workflow = ref([])
    const handleWorkflow = async (row) => {
        workflow.value = []
        const {data:res} = await getLog(row.id)
        workflow.value = res.data
        workflowDialogVisible.value = true
    }
    const handleDelete = async (index,row) => {
        const data = await removeInquiry([row.id])
        await get_order_list()
    }

    const supplierName = computed(() => (id) => {
        if(`${id}`.startsWith('G')) {
            let ids = `${id}`.split('-')
            let idx = seller_list2.value.findIndex(item => item.id == ids[0])
            if(idx != -1) {
                return seller_list2.value[idx].name
            }
        } else {
            let idx = supplier_list.value.findIndex(item => item.id == id)
            if(idx != -1) {
                return supplier_list.value[idx].name
            }
        }
        return 'unknown'
    })

    const customer_name = computed(() => (item) => {
        let val = `${item.true_name}`
        if(item.username != item.true_name) {
            val += ` ${item.username}`
        }
        if(item.mobile != null && item.mobile != '') {
            val += ` ${item.mobile}`
        }
        return val
    })

    const expandRowKeys = ref([])
    const expandChange = async (row,rows) => expandRowKeys.value = rows.map(item => item.id)

    const disabled = ref(false)
    const startFilter = async () => {
        currentPage.value = 1
        disabled.value = true
        await get_order_list()
        disabled.value = false
    }

    const resetFilter = async () => {
        inquiryStore.reset()
        await get_order_list()
    }

    const handleSizeChange = async (val) => {
        currentPage.value = 1
        await get_order_list()
    }

    const handleCurrentChange = async (val) => {
        await get_order_list()
    }

    const selectionRows = ref([])
    const handleTableSelectionChange = (rows) => selectionRows.value = rows
    const handleMerge = async () => {
        let rows = selectionRows.value
        let isSame = true
        let user_id = rows[0].user_id
        for(let i=1;i<rows.length;i++) {
            if(rows[i].user_id != user_id || rows[i].status != 0) {
                isSame = false
                break
            }
        }
        if(!isSame) {
            ElMessage({
                message: '无法合并不同用户或者已进行中的询单！',
                type: 'error',
            })
            return
        }
        let goods = []
        rows.forEach(row => {
            row.products.forEach(g => {
                let idx = goods.findIndex(gr => gr.id == g.id && gr.brand == g.brand)
                if(idx != -1) {
                    goods[idx].amount = +goods[idx].amount + +g.amount
                } else {
                    goods.push(g)
                }
            })
        })
        const {data:res} = await createInquiry(user_id,'合并询单')
        if(res.data.order_id) {
            await addInquiryGoods(res.data.order_id,goods)
            let orders = rows.map(order => order.id)
            await removeInquiry(orders)
            await addLog(res.data.order_id,`${userStore.userName}(${userStore.userId})`,'合并订单',JSON.stringify(orders))
            ElMessage({
                message: '订单合并成功！',
                type: 'success',
            })
        }
        currentPage.value = 1
        await get_order_list()
    }

    const toggleEditDrawer = ref(false)
    const editDrawer = ref('inquiry')
    const direction = ref('ttb')
    const editRow = ref(null)
    const editRowIndex = ref(0)

	const EditInquiry = defineAsyncComponent(() => import('@/components/Base.vue'))
	const EditSupply = defineAsyncComponent(() => import('@/components/Inquiry.vue'))
	const EditOffer = defineAsyncComponent(() => import('@/components/Offer.vue'))

	const edit_tabs = reactive({
		inquiry: {
			label: '询盘单及商品信息',
			icon: markRaw(HomeFilled),
			disabled: false,
			component: markRaw(EditInquiry)
		},
		supply: {
			label: '供应商询件',
			icon: markRaw(Search),
			disabled: true,
			component: markRaw(EditSupply)
		},
		offer: {
			label: '优选报价',
			icon: markRaw(EditPen),
			disabled: true,
			component: markRaw(EditOffer)
		},
		// result: {
		// 	label: '4.询盘结果',
		// 	icon: markRaw(Flag),
		// 	disabled: true,
		// 	component: markRaw(Result)
		// },
    })

    const showInquiryDrawer = ref(false)
    const inquiry_result = ref([])
    const inquiry_result_status = ref(0)
    const handleInquiryResult = async (row,index,evt) => {
        if(window.innerHeight >= evt.y * 2) {
            direction.value = 'btt'
        } else {
            direction.value = 'ttb'
        }
        if(!row.expand) {
            row.result = []
            row.offer.forEach(item => {
                item.offer.forEach(g => {
                    row.result.push(Object.assign({}, item, {
                        g_id: g.id,
                        g_brand: `${g.id}`.startsWith('G') ? g.brand : item.brand,
                        g_bname: `${g.id}`.startsWith('G') ? g.b_name : item.b_name,
                        g_name: g.name,
                        g_sell_price: g.sell_price,
                        g_sell_price2: g.sell_price2,
                        g_quality: `${item.id}`.startsWith('G') ? item.quality : '原装全新',
                        g_nums: g.nums,
                        g_note: g.note,
                    }))
                })
            })
            row.expand = true
        }
        inquiry_result.value = row.result
        inquiry_result_status.value = +row.status
        showInquiryDrawer.value = true
    }

    const checkBaseInfoDrawer = ref(false)
    const handleBaseInfo = async (row,index,evt) => {
        if(window.innerHeight >= evt.y * 2) {
            direction.value = 'btt'
        } else {
            direction.value = 'ttb'
        }
        editRow.value = row
        editRowIndex.value = index
        editDrawer.value = 'inquiry'
        toggleEditDrawer.value = true
    }

    const handleCheckSupply = async (row,index,evt) => {
        if(window.innerHeight >= evt.y * 2) {
            direction.value = 'btt'
        } else {
            direction.value = 'ttb'
        }
        editRow.value = row
        editRowIndex.value = index
        editDrawer.value = 'supply'
        toggleEditDrawer.value = true
    }

    const handleSubject = async (row) => {
        ElMessageBox.prompt('编辑摘要', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValue: row.subject,
            inputPlaceholder: '请输入摘要'
        }).then(async ({ value }) => {
            await update(row.id,{subject:value})
            row.subject = value
            await addLog(row.id,userStore.logName,'修改订单摘要',value)
            ElMessage({
                message: '成功修改订单摘要!',
                type: 'success',
            })
        }).catch(() => {
            ElMessage({
                type: 'warning',
                message: '取消编辑'
            });
        });
    }

    const handleStatusChange = async (id,state) => {
		if(!id) {
			return
		}
		switch(state) {
			case 'create-inquiry':
			case 'subject-change':
			case 'note-change':
			case 'customer-change':
				break
			case 'save-goods':
                await loadInquiryRow(id)
                toggleEditDrawer.value = false
				break
			case 'make-offer':
                await loadInquiryRow(id)
                toggleEditDrawer.value = false
				break
			case 'share-offer':
			case 'user-cancel':
				break;
			case 'remove-supply-inquiry':
				break
		}
    }

	const nogo = () => {
		if(!editRow.value.id) {
			return
		}
		ElMessageBox.prompt('请填写提前业务中止理由：', '客服中断', {
			type: 'warning',
			showCancelButton: true,
			cancelButtonText: '取消',
			confirmButtonText: '确定'
		}).then(async (val) => {
			await update(editRow.value.id, {is_del: 2,reason: val.value})
			router.push('/inquiry/list')
			await addLog(editRow.value.id,userStore.logName,'客服中断',val.value)
			ElMessage.success('询盘业务已提前中止！')
		}).catch(() => {
			ElMessage.error('无法种植业务！')
		})
	}

	const rollback = async () => {
		switch(editDrawer.value) {
			case 'inquiry':
				return
			case 'supply':
				ElMessageBox.confirm('确定要回滚到询盘基础节点吗？', '流程回滚', {
					type: 'warning',
					showCancelButton: true,
					cancelButtonText: '取消',
					confirmButtonText: '回滚'
				}).then(async () => {
					await removeSupplyInquiry(editRow.value.id)
					await update(editRow.value.id,{status: 0})
					await addLog(editRow.value.id,userStore.logName,'流程回滚','回滚到询盘基础节点')
					ElMessage.success('已回退到询盘基础！')
					editDrawer.value = 'inquiry'
				}).catch(() => {
					ElMessage.error('无法回滚流程！')
				})
				break
			case 'offer':
				ElMessageBox.confirm('确定要新建报价吗？', '新建报价', {
					type: 'warning',
					showCancelButton: true,
					cancelButtonText: '取消',
					confirmButtonText: '确定'
				}).then(async () => {
					await update(editRow.value.id,{status: 1,o_time: null,offer: null})
					await addLog(editRow.value.id,userStore.logName,'流程回滚','新建报价')
					ElMessage.success('已回退到询盘基础！')
					editDrawer.value = 'supply'
				}).catch(() => {
					ElMessage.error('无法重建报价！')
				})
				break
			case 'result':
				break
			case 'result':
				break
		}
	}
</script>

<style scoped>
    .el-table .cell {
        white-space: pre-wrap;
    }
    .pages {
        padding-top: 20px;
    }
    :deep(.no-expand-icon .el-table__expand-icon) {
        display: none;
    }
</style>