<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.user_reply && order_offer.user_reply.length)">
                <p>客户名：{{order_offer.username}}</p>
                <p>订单号：{{order_offer.order_no}}</p>
                <p>创建日期：{{order_offer.create_time}}</p>
                <p>客户回复：{{order_offer.finish_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="primary" :icon="Document" @click="downloadOfferFile()">下载客户订单</el-button>
                </div>
                <el-table
                    :data="offer_list"
                    fit
                    :summary-method="getSummaries"
                    :span-method="spanMethod"
                    show-summary
                    class="mt-4 text-xs w-auto"
                    :header-cell-style="{background: '#e0f2fe', color: 'black',borderColor: 'black'}"
                    :cell-style="{borderColor: 'black'}"
                    size="small"
                    border
                >
                    <el-table-column fixed label="#" width="50" align="center" halign="center">
                        <template #default="{$index}">
                            <el-text type="info">{{ getLineIndex($index) }}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="件号" width="100" />
                    <el-table-column prop="new_code" label="更新件号" width="100"></el-table-column>
                    <el-table-column prop="b_name" label="品牌" width="100" />
                    <el-table-column prop="name" label="名称" width="160" :show-overflow-tooltip="true"/>
                    <el-table-column prop="price" label="面价单价(元)" align="right" width="100">
                        <template #default="{row}">
                            ￥{{ parseFloat(row.price).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="o_price" label="销售单价(元)" align="right" width="100">
                        <template #default="{row}">
                            ￥{{ parseFloat(row.o_price).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="o_price2" label="加急服务(元)" align="right" width="100">
                        <template #default="{row}">
                            ￥{{ row.o_price2 ? parseFloat(row.o_price2).toFixed(2) : 0.00 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="o_nums" label="数量" align="right" width="70"/>
                    <el-table-column label="销售总价(元)" align="right" width="100">
                        <template #default="{row}">
                            ￥{{ (parseFloat(row.o_price)*parseInt(row.o_nums)).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" width="180" show-overflow-tooltip>
                        <template #default="{row}">
                            {{ row.o_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;text-align: right;width:100%;">
                <el-button type="success" @click="downloadOrderFile()">下载采购订单</el-button>
            </div>
            <div class="mt-4 text-left" v-for="(item,i) in buy_list" :key="i">
                <h3>{{ supplierName(i) }}采购清单</h3>
                <el-table
                    :data="item"
                    fit
                    :summary-method="orderSummaries"
                    show-summary
                    class="mt-4 text-xs w-auto"
                    :header-cell-style="{background: '#e0f2fe', color: 'black',borderColor: 'black'}"
                    :cell-style="{borderColor: 'black'}"
                    size="small"
                    border
                >
                    <el-table-column fixed label="#" width="50" align="center" halign="center">
                        <template #default="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="产品编码" width="100"/>
                    <el-table-column prop="b_name" label="商品品牌" width="100"/>
                    <el-table-column prop="name" label="商品名称" width="160" show-overflow-tooltip />
                    <el-table-column prop="price" label="采购单价" align="right" width="100">
                        <template #default="{row}">
                            ￥{{ parseFloat(row.price).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="price2" label="急件单价" align="right" width="100">
                        <template #default="{row}">
                            ￥{{ row.price2 ? parseFloat(row.price2).toFixed(2) : '0.00' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="采购数量" align="right" width="100"/>
                    <el-table-column label="单项总价" align="right" width="120">
                        <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 { addLog,Suppliers,shopList } from '@/api'
    import { getUserOrder } from '@/api/inquiry'
    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(props.orderId)
    const order_offer = ref({})
    const buy_list = ref({})
    const supplier_list = ref([])
    const seller_list = ref([])
    const sellerInfo = ref([])
    const offer_list = ref([])
    const span_list = ref([])
    const group_list = ref([])

    const flatOfferList = (src)  => {
        let start = 0
        src.forEach(item => {
            if(item.offer?.length > 0) {
                let rows = item.offer.length
                if(rows > 1) {
                    span_list.value.push([start,rows])
                }
                group_list.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_list.value.push([start,start])
                start += 1
            }
        })
    }

    const getLineIndex = (idx) => {
        let i = group_list.value.findIndex(([s,e]) => idx >=s && idx <= e)
        return i + 1
    }
    const spanMethod = ({row, column, rowIndex, columnIndex}) => {
        if (columnIndex >= 0 && columnIndex <= 5) {
            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}
            }
        }
    }

    onMounted(async () => {
        const {data:offer} = await getUserOrder(order_id.value)
        order_offer.value = offer.data
        if(offer.data.user_reply) {
            flatOfferList(offer.data.user_reply)
            for(let item of offer_list.value) {
                let { id,brand,b_name,code,name } = item
                for(let v of item.offer) {
                    if(`${v.id}`.startsWith('G')) {
                        let arr = v.id.split('-')
                        let g_item = {
                            id: arr[1],
                            brand,
                            b_name,
                            code,
                            name,
                            amount:v.nums,
                            price:v.sell_price,
                            price2:v.sell_price2,
                            quality: 0,
                            source: 0,
                            type:'seller'
                        }
                        const { data:goods } = await goodsInfo(arr[1])
                        if(goods.data.id) {
                            g_item.name = goods.data.name
                            g_item.brand = goods.data.brand_id
                            g_item.b_name = goods.data.b_name
                            g_item.quality = goods.data.new_quality
                            g_item.source = goods.data.new_source
                        }
                        if(arr[0] in buy_list.value) {
                            buy_list.value[arr[0]].push(g_item)
                        } else {
                            buy_list.value[arr[0]] = [g_item]
                        }
                    } else if(v.id != '') {
                        if(v.id in buy_list.value) {
                            buy_list.value[v.id].push({id,brand,b_name,code,name,amount:v.nums,price:v.sell_price,price2:v.sell_price2,source:0,quality:0,type:'supplier'})
                        } else {
                            buy_list.value[v.id] = [{id,brand,b_name,code,name,amount:v.nums,price:v.sell_price,price2:v.sell_price2,source:0,quality:0,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 sellerName = (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 === 7) {
                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 === 6) {
                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 downloadOrderFile = () => {
        var time = new Date();
        var ext = `采购订单-${time.getFullYear()}${time.getMonth() + 1}${time.getDate()}-${Math.round(Math.random() * 10000)}`;
        createOrderExcel(`${ext}.xlsx`)
        ElMessage({
            message: '成功下载采购订单!',
            type: 'success',
        })
    }

    const createOrderExcel = (fn) => {
        const workbook = XLSX.utils.book_new();
        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
        }
        const dataRow = 4
        for(let seller in buy_list.value) {
            let worksheet = XLSX.utils.aoa_to_sheet([[`${sellerName(seller)}采购清单`]], {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:5}}]
            worksheet['!merges'].push({s:{r:1,c:0},e:{r:1,c:5}})
            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 = buy_list.value[seller]
            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
            data.forEach((v,row) => {
                XLSX.utils.sheet_add_aoa(worksheet, [[v.brand_name,v.code,v.name,v.price, v.amount,{t:'n',v:0,f:`D${row+dataRow}*E${row+dataRow}`}]], {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[`D${row + dataRow}`].z = '0.00'
                worksheet[`E${row + dataRow}`].z = '0'
                worksheet[`F${row + dataRow}`].z = '0.00'
            })
            let row =  data.length + dataRow - 2
            XLSX.utils.sheet_add_aoa(worksheet, [['合计',{t:'n',v:0,f:`SUM(F${dataRow}:F${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:5}})
            XLSX.utils.book_append_sheet(workbook, worksheet);
        }
        XLSX.writeFile(workbook,fn,{compression: true});
    }

    const downloadOfferFile = () => {
        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`)
        ElMessage({
            message: '成功下载客户订单!',
            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:7}}]
        worksheet['!merges'].push({s:{r:1,c:0},e:{r:1,c:7}})
        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
        data.forEach((v,row) => {
                XLSX.utils.sheet_add_aoa(worksheet, [[v.brand_name,v.code,v.name,v.market_price, v.sell_price,v.amount,{t:'n',v:0,f:`E${row+dataRow}*F${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'
                worksheet[`G${row + dataRow}`].z = '0.00'
        })
        let row =  data.length + dataRow - 2
        XLSX.utils.sheet_add_aoa(worksheet, [['合计',{t:'n',v:0,f:`SUM(G${dataRow}:G${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.username}订单`);
        XLSX.writeFile(workbook,fn,{compression: true});
    }
</script>
