<template>
    <div v-if="hasEnquery">
        <el-row style="margin-top: 20px;">
            <el-col :span="16">
                <el-text v-if="offer.offer?.length" type="primary" tag="b">已完成报价单，报价日期：{{offer.o_time}}。</el-text>
            </el-col>
            <el-col :span="8">
                <span v-if="!editable">
                    <slot name="rollback"></slot>
                </span>
                <el-button v-if="editable" color="#e85827" @click="initPreset" size="large" :icon="ShoppingCartFull">批量预报价</el-button>
                <!-- <el-button v-if="editable" color="#485827" @click="() => {}" size="large" :icon="Money">低价预选</el-button> -->
                <el-button v-if="editable" :disabled="!hasChange" type="primary" size="large" :icon="Money" @click="createOffer">
                    <span v-if="offer.offer?.length">修改</span><span v-else>新建</span>报价单
                </el-button>
                <span class="ml-20px">
                    <slot name="nogo"></slot>
                </span>
            </el-col>
        </el-row>
        <div class="w-full flex justify-center items-center" ref="offerTableContainer">
            <el-table
                v-if="editable"
                fit
                size="small"
                class="w-auto text-xs mt-2"
                empty-text="无供应商报价"
                style="border: 1px solid black;"
                :header-cell-style="{background: '#e0f2fe',color: 'black',borderColor: 'black'}"
                :cell-style="{borderColor: 'black'}"
                border
                :max-height="tableHeight"
                :data="product_list"
                :span-method="spanMethod"
            >
                <el-table-column fixed label="#" width="50" align="center" header-align="center">
                    <template #default="{$index}">
                        <el-text type="info">{{ getLineIndex($index) }}</el-text>
                    </template>
                </el-table-column>
                <el-table-column prop="code" label="件号" width="120" header-align="center" show-overflow-tooltip>
                    <template #default="{row}">
                        <el-text tag="b" type="primary">{{row.code}}</el-text>
                    </template>
                </el-table-column>
                <el-table-column prop="new_code" label="更新件号" width="120" header-align="center" show-overflow-tooltip>
                    <template #default="{row}">
                        <el-text tag="b" type="warning">{{row.new_code}}</el-text>
                    </template>
                </el-table-column>
                <el-table-column prop="b_name" label="品牌" width="100" align="center" header-align="center"/>
                <el-table-column prop="price" label="面价" header-align="center" align="right" width="100" />
                <el-table-column prop="amount" label="需求数" width="80" header-align="center" align="right"/>
                <el-table-column label="已选数" width="80" header-align="center" align="right">
                    <template #default="{row,$index}">
                        <el-text type="info">{{ group_nums($index) }}</el-text>
                    </template>
                </el-table-column>
                <el-table-column label="报价" header-align="center">
                    <el-table-column label="售价(元)" header-align="center" align="right" width="100">
                        <template #default="{row,$index}">
                            <div class="flex-col cursor-pointer" v-if="row.customer_price > 0" @click="handlePriceChange(row,$index)">
                                <div><el-text type="info" tag="b" size="small">{{ row.customer_price.toFixed(2) }}</el-text></div>
                                <div><el-text type="warning" tag="b" size="small">
                                    加点：{{ row.cost_price != 0 ? Math.round(parseFloat(row.customer_price) * 100 / parseFloat(row.cost_price) - 100.0) : 0}}</el-text>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="总价(元)" header-align="center" align="right" width="100">
                        <template #default="{row}">
                            <div v-if="row.customer_price > 0">
                                <el-text type="primary" tag="b">{{ (row.customer_price * row.nums).toFixed(2) }}</el-text>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="加急售价(元)" header-align="center" align="right" width="100">
                        <template #default="{row,$index}">
                            <div class="flex-col" v-if="row.customer_price2 > 0" @click="handlePriceChange(row,$index,false)">
                                <div><el-text type="info" tag="b" size="small">{{ row.customer_price2.toFixed(2) }}</el-text></div>
                                <div class="mt-5px"><el-text type="warning" tag="b" size="small">
                                    加点：{{ row.cost_price2 != 0 ? Math.round(parseFloat(row.customer_price2) * 100 / parseFloat(row.cost_price2) - 100.0) : 0}}</el-text>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="customer_price2" label="加急总价(元)" header-align="center" align="right" width="100">
                        <template #default="{row}">
                            <div v-if="row.customer_price2 > 0">
                                <el-text type="primary" tag="b">{{ (row.customer_price2 * row.nums).toFixed(2) }}</el-text>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="nums" label="购买数" width="100" header-align="center">
                        <template #default="{row,$index}">
                            <el-input-number v-model="row.nums" :min="0" size="small" controls-position="right" style="width:90px;" @change="handleNumsChange(row)" :disabled="!row.g_id"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="note2" label="商家备注" header-align="center" width="180" show-overflow-tooltip>
                        <template #default="{row}">
                            <el-input v-model="row.note2" clearable size="small" type="text"/>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="供应商及商城询报价" header-align="center">
                    <el-table-column label="" width="50" align="center">
                        <template #default="{row}">
                            <i class="fa fa-check-circle text-stroke-indigo-700 text-lg" style="color: blue;" v-if="row.nums>0"></i>
                        </template>
                    </el-table-column>
                    <el-table-column prop="g_id" label="供应商" header-align="center" show-overflow-tooltip width="160" align="left">
                        <template #default="{row}">
                            <el-text tag="b" :type="row.nums > 0 ? 'primary':'info'">{{row.g_id ? supplierName(row.g_id) : ''}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column prop="g_price" label="报价" header-align="center" align="right" width="100"></el-table-column>
                    <el-table-column prop="g_price2" label="加急服务" header-align="center" align="right" width="100"></el-table-column>
                    <el-table-column prop="g_store" label="库存" header-align="center" align="right" width="80"></el-table-column>
                    <el-table-column prop="g_note" label="备注" header-align="center" align="left" width="180" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="g_source" label="来源" header-align="center" align="left" width="100"></el-table-column>
                </el-table-column>
            </el-table>

            <el-table
                v-else
                fit
                size="small"
                class="w-auto text-xs mt-2"
                style="border: 1px solid black;"
                :header-cell-style="{background: '#e0f2fe',color: 'black',borderColor: 'black'}"
                :cell-style="{borderColor: 'black'}"
                border
                :max-height="tableHeight"
                :data="offer_list"
                :span-method="spanMethod2"
            >
                <el-table-column fixed label="#" type="index" width="50" align="center" header-align="center"/>
                <el-table-column prop="code" label="件号" width="120" header-align="center" show-overflow-tooltip>
                    <template #default="{row}">
                        <el-text tag="b" type="primary">{{row.code}}</el-text>
                    </template>
                </el-table-column>
                <el-table-column prop="code" label="更新件号" width="120" header-align="center" show-overflow-tooltip>
                    <template #default="{row}">
                        <el-text tag="b" type="warning">{{row.new_code}}</el-text>
                    </template>
                </el-table-column>
                <el-table-column prop="b_name" label="品牌" width="120" align="center" header-align="center"/>
                <el-table-column prop="price" label="面价" header-align="center" align="right" width="100" />
                <el-table-column prop="amount" label="需求数" width="80" header-align="center" align="right"/>
                <el-table-column prop="note" label="客户备注" width="160" header-align="center" align="left"/>
                <el-table-column prop="o_nums" label="供应数" width="80" header-align="center" align="right"/>
                <el-table-column label="报价" header-align="center">
                    <el-table-column prop="cost_price" label="销售报价(元)" header-align="center" align="right" width="160">
                        <template #default="scope">
                            <div class="flex-col font-bold">
                                <div>
                                    <el-text type="primary" tag="b" size="small">销：￥{{parseFloat(scope.row.o_price).toFixed(2)}}</el-text>
                                </div>
                                <div class="mt-[0px]">
                                    <el-text class="mt-[5px]" type="danger" tag="b" size="small">进：￥{{ parseFloat(scope.row.o_cost).toFixed(2) }}</el-text>
                                </div>
                                <div class="mt-[0px]" v-if="scope.row.o_cost>0">
                                    <el-text class="mt-[5px]" type="success" tag="b" size="small">加点：{{ Math.round(parseFloat(scope.row.o_price) * 100 / parseFloat(scope.row.o_cost)) - 100 }}</el-text>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="customer_price" label="加急服务(元)" header-align="center" align="right" width="160">
                        <template #default="scope">
                            <div class="flex-col font-bold">
                                <div>
                                    <el-text type="primary" tag="b" size="small">销：￥{{parseFloat(scope.row.o_price2).toFixed(2)}}</el-text>
                                </div>
                                <div class="mt-[0px]">
                                    <el-text class="mt-[5px]" type="danger" tag="b" size="small">进：￥{{ parseFloat(scope.row.o_cost2).toFixed(2) }}</el-text>
                                </div>
                                <div class="mt-[0px]" v-if="scope.row.o_cost2>0">
                                    <el-text class="mt-[5px]" type="success" tag="b" size="small">加点：{{ Math.round(parseFloat(scope.row.o_price2) * 100 / parseFloat(scope.row.o_cost2)) - 100 }}</el-text>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="销售备注" header-align="center" show-overflow-tooltip width="180" align="left">
                        <template #default="{row}">
                            <el-text tag="b" type="info" size="small">{{row.o_note}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column prop="" label="供应商" header-align="center" show-overflow-tooltip width="160" align="left">
                        <template #default="{row}">
                            <el-text tag="b" type="primary">{{supplierName(row.o_id)}}</el-text>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <el-dialog
        v-model="presetDialogVisible"
        title="预报价参数"
        width="27%"
        destroy-on-close
        center
        :draggable="true"
    >
        <el-table :data="points">
            <el-table-column label="默认" prop="default" header-align="center" align="center" width="80">
                <template #default="{row}">
                    <el-radio :label="row.id" v-model="selected" size="large"><span></span></el-radio>
                </template>
            </el-table-column>
            <el-table-column label="供应商" prop="id" header-align="center">
                <template #default="{row}">
                    <el-text tag="b">{{ supplierName(row.id) }}</el-text>
                </template>
            </el-table-column>
            <el-table-column label="报价加点" prop="point" header-align="center" width="160">
                <template #default="{row}">
                    <el-input-number
                        v-model="row.point"
                        controls-position="right"
                        size="small"
                    >
                    </el-input-number>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="success" @click="presetPoint" :icon="Setting">预设报价参数</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog
        v-model="calcpriceDialogVisible"
        title="价格计算器"
        width="35%"
        destroy-on-close
        center
        :draggable="true"
    >
        <el-table :data="[calcPrice]">
            <el-table-column label="供应商价" prop="cost" align="center">
                <template #default="{row}">
                    <el-text type="primary">￥{{parseFloat(row.cost).toFixed(2)}}</el-text>
                </template>
            </el-table-column>
            <el-table-column label="定价策略" prop="type" align="center">
                <template #default="{row}">
                    <el-select v-model="row.type" placeholder="请选择定价策略">
                        <el-option label="手动价格(=)" value="fixed"></el-option>
                        <el-option label="阶梯加价(+)" value="add"></el-option>
                        <el-option label="固定加点(+%)" value="percent"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="价格参数" prop="point" align="center">
                <template #default="{row}">
                    <el-input v-model="row.point"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="客户报价" prop="customer" align="center">
                <template #default="{row}">
                    <el-text tag="b">￥{{ price_calculator }}</el-text>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="success" @click="setPrice()" :icon="EditPen">设定客户报价</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
    import { ref,onMounted,computed } from 'vue'
    import { addLog,shopList,Suppliers } from '@/api'
    import { makeOffer,inqueryResult } from '@/api/inquiry'
    import { Money,Plus,Open,TurnOff,ShoppingCartFull,Setting,EditPen,Select } from '@element-plus/icons-vue'
    import { ElMessage } from 'element-plus'
    import { md5 } from '@/utils'
    import { useRouter } from 'vue-router'
    import { useUserStore } from '@/store'
    const router = useRouter()
    const user_store = useUserStore()

    const props = defineProps({
        'orderId': {
            type: Number,
            default: 0
        },
        'orderStatus': {
            type: Number,
            default: 0
        }
    })
    const emit = defineEmits(['next-step','add-goods','make-order','status-change'])

    const order_id = ref(0)
    const orderStatus = ref(+props.orderStatus)
    const offer = ref({})
    const product = ref([])
    const productHash = ref('')
    const hasEnquery = ref(false)
    const preset = ref({})
    const points = ref([])
    const product_list = ref([])
    const offer_list = ref([])
    const span_list = ref([])
    const group_list = ref([])
    const span_list2 = ref([])
    const group_list2 = ref([])
    const editable = ref(false)
    const flat_array = (src)  => {
        let start = 0
        src.forEach(item => {
            if(item.enquiry && Object.keys(item.enquiry).length > 0) {
                let key_array = Object.keys(item.enquiry)//.filter(k => item.enquiry[k][0] > 0 || (item.enquiry[k].length > 3 && item.enquiry[k][3] >= 0))
                let rows = key_array.length
                if(rows > 1) {
                    span_list.value.push([start,rows])
                }
                group_list.value.push([start,start+rows-1])
                start += rows
                Object.entries(item.enquiry).forEach(([k,v]) => {
                    let i = v.length
                    product_list.value.push(Object.assign({},item,{
                        g_id: k,
                        g_price: i > 0 ? v[0] : 0.0,
                        g_price2: i > 3 ? v[3] : 0.0,
                        g_store: i > 1 ? v[1] : 0,
                        g_note: i > 2 ? v[2] : '',
                        g_source: i > 4 ? v[4] : '',
                        cost_price: i > 0 ? v[0] : 0.0,
                        cost_price2: i > 3 ? v[3] : 0.0,
                    }))
                })
            } else {
                product_list.value.push(Object.assign({},item,{
                    g_id: '',
                    g_price: 0.0,
                    g_price2: 0.0,
                    g_store: 0,
                    g_note: '',
                    g_source: '',
                    cost_price: 0.0,
                    cost_price2: 0.0,
                }))
                group_list.value.push([start,start])
                start += 1
            }
        })
    }

    const flatOfferList = (src)  => {
        let start = 0
        src.forEach(item => {
            if(item.offer?.length > 0) {
                let rows = item.offer.length
                if(rows > 1) {
                    span_list2.value.push([start,rows])
                }
                group_list2.value.push([start,start+rows-1])
                start += rows
                item.offer.forEach(v => {
                    offer_list.value.push(Object.assign({},item,{
                        o_id: v.id,
                        o_price: v.sell_price,
                        o_price2: v.sell_price2,
                        o_store: v.store,
                        o_nums: v.nums,
                        o_note: v.note,
                        o_source: v.source,
                        o_cost: v.cost,
                        o_cost2: v.cost2,
                    }))
                })
            } else {
                offer_list.value.push(Object.assign({},item,{
                    o_id: '',
                    o_price: 0,
                    o_price2: 0,
                    o_store: 0,
                    o_nums: 0,
                    o_note: '',
                    o_source: '',
                    o_cost: 0,
                    o_cost2: 0,
                }))
                group_list2.value.push([start,start])
                start += 1
            }
        })
    }

    const spanMethod = ({row, column, rowIndex, columnIndex}) => {
        if (columnIndex >= 0 && columnIndex <= 6) {
            let sp = span_list.value.find(([s,_]) => rowIndex === s)
            if(sp) {
                return {rowspan: sp[1], colspan: 1}
            }
            sp = span_list.value.find(([s,n]) => rowIndex > s && rowIndex < s + n)
            if(sp) {
                return {rowspan: 0, colspan: 0}
            }
        }
    }

    const spanMethod2 = ({row, column, rowIndex, columnIndex}) => {
        if (columnIndex >= 0 && columnIndex <= 5) {
            let sp = span_list2.value.find(([s,_]) => rowIndex === s)
            if(sp) {
                return {rowspan: sp[1], colspan: 1}
            }
            sp = span_list2.value.find(([s,n]) => rowIndex > s && rowIndex < s + n)
            if(sp) {
                return {rowspan: 0, colspan: 0}
            }
        }
    }

    const getLineIndex = (idx) => {
        let i = group_list.value.findIndex(([s,e]) => idx >=s && idx <= e)
        return i + 1
    }

    const group_nums = (idx) => {
        let g = group_list.value.find(([s,e]) => idx >=s && idx <= e)
        if(g) {
            return product_list.value.filter((_,index) => index >= g[0] && index <= g[1]).map(item => item.nums).reduce((prev,cur) => prev + cur,0)
        }
        return 0
    }

    const handleNumsChange = (row) => {
        if(row.nums <= 0) {
            row.cost_price = 0.0
            row.cost_price2 = 0.0
            row.customer_price = 0.0
            row.customer_price2 = 0.0
        } else {
            let p = points.value.find(item => item.id == supplyIndex(row.g_id))
            let pt = p ? p.point : 0
            let cost = row.g_price
            let cost2 = row.g_price2
            row.cost_price = cost
            row.cost_price2 = cost2
            row.customer_price = Math.ceil(cost * (100 + pt) / 100.00)
            row.customer_price2 = Math.ceil(cost2 * (100 + pt) / 100.00)
        }
    }

    const tableHeight = ref(0)
    const offerTableContainer = ref(null)
    
    const load = async () => {
        let { data:res } = await inqueryResult(order_id.value)
        if(res.data && res.data.products) {
            if(res.data.status >= 3) {
                editable.value = false
            } else {
                editable.value = true
            }
            offer.value = res.data
            product.value = res.data.products
            points.value = []
            offer.value.supplier_list.forEach(item => points.value.push({id: item,point:5,default: false}))
            if(points.value.length>0) {
                points.value[0].default = true
            }
            offer.value.shop_list.forEach(item => points.value.push({id: `G${item}`,point:3,default: false}))
            product.value.forEach((item) => {
                item.offer = []
                if(item.enquiry && Object.keys(item.enquiry).length) {
                    hasEnquery.value = true
                }
            })
            productHash.value = md5(JSON.stringify(product_list.value))
            const {data:supplier} = await Suppliers(offer.value.supplier_list)
            supplier_list.value = supplier.data.map(item => ({id:item.sid,name:item.sname,mobile:item.mobile}))
            const {data:seller} = await shopList(offer.value.shop_list)
            seller_list.value = seller.data.map(item => ({id:`G${item.id}`,name:`*商城*${item.seller_name}`,mobile:item.mobile}))
        }
        flat_array(product.value)
        flatOfferList(offer.value.offer)
    }

    onMounted(async () => {
        order_id.value = props.orderId
        await load()
        if(offerTableContainer.value) {
            const rect = offerTableContainer.value.getBoundingClientRect();
            tableHeight.value = window.innerHeight - rect.top - 20;
        } else {
            tableHeight.value = window.innerHeight - 180
        }
    })

    // const resetPrice = () => {
    //     product.value.forEach(item => {
    //         let price_arr = []
    //         item.enquiry2.forEach(m => {
    //             if(!`${m.id}`.startsWith('G') && m.price > 0) {
    //                 price_arr.push(m.price)
    //             }
    //         })
    //         let select_item = item.enquiry2.find((m) => {
    //             if(!`${m.id}`.startsWith('G') && m.price == Math.min(...price_arr)) {
    //                 return true
    //             }
    //         })
    //         if(select_item && select_item.id) {
    //             item.selected = select_item.id
    //             item.cost_price = select_item.price
    //             item.cost_price2 = select_item.price2
    //             item.note2 = select_item.note
    //             let pt = points.value.find(p => p.id == item.selected)
    //             if(pt && pt.id) {
    //                 item.customer_price = Math.ceil(select_item.price * (100 + pt.point) / 100)
    //                 item.customer_price2 = Math.ceil(select_item.price2 * (100 + pt.point) / 100)
    //             } else {
    //                 item.customer_price = Math.ceil(select_item.price)
    //                 item.customer_price2 = Math.ceil(select_item.price2)
    //             }
    //         }
    //     })
    // }

    const supplier_list = ref([])
    const seller_list = ref([])
    const supplyIndex = (id) => `${id}`.startsWith('G') ? `${id}`.split('-')[0] : id
    const supplierName = computed(() => (id) => {
        if(`${id}`.startsWith('G')) {
            let ids = `${id}`.split('-')
            let idx = seller_list.value.findIndex(item => item.id == ids[0])
            if(idx != -1) {
                return seller_list.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 enquiryData = computed(() => (obj) => {
        let ids = Object.keys(obj)
        let newData = []
        for(let i=0;i<ids.length;i++) {
            newData.push({
                id:ids[i],
                price:obj[ids[i]][0],
                store:obj[ids[i]][1],
                note:obj[ids[i]][2],
            })
        }
        return newData
    })

    const hasChange = computed(() => productHash.value != md5(JSON.stringify(product.value)) )

    const calcpriceDialogVisible = ref(false)
    const handlePriceChange = (row,index,what) => {
        if(row.nums <= 0) {
            row.cost_price = 0.00
            row.cost_price2 = 0.00
            row.customer_price = 0.00
            row.customer_price2 = 0.00
        } else {
            calcpriceDialogVisible.value = true
            row.cost_price = row.g_price
            row.cost_price2 = row.g_price2
            calcPrice.value.cost = row.cost_price
            calcPrice.value.cost2 = row.cost_price2
            calcPrice.value.customer = row.customer_price
            calcPrice.value.customer2 = row.customer_price2
            calcPrice.value.index = index
        }
    }

    const calcPrice = ref({
        cost: 0.0,
        cost2: 0.0,
        type: 'percent',
        point: 0.0,
        customer: 0.0,
        customer2: 0.0,
        index: 0
    })

    const price_calculator = computed(() => {
        calcPrice.value.customer = 0.0
        calcPrice.value.customer2 = 0.0
        if(calcPrice.value.type  == 'fixed') {
            calcPrice.value.customer = Math.ceil(parseFloat(calcPrice.value.point))
            calcPrice.value.customer2 = Math.ceil(parseFloat(calcPrice.value.point))
        } else if(calcPrice.value.type  == 'add') {
            calcPrice.value.customer = Math.ceil(parseFloat(calcPrice.value.point) + parseFloat(calcPrice.value.cost))
            calcPrice.value.customer2 = Math.ceil(parseFloat(calcPrice.value.point) + parseFloat(calcPrice.value.cost2))
        } else if(calcPrice.value.type  == 'percent') {
            calcPrice.value.customer = Math.ceil((1.0 + parseFloat(calcPrice.value.point) / 100.00) * parseFloat(calcPrice.value.cost))
            calcPrice.value.customer2 = Math.ceil((1.0 + parseFloat(calcPrice.value.point) / 100.00) * parseFloat(calcPrice.value.cost2))
        }
        return calcPrice.value.customer
    })

    const setPrice = () => {
        product_list.value[calcPrice.value.index].customer_price = calcPrice.value.customer
        product_list.value[calcPrice.value.index].customer_price2 = calcPrice.value.customer2
        calcpriceDialogVisible.value = false
    }

    const presetDialogVisible = ref(false)
    const selected = ref(0)
    const initPreset = () => {
        selected.value = points.value[0].id
        presetDialogVisible.value = true
    }

    const presetPoint = () => {
        preset.value = {}
        points.value.forEach(item => {
            preset.value[`${item.id}`] = parseInt(item.point)
            if(item.default) {
                preset.value.default = item.id
            }
        })
        preset.value.default = selected.value

        product_list.value.forEach(item => {
            if(preset.value.default == item.g_id) {
                item.selected = [preset.value.default]
                item.note2 = item.g_note
                let cost = item.g_price
                let cost2 = item.g_price2
                item.cost_price = cost
                item.cost_price2 = cost2
                item.customer_price = Math.ceil(cost * (100 + preset.value[`${item.selected}`]) / 100.00)
                item.customer_price2 = Math.ceil(cost2 * (100 + preset.value[`${item.selected}`]) / 100.00)
                item.nums = item.amount
            } else {
                item.selected = []
                item.note2 = ''
                item.cost_price = 0.00
                item.cost_price2 = 0.00
                item.customer_price = 0.00
                item.customer_price2 = 0.00
                item.nums = 0
            }
        })
        // product.value.forEach(item => {
        //     if(item.enquiry[preset.value.default]) {
        //         item.selected = preset.value.default
        //         item.note2 = item.enquiry[item.selected][2]
        //         let cost = item.enquiry[item.selected][0]
        //         let cost2 = item.enquiry[item.selected].length < 4 ? 0.0 : item.enquiry[item.selected][3]
        //         item.cost_price = cost
        //         item.cost_price2 = cost2
        //         item.customer_price = Math.ceil(cost * (100 + preset.value[`${item.selected}`]) / 100.00)
        //         item.customer_price2 = Math.ceil(cost2 * (100 + preset.value[`${item.selected}`]) / 100.00)
        //     } else {
        //         item.selected = 0
        //         item.note2 = ''
        //         item.cost_price = 0.00
        //         item.cost_price2 = 0.00
        //         item.customer_price = 0.00
        //         item.customer_price2 = 0.00
        //     }
        // })
        presetDialogVisible.value = false
    }

    const createOffer = async () => {
        product.value.forEach(item => {
            let offer = product_list.value.filter(p => p.id == item.id && p.nums > 0).map(p => ({ //  && (p.g_price > 0 || p.g_price2 > 0)
                id: p.g_id,
                cost: p.g_price,
                sell_price: p.customer_price,
                cost2: p.g_price2,
                sell_price2: p.customer_price2,
                nums: p.nums,
                note: p.note2,
                store: p.g_store,
                source: p.g_source
            }))
            item.offer = offer
        })
        const { data:res } = await makeOffer(order_id.value,product.value)
        if(res.data) {
            let action = '创建用户报价单'
            if(offer.value.offer) {
                action = '修改用户报价单'
            }
            await addLog(order_id.value,user_store.logName,action,JSON.stringify(product.value))
            ElMessage({
                message: `成功${action}!`,
                type: 'success',
            })
            editable.value = false
            offer.value.offer = product.value
            offer.value.status = 3
            emit('status-change',order_id.value,'make-offer')
            productHash.value = md5(JSON.stringify(product_list.value))
        }
    }
</script>
