<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.offer_time}}。</el-text>
            </el-col>
            <el-col :span="8">
                <el-button v-if="offer.enquiry_return>0" color="#e85827" @click="initPreset" size="large" :icon="ShoppingCartFull" >批量预报价</el-button>
                <el-button v-if="offer.enquiry_return>0" color="#485827" @click="resetPrice" size="large" :icon="Money" >低价预选</el-button>
                <el-button :disabled="!hasChange" type="primary" size="large" :icon="Money" @click="createOrderOffer"><span v-if="offer.offer.length">修改</span><span v-else>新建</span>报价单</el-button>
            </el-col>
        </el-row>
        <el-table
            ref="orderResultTableRef"
            fit
            size="small"
            class="w-full 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
            :height="800"
            :data="product"
        >
            <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 />
            <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="100" header-align="center" align="center">
                <template #default="{row}">
                    <el-input-number v-model="row.amount" :min="0" size="small" controls-position="right" style="width:80px;"/>
                </template>
            </el-table-column>
            <el-table-column label="商家备注" header-align="center" width="180" align="center">
                <template #default="{row}">
                    <el-input v-model="row.note2" clearable size="small" type="textarea" autosize></el-input>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="cost_price" label="选中报价(元)" header-align="center" align="right" width="120px">
                <template #default="{row}">
                    <el-text>￥{{ parseFloat(row.cost_price).toFixed(2) }}</el-text>
                </template>
            </el-table-column> -->
            <el-table-column label="客户报价(元)" header-align="center" align="right" width="140">
                <template #default="scope">
                    <div @click="handlePriceChange(scope.row,scope.$index)" class="cursor-pointer">
                        <div class="flex-col font-bold">
                            <div>
                                <el-text type="primary" tag="b" size="small">销：￥{{parseFloat(scope.row.customer_price).toFixed(2)}}</el-text>
                            </div>
                            <div class="mt-[0px]">
                                <el-text class="mt-[5px]" type="danger" tag="b" size="small">进：￥{{ parseFloat(scope.row.cost_price).toFixed(2) }}</el-text>
                            </div>
                            <div class="mt-[0px]">
                                <el-text class="mt-[5px]" type="success" tag="b" size="small">加点：{{ Math.round(parseFloat(scope.row.customer_price) * 100 / parseFloat(scope.row.cost_price)) - 100 }}</el-text>
                            </div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="紧急报价(元)" header-align="center" align="right" width="120">
                <template #default="scope">
                    <el-button
                        text
                        @click="handlePriceChange(scope.row,scope.$index)"
                    >
                        <div class="flex-col font-bold" v-if="parseFloat(scope.row.cost_price2) > 0.0">
                            <div>
                                <el-text type="primary" tag="b" size="small">销：￥{{parseFloat(scope.row.customer_price2).toFixed(2)}}</el-text>
                            </div>
                            <div class="mt-[5px]">
                                <el-text class="mt-[5px]" type="danger" tag="b" size="small">进：￥{{ parseFloat(scope.row.cost_price2).toFixed(2) }}</el-text>
                            </div>
                        </div>
                        <!-- <div v-if="parseFloat(scope.row.cost_price2) > 0.0">
                            ￥{{parseFloat(scope.row.customer_price2).toFixed(2)}}/<el-text type="danger" tag="b">￥{{ parseFloat(scope.row.cost_price2).toFixed(2) }}</el-text>
                        </div> -->
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="供应商及商城报价" header-align="center">
                <template #header>
                    <div style="width: 100%;display: inline-grid;align-items: center;grid-template-columns: 50px repeat(8,1fr);">
                        <div class="text-center">选项</div>
                        <div class="text-center" style="border-right: 1px solid black;border-left: 1px solid black;">供应商</div>
                        <div class="text-center" style="border-right: 1px solid black;">面价(元)</div>
                        <div class="text-center" style="border-right: 1px solid black;">报价(元)</div>
                        <div class="text-center" style="border-right: 1px solid black;">急件价(元)</div>
                        <div class="text-center" style="border-right: 1px solid black;">库存</div>
                        <div class="text-center" style="border-right: 1px solid black;">货源</div>
                        <div class="text-center" style="border-right: 1px solid black;">货期</div>
                        <div class="text-center">备注</div>
                    </div>
                </template>
                <template #default="scope">
                    <el-table
                        :data="scope.row.enquiry2"
                        :show-header="false"
                        size="small"
                        class="w-auto text-xs"
                        empty-text="无供应商报价"
                        :cell-style="{borderColor: 'black'}"
                        border
                        style="margin:0;padding: 0;"
                    >
                        <el-table-column width="50" align="center">
                            <template #default="{row}">
                                <el-radio :label="row.id" v-model="scope.row.selected" @change="handleSupplierChange(scope.row,row)" :disabled="parseFloat(row.price)==0"><span></span></el-radio>
                            </template>
                        </el-table-column>
                        <el-table-column prop="id" label="供应商" header-align="center">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">{{ supplierName(row.id) }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="market" label="面价(元)" header-align="center" align="right">
                            <template #default="{row}">
                                <el-text v-if="row.market" :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">￥{{ parseFloat(row.market).toFixed(2) }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="报价(元)" header-align="center" align="right">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">￥{{ parseFloat(row.price).toFixed(2) }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="price2" label="急件价(元)" header-align="center" align="right">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">￥{{ parseFloat(row.price2).toFixed(2) }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="store" label="库存" header-align="center" align="right">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small" align="right">{{ row.store }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="source" label="货源" header-align="center">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">{{ row.source }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="store" label="货期" header-align="center" align="right">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">{{ row.period }}</el-text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="note" label="备注" header-align="center">
                            <template #default="{row}">
                                <el-text :tag="row.id == scope.row.selected ? 'b' : 'i'" size="small">{{ row.note }}</el-text>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-table-column>
        </el-table>
    </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 { useRouter } from 'vue-router'
    import { Money,Plus,Open,TurnOff,ShoppingCartFull,Setting,EditPen } from '@element-plus/icons-vue'
    import { ElMessage } from 'element-plus'
    import { md5 } from '@/utils'
    import { useUserStore } from '@/store'
    const user_store = useUserStore()

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

    const order_id = ref(0)
    const orderStatus = ref(parseInt(props.orderStatus))
    const offer = ref({})
    const product = ref([])
    const productHash = ref('')
    const hasEnquery = ref(false)
    const preset = ref({})
    const points = ref([])

    onMounted(async () => {
        order_id.value = props.orderId
        let {data: res} = await inqueryResult(order_id.value)
        if(res.data && res.data.product) {
            offer.value = res.data
            product.value = res.data.product
            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
            }
            product.value.forEach((item,idx) => {
                item.note2 = offer.value.offer[idx] ? offer.value.offer[idx].note : ''
                item.enquiry2 = []
                let ids = Object.keys(item.enquiry)
                let vals = Object.values(item.enquiry)
                for(let i=0;i<ids.length;i++) {
                    item.enquiry2.push({
                        id: ids[i],
                        price: parseFloat(vals[i][0]) ? Math.round(parseFloat(vals[i][0]) * 100) / 100 : 0.00,
                        price2: vals[i].length < 4 ? 0.0 : parseFloat(vals[i][3]) ? Math.round(parseFloat(vals[i][3]) * 100) / 100 : 0.00,
                        store: vals[i][1],
                        note: vals[i][2],
                        source: vals[i].length < 5 ? '' : vals[i][4]
                    })
                }
            })
            productHash.value = md5(JSON.stringify(product.value))
            for(var i=0;i<product.value.length;i++) {
                if(Object.keys(product.value[i].enquiry).length > 0) {
                    hasEnquery.value = true
                    break
                }
            }
        }
        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}))
    })

    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 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 handleSupplierChange = (row,select_item) => {
        row.cost_price = select_item.price
        row.cost_price2 = select_item.price2
        row.note2 = select_item.note
        let pt = points.value.find(p => p.id == row.selected)
        if(pt && pt.id) {
            row.customer_price = Math.ceil(select_item.price * (100 + pt.point) / 100)
            row.customer_price2 = Math.ceil(select_item.price2 * (100 + pt.point) / 100)
        } else {
            row.customer_price = Math.ceil(select_item.price)
            row.customer_price2 = Math.ceil(select_item.price2)
        }
    }

    const calcpriceDialogVisible = ref(false)
    const handlePriceChange = (row,index) => {
        if(!row.selected || row.selected == 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.enquiry[row.selected][0]
            row.cost_price2 = row.enquiry[row.selected].length < 4 ? 0.0 : row.enquiry[row.selected][3]
            calcPrice.value.cost = row.cost_price
            calcPrice.value.cost2 = row.cost_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.value[calcPrice.value.index].customer_price = calcPrice.value.customer
        product.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.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 createOrderOffer = async () => {
        let data = product.value.map(
            (item,idx) => (
                {
                    code:item.code,
                    name:item.name,
                    brand:item.brand,
                    brand_name: item.b_name,
                    market_price:item.price,
                    sell_price: item.customer_price,
                    sell_price2: item.customer_price2,
                    amount: item.amount,
                    selected: item.selected,
                    from: item.selected != 0 ? item.enquiry[item.selected] : [0,0,'',0],
                    store: Object.values(item.enquiry).reduce((prev,cur) => prev + parseInt(cur[1]),0),
                    note: item.note2 ?? ''
                }
            )
        )
        const {data:res} = await $makeOrderOffer(order_id.value,data)
        if(res.data) {
            let action = '创建用户报价单'
            if(offer.value.offer) {
                action = '修改用户报价单'
            }
            await addLog(order_id.value,user_store.name,action,JSON.stringify(data))
            ElMessage({
                message: `成功${action}!`,
                type: 'success',
            })
            reload()
        }
        productHash.value = md5(JSON.stringify(product.value))
        emit('next-step',order_id.value)
    }

    const reload = async () => {
        let {data: res} = await $orderEnqueryResult(order_id.value)
        if(res.data) {
            offer.value = res.data
        }
    }
</script>
