<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"
                >
                    <el-option v-for="customer in customer_list" :label="customer_name(customer)" :value="customer.id" :key="customer.id" />
                </el-select>
                <el-input v-model="filterVariable.code" placeholder="订单包含件号" size="large" @change="startFilter" />
            </div>
        </el-col>
        <el-col :span="3">
            <div class="flex items-center gap-2">
                <el-select
                    v-if="userStore.team.length > 1"
                    v-model="filterVariable.operator"
                    placeholder="业务主办"
                    size="large"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    @change="startFilter"
                >
                    <el-option v-for="[id,item] of Object.entries(userStore.teamInfo)" :label="item.name" :value="id" :key="id" />
                </el-select>
                <el-select v-model="filterVariable.status" placeholder="状态节点" size="large" @change="startFilter">
                    <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"
                />
                <el-button @click="resetFilter" type="success" class="hover:(bg-red-400 text-white)"><i class="fa fa-eraser pr-2"></i>重置筛选</el-button>
            </div>
        </el-col>
        <el-col :span="3" :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"><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
        fit
        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="expand" width="1">
            <template #default="{row: order_row}">
                <div class="w-full p-2 flex overflow-auto" :class="`h-${subTableHeight}px`">
                    <el-table
                        size="small"
                        fit
                        :data="order_row.status<=1 ? order_row.goods : order_row.offer"
                        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="center" header-align="center" v-if="order_row.status <= 1"/>
                        <el-table-column prop="brand_name" label="品牌" show-overflow-tooltip width="100" align="center" header-align="center" v-if="order_row.status == 3"/>
                        <el-table-column prop="code" label="件号" show-overflow-tooltip width="120" align="center" header-align="center"/>
                        <el-table-column prop="new_code" label="更新件号" show-overflow-tooltip width="120" align="center" header-align="center"/>
                        <el-table-column prop="name" label="品名" show-overflow-tooltip width="120" align="center" header-align="center"/>
                        <el-table-column prop="price" label="面价" show-overflow-tooltip width="100" align="right" header-align="center" v-if="order_row.status <= 1">
                            <template #default="{row}">
                                {{ (Math.round(row.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" v-if="order_row.status <= 1">
                            <template #default="{row}">
                                <el-tag v-if="row.goods?.length>0" effect="dark" type="primary">有货({{ row.goods?.length }})</el-tag>
                                <el-tag v-else effect="dark" type="danger">无货</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="market_price" label="面价" show-overflow-tooltip width="100" align="right" header-align="center" v-if="order_row.status == 3">
                            <template #default="{row}">
                                {{ (Math.round(row.market_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" v-if="order_row.status <= 1">
                            <template #default="{row}">
                                {{ (Math.round(row.sell_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" v-if="order_row.status == 3">
                            <template #default="{row}">
                                {{ (Math.round(row.sell_price * 100) / 100.00).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="sell_price2" label="加急服务" show-overflow-tooltip width="100" align="right" header-align="center" v-if="order_row.status == 3">
                            <template #default="{row}">
                                {{ (Math.round(row.sell_price2 * 100) / 100.00).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" label="数量" show-overflow-tooltip width="100" align="right" header-align="center"/>
                        <el-table-column prop="store" label="库存数" width="72" align="right" header-align="center" v-if="order_row.status == 3"/>
                        <el-table-column prop="note" label="客户备注" show-overflow-tooltip width="140" align="center" header-align="center" v-if="order_row.status <= 1"/>
                        <el-table-column prop="note" label="报价备注" show-overflow-tooltip width="140" align="center" header-align="center" v-if="order_row.status == 3"/>
                        <el-table-column label="供应商采购" width="120" align="center" header-align="center" v-if="order_row.status == 3">
                            <el-table-column prop="selected" label="供应商" show-overflow-tooltip width="120" align="center" header-align="center">
                                <template #default="{row}">
                                    {{ supplierName(row.selected) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="报价" width="100" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ parseFloat(row.from[0]) ? parseFloat(row.from[0]).toFixed(2) : 0.00 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="加急服务" width="100" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ row.from[3] && parseFloat(row.from[3]) ? parseFloat(row.from[3]).toFixed(2) : 0.00 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="可供数" width="60" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ row.from[1] }}
                                </template>
                            </el-table-column>
                            <el-table-column label="货源" show-overflow-tooltip width="100" align="center" header-align="center">
                                <template #default="{row}">
                                    {{ row.from[5] ? row.from[5] : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" show-overflow-tooltip width="100" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ row.from[2] }}
                                </template>
                            </el-table-column>
                        </el-table-column>
                    </el-table>
                </div>
            </template>
        </el-table-column>
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="create_time" label="建单时间" width="120px" header-align="center" align="center">
            <template #default="{row}">
                <el-text size="small">{{ dayjs(row.create_time).format('YY-MM-DD HH:mm') }}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="order_no" label="尾号" header-align="center" align="center" width="86px">
            <template #default="{row}">
                <el-button
                    text
                    @click="row.creator==userStore.userId?router.push({path:`/inquiry/edit/${row.id}`}):expandPanel(row)"
                >
                    <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-text size="small">{{ row.true_name ? row.true_name : row.user_name }}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="order_no" label="订单主题" header-align="center" width="200px" show-overflow-tooltip>
            <template #default="{row}">
                <el-text size="small" type="primary" tag="b">{{ row.subject }}</el-text>
            </template>
        </el-table-column>
        <el-table-column label="订单商品" header-align="center" width="90px" align="center">
            <template #default="{row}">
                <el-button v-if="row.goods.length > 0" type="info" size="small" circle @click="expandPanel(row)">{{ row.goods.length }}</el-button>
                <el-button v-else type="info" size="small" circle disabled>0</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.team.length > 1">
            <template #default="{row}">
                {{ userStore.teamInfo[row.creator]?.name || `ID-${row.creator}` }}
            </template>
        </el-table-column>
        <el-table-column label="工作节点" align="center" header-align="center" width="140px">
            <template #default="{row}">
                <el-tag effect="dark" :type="row.status==0 ? 'danger' : row.status==5 ? 'success' : 'primary'" size="large">
                    {{ row.status==0 ? (row.goods.length == 0 ? '添加商品' : (row.inquiry_status.total == 0 ? '制询价函' : (row.inquiry_status.total == row.inquiry_status.receive ? '等待报价' : '等待回函'))) : 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}">
                <el-tag size="large" effect="dark" :type="inquiryShow(row.inquiry_status.receive,row.inquiry_status.total)">
                    {{ `${row.inquiry_status.receive}/${row.inquiry_status.total}` }}
                </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-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'"
                            :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>
</template>

<script setup>
    import { ref,onMounted,computed } from 'vue'
    import { useRouter } from 'vue-router'
    import dayjs from 'dayjs'
    import { ElMessage } from 'element-plus'
    import { customerList,supplierList,sellerList,addLog,getLog }  from '@/api'
    import { inquiryList,inquiryStatus,createInquiry,addInquiryGoods,removeInquiry }  from '@/api/inquiry'
    import { status_name }  from '@/utils'
    import { storeToRefs } from 'pinia'
    import { useUserStore,useInquiryListStore } from '@/store'
    import { Share,Delete,InfoFilled } from '@element-plus/icons-vue'

    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()
        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}))
    })

    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 statusList = ref({})
    const customer_list = ref([])

    // const seller_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(320)
    const loading = ref(false)

    const orderStatus = computed(() => (status,isdel) => status_name(status,isdel))

    const get_order_list = async () => {
        loading.value = true
        // statusList.value = {}
        const { data:res } = await inquiryList(userStore.team,filterVariable.value,currentPage.value,pageSize.value)
        order_list.value = res.data
        total.value = res.total
        orderIds.value = []
        order_list.value.forEach(async (item) => {
            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 get_order_status = async () => {
    //     let ids = order_list.value.map(item => item.id)
    //     const {data:status} = await inquiryStatus(ids)
    //     statusList.value = status.data
    // }

    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)
        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 expandPanel = (row) => orderTableRef.value.toggleRowExpansion(row)
    const expandRowKeys = ref([])
    const isExpanded = computed(() => (id) => expandRowKeys.value.findIndex(it => it == id))
    const expandChange = async (row,rows) => expandRowKeys.value = rows.map(item => item.id)

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

    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 goodsSorted = computed(() => (goods) => {
        return _.orderBy(goods, ['code', 'brand'], ['asc', 'asc'])
    })

    const inquiryShow = computed(() => (val,total) => {
        if (val == 0 || val == '0') {
            return 'warning'
        } else if(total == val) {
            return 'success'
        } else {
            return 'primary'
        }
    })

    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.goods.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()
    }
</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>