<template>
    <div>
        <el-button size="large" type="primary" @click="makeInquiry" :icon="Message">
            添加询价单
        </el-button>
        <el-button size="large" type="success" @click="refresh" :icon="RefreshRight">
            刷新列表
        </el-button>
        <el-button size="large" type="danger" @click="() => {}" :icon="DArrowLeft">
            流程回退
        </el-button>
    </div>
    <div>
        <el-table
            ref="inquiryTableRef"
            fit
            :data="inquiryList"
            class="w-full mt-4"
            row-class-name="no-expand-icon"
            row-key="id"
            @row-click="expandPanel"
            @expand-change="expandChange"
        >
            <el-table-column type="expand" width="0">
                <template #default="{row}">
                    <div class="flex justify-center items-center mt-2">
                        <b>{{ row.supplier_name }}</b>
                    </div>
                    <div class="flex justify-center mt-2">
                        <el-table
                            size="small"
                            fit
                            :data="row.return_data"
                            class="text-xs mt-4 w-auto"
                            style="border: 1px solid black;"
                            :header-cell-style="{background: '#e0f2fe', color: 'black',borderColor: 'black'}"
                            :cell-style="{borderColor: 'black'}"
                            :max-height="480"
                            border
                        >
                            <el-table-column type="index" label="#" width="50" align="center" header-align="center"/>
                            <el-table-column prop="code" label="件号" show-overflow-tooltip width="120" align="center" header-align="center"/>
                            <el-table-column prop="new_code" label="更新件号" show-overflow-tooltip width="120" align="center" header-align="center"/>
                            <el-table-column prop="b_name" label="品牌" show-overflow-tooltip width="100" align="center" header-align="center"/>
                            <el-table-column prop="market" label="面价" show-overflow-tooltip width="100" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ (Math.round(row.market * 100) / 100.00).toFixed(2) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="报价" show-overflow-tooltip width="100" align="right" header-align="center">
                                <template #default="{row}">
                                    <div :class="row.market!=0 && row.price>(row.market*0.5) ? 'text-black' : 'text-red font-bold'">
                                        {{ (Math.round(row.price * 100) / 100.00).toFixed(2) }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="amount" label="数量" width="60" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ row.amount }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="nums" label="库存" width="60" align="right" header-align="center"/>
                            <el-table-column prop="weight" label="重量" width="80" align="right" header-align="center">
                                <template #default="{row}">
                                    {{ (Math.round(row.weight * 1000) / 1000.00).toFixed(3) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="period" label="货期" width="60" align="right" header-align="center"/>
                            <el-table-column prop="source" label="货源" show-overflow-tooltip  width="80" header-align="center"/>
                            <el-table-column prop="note" label="备注" show-overflow-tooltip width="80" header-align="center"/>
                        </el-table>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="order_no" label="订单号" width="140" header-align="center" align="center" show-overflow-tooltip>
                <template #default="{row}">
                    <el-text size="small">{{ row.order_no }}</el-text>
                </template>
            </el-table-column>
            <el-table-column prop="supplier_name" label="供应商" width="120" header-align="center" align="center" show-overflow-tooltip>
                <template #default="{row}">
                    <el-text size="small">{{ row.supplier_name }}</el-text>
                </template>
            </el-table-column>
            <!-- <el-table-column label="客户" width="200" show-overflow-tooltip header-align="center" align="center">
                <template #default="{row}">
                    <el-text size="small">{{ row.true_name ? row.true_name : row.user_name}}</el-text>
                </template>
            </el-table-column> -->
            <el-table-column label="询价品类" header-align="center" width="120px" align="center">
                <template #default="{row}">
                    <el-popover effect="light" trigger="hover" placement="left-start" width="auto">
                        <template #default>
                            <el-table
                                fit
                                :data="row.products"
                                :height="240"
                                style="width:400px"
                            >
                                <el-table-column prop="code" label="编码" :show-overflow-tooltip="true" width="100px"/>
                                <el-table-column prop="b_name" label="品牌" :show-overflow-tooltip="true" width="80px" />
                                <el-table-column prop="name" label="品名" :show-overflow-tooltip="true" width="80px" />
                                <el-table-column prop="amount" label="数量" width="60px" />
                                <el-table-column prop="note" label="备注" :show-overflow-tooltip="true"  width="80px"/>
                            </el-table>
                        </template>
                        <template #reference>
                            <el-tag type="danger">{{row.products.length}}</el-tag>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="询价状态" width="120px" head-align="center" align="center">
                <template #default="{row}">
                    <el-text v-if="row.status==0" style="font-weight: 600;">待询价</el-text>
                    <el-text v-else-if="row.status==1" type="primary" style="font-weight: 600;">已发函</el-text>
                    <el-text v-else-if="row.status==2" type="success" style="font-weight: 600;">已报价</el-text>
                    <el-text v-else type="warning" style="font-weight: 600;">未知状态</el-text>
                </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" header-align="center" align="center" width="160">
                <template #default="{row}">
                    <el-text size="small">{{ row.create_time }}</el-text>
                </template>
            </el-table-column>
            <el-table-column prop="return_time" label="回函时间" header-align="center" align="center" width="160">
                <template #default="{row}">
                    <el-text size="small">{{ row.return_time }}</el-text>
                </template>
            </el-table-column>
            <el-table-column prop="note" label="询单需求" header-align="center" width="200px" :show-overflow-tooltip="true" />
            <el-table-column prop="link" label="链接" header-align="center" align="center">
                <template #default="scope">
                    <el-button size="small" type="success" :icon="ChatDotRound" @click.stop="copyToClipboard(`${scope.row.order_no.substr(2,2)}年${scope.row.order_no.substr(4,2)}月${scope.row.order_no.substr(6,2)}日\n${scope.row.subject}\n${scope.row.link}`)" :disabled="scope.row.status<1">复制报文</el-button>
                    <el-button size="small" type="info" :icon="Link" @click.stop="copyToClipboard(scope.row.link)" :disabled="scope.row.status<1">复制链接</el-button>
                    <el-button size="small" type="primary" :icon="Download" @click.stop="downloadExcel(scope.row)">详表</el-button>
                    <el-button size="small" type="default" :icon="Download" @click.stop="simpleExcel(scope.row)">简表</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
                <template #default="scope">
                    <el-button
                        size="small"
                        type="danger"
                        :icon="Promotion"
                        :disabled="parseInt(scope.row.status)!=0"
                        @click.stop="handleSendLink(scope.$index,scope.row.link)"
                    />
                    <el-button
                        size="small"
                        type="primary"
                        :icon="Upload"
                        @click.stop="uploadExcel(scope.row)"
                        :disabled="parseInt(scope.row.status)>=2"
                    />
                    <el-button
                        size="small"
                        :type="expandRowKeys.findIndex(it => it == scope.row.id) > -1 ? 'default' : 'success'"
                        :icon="expandRowKeys.findIndex(it => it == scope.row.id) > -1 ? Hide : View"
                        :disabled="!scope.row.return_data || scope.row.return_data.length == 0"
                        @click.stop="expandPanel(scope.row)"
                    />
                    <el-button
                        size="small"
                        type="primary"
                        :icon="Download"
                        :disabled="!scope.row.return_data || scope.row.return_data.length == 0"
                        @click.stop="exportReturn(scope.row)"
                    />
                </template>
            </el-table-column>
        </el-table>
    </div>

    <el-dialog
        v-model="centerDialogVisible"
        title="创建询价函"
        width="30%"
        destroy-on-close
        center
    >
        <el-card class="box-card-edit">
            <el-row>
                <el-col :span="12">
                    <el-table
                        ref="goodsTableRef"
                        fit
                        :data="goodsList"
                        style="height: 300px;"
                        @selection-change="handleGoodsSelect"
                    >
                        <el-table-column fixed type="selection" width="50px" />
                        <el-table-column prop="code" label="产品编码" width="160px" align="center">
                            <template #default="scope">
                                <el-popover effect="light" trigger="hover" placement="left-start" width="auto">
                                    <template #default>
                                        <div>代码: {{ scope.row.code }}</div>
                                        <div>品名: {{ scope.row.name }}</div>
                                        <div>品牌: {{ scope.row.b_name }}</div>
                                        <div>数量: {{ scope.row.amount }}</div>
                                        <div>备注: {{ scope.row.note }}</div>
                                    </template>
                                    <template #reference>
                                        <el-text v-if="scope.row.new_code" type="primary">{{ scope.row.new_code }}</el-text>
                                        <el-text v-else>{{ scope.row.code }}</el-text>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column prop="b_name" label="品牌" width="120px" />
                    </el-table>
                </el-col>
                <el-col :span="12">
                    <el-form :inline="true">
                        <el-form-item label="需求备注">
                            <el-input v-model="new_inquiry.note" placeholder="需求备注" />
                        </el-form-item>
                        <el-form-item label="供应商：">
                            <el-autocomplete
                                v-model="supplier_id"
                                :fetch-suggestions="supplierSearch"
                                @select="handleSupplierSelect"
                                clearable
                                class="inline-input w-50"
                                placeholder="供应商关键字"
                            />
                        </el-form-item>
                    </el-form>
                    <el-table
                        fit
                        :data="new_inquiry.supplier_array"
                        :show-header="false"
                        empty-text="未选择供应商"
                        style="height: 198px;"
                    >
                        <el-table-column prop="name" label="供应商" width="240px" :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template #default="scope">
                                <el-button
                                    size="small"
                                    type="danger"
                                    :icon="CloseBold"
                                    @click="removeSupplier(scope.$index)"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
        </el-card>
        <template #footer>
        <span class="dialog-footer">
            <el-button type="success" @click="create_inquiry" :icon="Message" :disabled="goods_nums==0 || new_inquiry.supplier_array.length==0">
                确认添加
            </el-button>
        </span>
        </template>
    </el-dialog>

    <el-dialog
        v-model="contactDialog"
        title="选择供应商联系人"
        width="30%"
        destroy-on-close
        center
    >
        <el-card class="box-card-edit">
            <el-form label-width="100px">
                <el-form-item label="联系人">
                    <el-select v-model="contact_id" placeholder="选择供应商联系人" size="large">
                        <el-option
                            v-for="item in contact_list"
                            :key="item.id"
                            :label="item.username"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-card>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="selectContact" :icon="Avatar" :disabled="!contact_id">
                    确认选中
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
    import { ref,reactive,computed,onMounted,onUnmounted } from 'vue'
    const emit = defineEmits(['next-step','add-goods','make-order'])
    import { useUserStore } from '@/store'
    const user_store = useUserStore()
    import { brandList } from '@/api'
    import { supplierInquiry,inquiryGoodsList } from '@/api/inquiry'
    import { Message,DocumentCopy,View,RefreshRight,Download,Upload,CloseBold,Avatar,Promotion,ChatDotRound,Link,Hide,DArrowLeft } from '@element-plus/icons-vue'
    // import { $orderGoods,$orderInfo,$orderInquiry,$enquiryReturn,$createInquiry,$sendLink,$actionLog,brandList,supplierList,searchSupplier,getSupplierContact } from '@/api'
    // import { Message,DocumentCopy,View,RefreshRight,Download,Upload,CloseBold,Avatar,Promotion,ChatDotRound,Link,Hide } from '@element-plus/icons-vue'
    import XLSX from 'xlsx-js-style'
    import { ElMessage } from 'element-plus'
    import { md5 } from '@/utils'

    const props = defineProps({
        'orderId': {
            type: Number,
            default: 0
        },
        'orderStatus':{
            type: Number,
            default: 0
        }
    })

    const brand_list = ref([])
    const inquiryTableRef = ref()
    const goodsList = ref([])
    const inquiryList = ref([])
    const orderStatus = ref(0)
    const order_id = ref(0)

    onMounted(async () => {
        const { data:bres } = await brandList()
        brand_list.value = bres.data
        order_id.value = +props.orderId
        orderStatus.value = +props.orderStatus
        if(props.orderId) {
            order_id.value = props.orderId
            const {data:res} = await inquiryGoodsList(order_id.value)
            goodsList.value = res.data
            const {data:inquiry} = await supplierInquiry(order_id.value)
            inquiryList.value = inquiry.data
        }
    })

    const goodsTableRef = ref()
    const centerDialogVisible = ref(false)

    const goodsSelected = ref([])
    const goods_nums = computed(() => goodsSelected.length)
    const handleGoodsSelect = (val) => goodsSelected.value = val

    const expandPanel = (row) => {
        if(row.return_data && row.return_data.length > 0) {
            inquiryTableRef.value.toggleRowExpansion(row)
        }
    }

    const expandRowKeys = ref([])
    const isExpanded = computed(() => (id) => expandRowKeys.value.findIndex(it => it == id))
    const expandChange = async (row,rows) => {
        expandRowKeys.value = rows.map(item => item.id)
    }

    const supplier_id = ref('')
    const supplierSearch = async (qs, cb) => {
        if(qs && qs.length) {
            try {
                const {data:slist} = await searchSupplier(qs)
                var list = slist.data
                if (list.length == 0) {
                    list.push({
                        id: '-1',
                        value: '无匹配结果'
                    })
                    cb(list);
                } else {
                    list = list.map(item => {
                        return {
                            value: item.sname,
                            id: `${item.sid}`,
                            name: item.sname,
                            cname: item.company_name
                        }
                    })
                    cb(list);
                }
            } catch (error) {
                console.log(error)
            }
        } else {
            cb([{id: '-1',value: '无匹配结果'}])
        }
    }

    const handleSupplierSelect = async (item) => {
        supplier_id.value = ''
        if(item.id != -1 && !new_inquiry.supplier_array.map(m => m.id).includes(item.id)) {
            new_inquiry.supplier_array.push({id: item.id,name: item.name,cname: item.cname})
        }
    }

    let new_inquiry = reactive({
        supplier_array: [],
        note: ''
    })

    const makeInquiry = () => {
        new_inquiry = reactive({
            supplier_array: [],
            note: ''
        })
        supplier_id.value = ''
        centerDialogVisible.value = true
    }

    const removeSupplier = (index) => {
        new_inquiry.supplier_array.splice(index, 1)
    }

    const create_inquiry = async () => {
        centerDialogVisible.value = false
        const {data:order} = await $orderInfo(props.orderId)
        let data = {
            products: goodsSelected.value,
            suppliers: new_inquiry.supplier_array.map(item => item.id),
            order_no: order.data.order_no,
            user_id: order.data.user_id,
            note: new_inquiry.note
        }
        const {data:res} = await $createInquiry(props.orderId,data)
        if(res.data.length) {
            await $actionLog(props.orderId,user_store.name,'创建询价函',JSON.stringify(data))
            ElMessage({
                message: "询价函成功创建！",
                type: 'success',
            })
            const {data:inquiry} = await $orderInquiry(props.orderId)
            inquiryList.value = inquiry.data
        }
    }

    const copyToClipboard = (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');
        }
    }

    const contact_list = ref([])
    const contact_id = ref(0)
    const contactDialog = ref(false)
    const inquiryIndex = ref(0)
    const inquiryUrl = ref('')
    const handleSendLink = async (index,url) => {
        contact_id.value = 0
        let {data: res} = await getSupplierContact(inquiryList.value[index].supplier_id)
        if(res.data.contact.length > 1) {
            contact_list.value = res.data.contact
            contact_id.value = null
            inquiryIndex.value = index
            inquiryUrl.value = url
            contactDialog.value = true
        } else {
            if(res.data.contact.length == 1) {
                contact_id.value = res.data.contact[0].id
            }
            copyToClipboard(url)
            await $actionLog(props.orderId,user_store.name,'发送询价函','询价函id=' + inquiryList.value[index].id)
            if(inquiryList.value[index].status != 2) {
                await $sendLink(inquiryList.value[index].id,contact_id.value)
                inquiryList.value[index].status = 1
            }
            ElMessage({
                message: "询价函链接已生成！",
                type: 'success',
            })
        }
    }

    const selectContact = async () => {
        contactDialog.value = false
        copyToClipboard(inquiryUrl.value)
        await $actionLog(props.orderId,user_store.name,'发送询价函','询价函id=' + inquiryList.value[inquiryIndex.value].id)
        if(inquiryList.value[inquiryIndex.value].status != 2) {
            await $sendLink(inquiryList.value[inquiryIndex.value].id,contact_id.value)
            inquiryList.value[inquiryIndex.value].status = 1
        }
        ElMessage({
            message: "询价函链接已生成！",
            type: 'success',
        })
    }

    const refresh = async () => {
        const {data:inquiry} = await $orderInquiry(props.orderId)
        inquiryList.value = inquiry.data
    }

    const exportReturn = (row) => {
        const worksheet = XLSX.utils.aoa_to_sheet([[`${row.supplier_name}报价函`]], {origin: 'A1'})
        if(!worksheet["!rows"]) {
            worksheet["!rows"] = []
        }
        if(!worksheet["!cols"]) {
            worksheet["!cols"] = []
        }
        if(!worksheet["!rows"][0]) {
            worksheet["!rows"][0] = {hpx: 22}
        }
        worksheet["!cols"][3] = {wch: 20}
        worksheet['A1']['s'] = {font:{bold:true,sz:14},alignment:{horizontal:'center',vertical:'center',wrapText:true}}
        worksheet['!merges'] = [{s:{r:0,c:0},e:{r:0,c:9}}]
        worksheet['!merges'].push({s:{r:1,c:0},e:{r:1,c:3}})
        worksheet['!merges'].push({s:{r:1,c:5},e:{r:1,c:9}})
        worksheet['F2'] = {t:'d',v: row.return_time,z:'报价日期：YYYY年MM月DD日'}
        XLSX.utils.sheet_add_aoa(worksheet, [['品牌', '产品件号', '更新件号','品名','购买数','面价单价(元)', '执行单价(元)','紧急单价(元)','库存数','备注']], {origin: "A3"})
        let data = row.return_data
        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
        worksheet['J3']['s'] = title_style
        data.forEach((v,row) => {
            // 修改只显示new_code
            // XLSX.utils.sheet_add_aoa(worksheet, [[v.b_name,v.new_code ? v.new_code : v.code,v.new_code ?? '',v.name,v.amount,v.market,v.price,v.price2,v.nums,v.note]],{origin: `A${row + dataRow}`})
            XLSX.utils.sheet_add_aoa(worksheet, [[v.b_name,v.code,v.new_code ?? '',v.name,v.amount,v.market,v.price,v.price2,v.nums,v.note]],{origin: `A${row + dataRow}`})
            if(worksheet[`A${row + dataRow}`]) {
                worksheet[`A${row + dataRow}`]['s'] = style_center
            }
            if(worksheet[`E${row + dataRow}`]) {
                worksheet[`E${row + dataRow}`]['s'] = style_right
                worksheet[`E${row + dataRow}`]['s'] = '0'
            }
        })
        const workbook = XLSX.utils.book_new();
        if(!workbook.Custprops) {
            workbook.Custprops = {}
        }
        let token = `${row.supplier_id}ji${row.id}fu${row.user_id}jf${row.order_id}`
        workbook.Custprops["type"] = 'full';
        workbook.Custprops["inquery"] = row.id;
        workbook.Custprops["supplier"] = row.supplier_id;
        workbook.Custprops["link"] = row.link;
        workbook.Custprops["order_no"] = row.order_no;
        workbook.Custprops["token"] = md5(token);
        XLSX.utils.book_append_sheet(workbook, worksheet, `${row.supplier_name}报价函`);
        var time = new Date();
        var ext = `${row.supplier_name}-${time.getFullYear()}${time.getMonth() + 1}${time.getDate()}-${Math.round(Math.random() * 10000)}`;
        let fn = `${ext}.xlsx`
        XLSX.writeFile(workbook,fn,{compression: true});
        ElMessage({
            message: "询价回函已下载！",
            type: 'success',
        })
    }

    const downloadExcel = async (row_data) => {
        const {data: order} = await $orderInfo(row_data.order_id)
        let seller_name = order.data.seller_name
        const worksheet = XLSX.utils.aoa_to_sheet([[`${seller_name}询价单`]], {origin: 'A1'})
        if(!worksheet["!rows"]) {
            worksheet["!rows"] = []
        }
        if(!worksheet["!cols"]) {
            worksheet["!cols"] = []
        }
        if(!worksheet["!rows"][0]) {
            worksheet["!rows"][0] = {hpx: 22}
        }
        worksheet["!cols"][3] = {wch: 20}
        worksheet['A1']['s'] = {font:{bold:true,sz:14},alignment:{horizontal:'center',vertical:'center',wrapText:true}}
        worksheet['!merges'] = [{s:{r:0,c:0},e:{r:0,c:9}}]
        worksheet['!merges'].push({s:{r:1,c:0},e:{r:1,c:3}})
        worksheet['!merges'].push({s:{r:1,c:5},e:{r:1,c:9}})
        worksheet['A2'] = {t:'s',v:`报价单位：${row_data.supplier_name}`}
        worksheet['F2'] = {t:'d',v: row_data.create_time,z:'询价日期：YYYY年MM月DD日'}
        XLSX.utils.sheet_add_aoa(worksheet, [['品牌', '产品件号', '更新件号','品名','购买数','面价单价(元)', '执行单价(元)','紧急单价(元)','库存数','备注']], {origin: "A3"})
        let data = row_data.products
        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
        worksheet['J3']['s'] = title_style
        data.forEach((v,row) => {
            // 修改只显示new_code
            // XLSX.utils.sheet_add_aoa(worksheet, [[v.b_name,v.code,'',v.name,v.amount]],{origin: `A${row + dataRow}`})
            XLSX.utils.sheet_add_aoa(worksheet, [[v.b_name,v.new_code ? v.new_code : v.code,'',v.name,v.amount]],{origin: `A${row + dataRow}`})
            if(worksheet[`A${row + dataRow}`]) {
                worksheet[`A${row + dataRow}`]['s'] = style_center
            }
            if(worksheet[`E${row + dataRow}`]) {
                worksheet[`E${row + dataRow}`]['s'] = style_right
                worksheet[`E${row + dataRow}`]['s'] = '0'
            }
        })
        const workbook = XLSX.utils.book_new();
        if(!workbook.Custprops) {
            workbook.Custprops = {}
        }
        let token = `${row_data.supplier_id}ji${row_data.id}fu${row_data.user_id}jf${row_data.order_id}`
        workbook.Custprops["type"] = 'full';
        workbook.Custprops["inquery"] = row_data.id;
        workbook.Custprops["supplier"] = row_data.supplier_id;
        workbook.Custprops["link"] = row_data.link;
        workbook.Custprops["order_no"] = row_data.order_no;
        workbook.Custprops["token"] = md5(token);
        XLSX.utils.book_append_sheet(workbook, worksheet, `${seller_name}询价函`);
        var time = new Date();
        var ext = `${row_data.supplier_name}-${time.getFullYear()}${time.getMonth() + 1}${time.getDate()}-${Math.round(Math.random() * 10000)}`;
        let fn = `${ext}.xlsx`
        XLSX.writeFile(workbook,fn,{compression: true});
        await $actionLog(props.orderId,user_store.name,'下载询价函','询价函id=' + row_data.id)
        if(row_data.status != 2) {
            await $sendLink(row_data.id)
            row_data.status = 1
        }
        ElMessage({
            message: "询价函已下载！",
            type: 'success',
        })
    }

    //简易询价单
    const simpleExcel = async (row_data) => {
        const {data: order} = await $orderInfo(row_data.order_id)
        let seller_name = order.data.seller_name
        let data = row_data.products
        if(data.length) {
            let sheet_data = []
            data.forEach(item => sheet_data.push([item.code,item.amount]))
            const worksheet = XLSX.utils.aoa_to_sheet(sheet_data, {origin: 'A1'})
            if(!worksheet["!cols"]) {
                worksheet["!cols"] = []
            }
            worksheet["!cols"][0] = {wch: 20}
            worksheet["!cols"][1] = {wch: 20}
            const workbook = XLSX.utils.book_new();
            if(!workbook.Custprops) {
                workbook.Custprops = {}
            }
            let token = `${row_data.supplier_id}ji${row_data.id}fu${row_data.user_id}jf${row_data.order_id}`
            workbook.Custprops["type"] = 'simple';
            workbook.Custprops["inquery"] = row_data.id;
            workbook.Custprops["supplier"] = row_data.supplier_id;
            workbook.Custprops["link"] = row_data.link;
            workbook.Custprops["order_no"] = row_data.order_no;
            workbook.Custprops["token"] = md5(token);
            XLSX.utils.book_append_sheet(workbook, worksheet, `${seller_name}询价函`);
            var time = new Date();
            var ext = `${row_data.supplier_name}-${time.getFullYear()}${time.getMonth() + 1}${time.getDate()}-${Math.round(Math.random() * 10000)}`;
            let fn = `${ext}.xlsx`
            XLSX.writeFile(workbook,fn,{compression: true});
            await $actionLog(props.orderId,user_store.name,'生成并下载简易询价函','询价函id=' + row_data.id)
            if(row_data.status != 2) {
                await $sendLink(row_data.id)
                row_data.status = 1
            }
            ElMessage({
                message: "简易询价函已下载！",
                type: 'success',
            })
        } else {
            ElMessage({
                message: "没有需要询价的产品！",
                type: 'warning',
            })
        }
    }
    const MAP_KEYS = ['件号','品牌','数量','单价','面价','新号','备注','库存']
    const MAP_NAME = ['code','brand','amount','price','market','new_code','note','nums']
    // 简易询价回函处理，无表头，顺序件号、单价、数量、备注、品牌
    const uploadExcel = async (row_data) => {
        const [hFile] = await window.showOpenFilePicker({
            types: [{
                description: '数据表',
                accept: {
                    'application/vnd.ms-excel': ['.xlsx', '.xls', /*...*/ ]
                }
            }],
            excludeAcceptAllOption: true,
            multiple: false
        });
        const file = await (await hFile.getFile()).arrayBuffer();
        const wb = XLSX.read(file);
        let token = md5(`${row_data.supplier_id}ji${row_data.id}fu${row_data.user_id}jf${row_data.order_id}`)
        if(wb.Custprops["inquery"] == row_data.id && wb.Custprops["supplier"] == row_data.supplier_id && wb.Custprops["link"] == row_data.link && wb.Custprops["order_no"] == row_data.order_no && wb.Custprops["token"] == token) {
            const sheet = wb.SheetNames[0]
            if(wb.Custprops["type"] == 'simple') {
                const price_data = XLSX.utils.sheet_to_json(wb.Sheets[sheet], {header: "A"})
                let product = row_data.products
                price_data.forEach(item => {
                    let product_data = product.find(val => val.code == item['A'])
                    if(product_data) {
                        product_data.price = item['C'] ?? 0.0
                        product_data.note = item['D'] ?? ''
                        product_data.nums = item['E'] ?? 0
                    }
                })
                const {data:res} = await $enquiryReturn(row_data.id,product,token)
                if(res.data.result) {
                    row_data.status = 2
                    row_data.return_data = product
                    ElMessage({
                        message: "文件询价函报价成功！",
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: "文件询价函报价失败！请检查后重试!",
                        type: 'error',
                    })
                }
            } else if(wb.Custprops["type"] == 'full') {
                const price_data = XLSX.utils.sheet_to_json(wb.Sheets[sheet], {header: "A"})
                price_data.splice(0,3)
                let product = row_data.products
                price_data.forEach(item => {
                    let product_data = product.find(val => val.code == item['B'])
                    if(product_data) {
                        product_data.new_code = item['C'] ?? ''
                        product_data.market = item['F'] ?? 0.0
                        product_data.price = item['G'] ?? 0.0
                        product_data.price2 = item['H'] ?? 0.0
                        product_data.nums = item['I'] ?? 0
                        product_data.note = item['J'] ?? ''
                    }
                })
                const {data:res} = await $enquiryReturn(row_data.id,product,token)
                if(res.data.result) {
                    row_data.status = 2
                    row_data.return_data = product
                    ElMessage({
                        message: "文件询价函报价成功！",
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: "文件询价函报价失败！请检查后重试!",
                        type: 'error',
                    })
                }
            } else {
                ElMessage({
                    message: "不支持的询价函格式！",
                    type: 'warning',
                })
            }
        } else {
            ElMessage({
                message: "无效的询价函！",
                type: 'warning',
            })
        }
    }
</script>
<style scoped>
    :deep(.no-expand-icon .el-table__expand-icon) {
        display: none;
    }
</style>