<template>
    <el-tabs type="border-card">
        <el-tab-pane>
            <template #label>
                <span style="font-weight: 600;">客户报价单</span>
            </template>
            <div style="margin-top: 20px;text-align: left;" v-if="order_id || (order_offer.goods_array && order_offer.goods_array.length)">
                <p>客户名：{{order_offer.true_name ? order_offer.true_name : order_offer.username}}</p>
                <p>订单号：{{order_offer.order_no}}</p>
                <p>创建日期：{{order_offer.create_time}}</p>
                <p>报价日期：{{order_offer.update_time}}</p>
                <p>收货地址：{{order_offer.addr_id != 0 ? `${order_offer.area_name} ${order_offer.address} ${order_offer.accept_name }(${order_offer.mobile})` : '无'}}</p>
                <hr>
                <div style="margin-top: 20px;text-align: right;width:100%;">
                    <el-button type="warning" :icon="Document" @click="downloadOfferFile()">下载Excel报价单</el-button>
                    <el-button type="warning" :icon="Link" @click="copyToClipboard(order_offer.link)">发送在线报价单链接</el-button>
                </div>
                <el-table
                    :data="order_offer.goods_array"
                    fit
                    style="margin-top: 20px;"
                    :summary-method="getSummaries"
                    show-summary
                >
                    <el-table-column fixed label="#" width="50px" align="center" halign="center">
                        <template #default="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="产品编码"/>
                    <el-table-column prop="brand_name" label="品牌" />
                    <el-table-column prop="name" label="名称" width="160px" :show-overflow-tooltip="true"/>
                    <el-table-column prop="market_price" label="面价单价(元)" align="right">
                        <template #default="{row}">
                            ￥{{ parseFloat(row.market_price).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sell_price" label="销售单价(元)" align="right">
                        <template #default="{row}">
                            ￥{{ parseFloat(row.sell_price).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sell_price2" label="急件单价(元)" align="right">
                        <template #default="{row}">
                            ￥{{ row.sell_price2 ? parseFloat(row.sell_price2).toFixed(2) : 0.00 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="数量(件/套)" align="right"/>
                    <!-- <el-table-column prop="store" label="库存(件/套)" align="right"/> -->
                    <el-table-column label="销售总价(元)" align="right">
                        <template #default="{row}">
                            ￥{{ (parseFloat(row.sell_price)*parseInt(row.amount)).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="备注">
                        <template #default="{row}">
                            {{ row.note ?? '' }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-tab-pane>
        <el-tab-pane>
            <template #label>
                <span style="font-weight: 600;">预采购订单</span>
            </template>
            <div style="margin-top: 20px;" v-for="(item,i) in buy_list" :key="i">
                <h3>{{ supplierName(i) }}采购清单</h3>
                <el-table
                    :data="item"
                    fit
                    :summary-method="orderSummaries"
                    show-summary
                >
                    <el-table-column fixed label="#" width="50px" align="center" halign="center">
                        <template #default="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="产品编码"/>
                    <el-table-column prop="brand_name" label="商品品牌"/>
                    <el-table-column prop="name" label="商品名称" width="160px" :show-overflow-tooltip="true" />
                    <el-table-column prop="price" label="采购单价" align="right">
                        <template #default="{row}">
                            ￥{{ parseFloat(row.price).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="price2" label="急件单价" align="right">
                        <template #default="{row}">
                            ￥{{ row.price2 ? parseFloat(row.price2).toFixed(2) : '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="采购数量" align="right"/>
                    <el-table-column label="单项总价" align="right">
                        <template #default="{row}">
                            ￥{{ (parseFloat(row.price)*parseInt(row.amount)).toFixed(2) }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-tab-pane>
    </el-tabs>
</template>

<script setup>
    import { ref,computed,onMounted } from 'vue'
    import { useRoute,useRouter } from 'vue-router'
    import { $getOrderOffer,$actionLog,Suppliers,shopList } from '@/api'
    import { Document,Link } from '@element-plus/icons-vue'
    import XLSX from 'xlsx-js-style'
    import { useUserStore } from '@/store'
    import { ElMessage } from 'element-plus'

    const emit = defineEmits(['next-step','add-goods','make-order'])
    const user_store = useUserStore()
    const route = useRoute()
    const router = useRouter()
    const props = defineProps({
        'orderId': {
            type: Number,
            default: 0
        },
        'orderStatus': {
            type: String,
            default: 0
        }
    })
    const orderStatus = ref(parseInt(props.orderStatus))
    const order_id = ref(0)
    const order_offer = ref({})
    const buy_list = ref({})
    const supplier_list = ref([])
    const seller_list = ref([])
    const sellerInfo = ref([])

    onMounted(async ()=>{
        order_id.value = props.orderId
        const {data:offer} = await $getOrderOffer(order_id.value)
        order_offer.value = offer.data
        if(offer.data.goods_array) {
            offer.data.goods_array.forEach(item => {
                let {brand,brand_name,code,amount,name,selected} = item
                if(`${selected}`.startsWith('G')) {
                    let arr = selected.split('-')
                    if(arr[0] in buy_list.value) {
                        buy_list.value[arr[0]].push({id: arr[1],brand,brand_name,code,name,amount,price:item.from[0],price2:item.from[3] ?? 0.00,type:'seller'})
                    } else {
                        buy_list.value[arr[0]] = [{id: arr[1],brand,brand_name,code,name,amount,price:item.from[0],price2:item.from[3] ?? 0.00,type:'seller'}]
                    }
                } else if(selected != 0) {
                    if(selected in buy_list.value) {
                        buy_list.value[selected].push({id: 0,brand,brand_name,code,name,amount,price:item.from[0],price2:item.from[3] ?? 0.00,type:'supplier'})
                    } else {
                        buy_list.value[selected] = [{id: 0,brand,brand_name,code,name,amount,price:item.from[0],price2:item.from[3] ?? 0.00,type:'supplier'}]
                    }
                }
            })
        }
        const {data:supplier} = await Suppliers(offer.data.suppliers)
        supplier_list.value = supplier.data.map(item => ({id:item.sid,name:item.sname,mobile:item.mobile}))
        const {data:seller} = await shopList(offer.data.shops)
        seller_list.value = seller.data.map(item => ({id:`G${item.id}`,name:`*商城*${item.seller_name}`,mobile:item.mobile}))
        sellerInfo.value = seller.data
    })

    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 getSummaries = (param) => {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
            if (index === 1) {
                sums[index] = '合计金额'
                return
            }
            if (index === 8) {
                let price_sum = 0
                data.forEach(item => price_sum += parseFloat(item.amount) * parseFloat(item.sell_price))
                sums[index] = `￥${price_sum.toFixed(2)}`
                return
            }
        })
        return sums
    }

    const orderSummaries = (param) => {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
            if (index === 1) {
                sums[index] = '合计金额'
                return
            }
            if (index === 7) {
                let price_sum = 0
                data.forEach(item => price_sum += parseFloat(item.amount) * parseFloat(item.price))
                sums[index] = `￥${price_sum.toFixed(2)}`
                return
            }
        })
        return sums
    }

    const copyToClipboard = async (content) => {
        if (window.clipboardData) {
            window.clipboardData.setData('text', content);
        } else {
            (function (content) {
                document.oncopy = function (e) {
                    e.clipboardData.setData('text', content);
                    e.preventDefault();
                    document.oncopy = null;
                }
            })(content);
            document.execCommand('Copy');
        }
        let action = '发送报价单链接'
        await $actionLog(order_id.value,user_store.name,action,'')
        ElMessage({
            message: `成功${action}!`,
            type: 'success',
        })
    }

    const downloadOfferFile = async () => {
        var time = new Date();
        var ext = `${order_offer.value.username}-${time.getFullYear()}${time.getMonth() + 1}${time.getDate()}-${Math.round(Math.random() * 10000)}`;
        createExcel(`${ext}.xlsx`)
        let action = '导出报价单'
        await $actionLog(order_id.value,user_store.name,action,'')
        ElMessage({
            message: `成功${action}!`,
            type: 'success',
        })
    }

    const createExcel = (fn) => {
        const worksheet = XLSX.utils.aoa_to_sheet([[`${order_offer.value.seller_name}报价单`]], {origin: 'A1'})
        if(!worksheet["!rows"]) {
            worksheet["!rows"] = []
        }
        if(!worksheet["!rows"][0]) {
            worksheet["!rows"][0] = {hpx: 22}
        }
        if(!worksheet["!cols"]) {
            worksheet["!cols"] = []
        }
        worksheet["!cols"][2] = {wch: 20}
        worksheet['A1']['s'] = {font:{bold:true,sz:14},alignment:{horizontal:'center',wrapText:true}}
        worksheet['!merges'] = [{s:{r:0,c:0},e:{r:0,c:8}}]
        worksheet['!merges'].push({s:{r:1,c:0},e:{r:1,c:8}})
        worksheet['A2'] = {t:'d',v:order_offer.value.update_time}
        worksheet['A2'].z = '报价日期：YYYY年MM月DD日'
        XLSX.utils.sheet_add_aoa(worksheet, [['品牌', '编码', '品名','面价(元)', '售价(元)','急件单价(元)','数量','小计','备注']], {origin: "A3"})
        let data = order_offer.value.goods_array
        const dataRow = 4
        const align_center = {
            horizontal: 'center',
            vertical: 'center',
            wrapText: true
        }
        const align_right = {
            horizontal: 'right',
            vertical: 'center',
            wrapText: true
        }
        const title_style = {
            font: { bold: true },
            alignment: align_center
        };
        const style_center = {
            alignment: align_center
        }
        const style_right = {
            alignment: align_right
        }
        worksheet['A3'].s = title_style
        worksheet['B3'].s = title_style
        worksheet['C3'].s = title_style
        worksheet['D3'].s = title_style
        worksheet['E3'].s = title_style
        worksheet['F3'].s = title_style
        worksheet['G3'].s = title_style
        worksheet['H3'].s = title_style
        worksheet['I3'].s = title_style
        data.forEach((v,row) => {
                XLSX.utils.sheet_add_aoa(worksheet, [[v.brand_name,v.code,v.name,v.market_price, v.sell_price,v.sell_price2 ?? 0,v.amount,{t:'n',v:0,f:`E${row+dataRow}*G${row+dataRow}`},v.note??'']], {origin: `A${row + dataRow}`})
                worksheet[`A${row + dataRow}`].s = style_center
                worksheet[`D${row + dataRow}`].s = style_right
                worksheet[`E${row + dataRow}`].s = style_right
                worksheet[`F${row + dataRow}`].s = style_right
                worksheet[`G${row + dataRow}`].s = style_right
                worksheet[`D${row + dataRow}`].z = '0.00'
                worksheet[`E${row + dataRow}`].z = '0.00'
                worksheet[`F${row + dataRow}`].z = '0.00'
                worksheet[`G${row + dataRow}`].z = '0'
                worksheet[`H${row + dataRow}`].z = '0.00'
        })
        let row =  data.length + dataRow - 2
        XLSX.utils.sheet_add_aoa(worksheet, [['合计',{t:'n',v:0,f:`SUM(H${dataRow}:H${row+1})`,z:'￥0.00元'}]], {origin: -1})
        worksheet[XLSX.utils.encode_cell({r:row+1, c:0})].s = title_style
        worksheet['!merges'].push({s:{r:row+1,c:1},e:{r:row+1,c:7}})
        const workbook = XLSX.utils.book_new();
        if(!workbook.Custprops) {
            workbook.Custprops = {}
        }
        workbook.Custprops["link"] = order_offer.value.link;
        workbook.Custprops["order_no"] = order_offer.value.order_no;
        XLSX.utils.book_append_sheet(workbook, worksheet, `客户${order_offer.value.true_name ? order_offer.value.true_name : order_offer.value.username}报价单`);
        XLSX.writeFile(workbook,fn,{compression: true});
    }
</script>
