<template>
    <el-card>
        <div class="flex items-center justify-between m-4">
            <div class="flex flex-col">
                <div style="color: gray">姓名：</div>
                <div style="color: black">{{ formData.other_data?.nickname }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">手机：</div>
                <div style="color: black">{{ formData.other_data?.phone }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">送货地址：</div>
                <div style="color: black">{{ formData.other_data?.address }}</div>
            </div>
        </div>
        <div class="flex items-center justify-between m-4">
            <div class="flex flex-col">
                <div style="color: gray">单号：</div>
                <div style="color: black">{{ formData.order_id }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">支付单号：</div>
                <div style="color: black">{{ formData.order_sn }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">门店：</div>
                <div style="color: black">{{ formData.system_store }}</div>
            </div>
        </div>
        <div class="flex items-center justify-between m-4">
            <div class="flex flex-col">
                <div style="color: gray">到货时间：</div>
                <div style="color: black">{{ formData.other_data?.arrival_time }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">桌数：</div>
                <div style="color: black">{{ formData.other_data?.tables }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">办事天数：</div>
                <div style="color: black">{{ formData.other_data?.days }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">厨师：</div>
                <div style="color: black">{{ formData.other_data?.chef }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">电话：</div>
                <div style="color: black">{{ formData.other_data?.chef_phone }}</div>
            </div>
        </div>

        <div class="flex items-center justify-between m-4">
            <div class="flex flex-col">
                <div style="color: gray">采购事由：</div>
                <div style="color: black">{{ formData.other_data?.purpose }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">备注：</div>
                <div style="color: black">{{ formData.mark }}</div>
            </div>
        </div>
        <div class="flex items-center justify-between m-4">
            <div class="flex flex-col">
                <div style="color: gray">总价</div>
                <div style="color: black">￥{{ formData.total_price }}</div>
            </div>
            <div class="flex flex-col flex-2">
                <div style="color: gray">时间</div>
                <div style="color: black">{{ formData.create_time }}</div>
            </div>
            <!-- <el-button @click="xlsx(formData.id, 1)"> 打印订单 </el-button> -->
            <el-button @click="xlsx2(formData.id)"> 打印商品标签 </el-button>
            <el-button @click="generateOrderClick"> 生成商品订单 </el-button>
            <el-button @click="demos"> demo </el-button>
        </div>
        <el-button type="primary" @click="dialogShop = true"> 追加 </el-button>

        <el-tabs
            v-model="activeName"
            class="demo-tabs mt-3"
            type="border-card"
            @tab-change="tabChange"
        >
            <el-tab-pane label="明细" name="second">
                <orderCartInfo ref="orderCartInfoRef" :id="formData.id" />
            </el-tab-pane>
            <el-tab-pane label="采购" name="offer">
                <goodsOffer ref="goodsOfferRef" :order_id="formData.id" />
            </el-tab-pane>
            <el-tab-pane label="入库" name="warehousing">
                <warehousing ref="warehousingRef" :order_id="formData.id" />
            </el-tab-pane>
            <el-tab-pane label="出库" name="outbound">
                <outbound ref="outboundRef" :order_id="formData.id" />
            </el-tab-pane>
            <el-tab-pane label="退库房" name="returnWarehouse">
                <returnWarehouse ref="returnWarehouseRef" />
            </el-tab-pane>
            <el-tab-pane label="退供应商" name="returnSupplier">
                <returnSupplier ref="returnSupplierRef" />
            </el-tab-pane>
        </el-tabs>
    </el-card>
    <el-dialog v-model="dialogShop" title="追加商品" width="1200">
        <el-form ref="formRef" label-width="90px">
            <div class="mb-2">
                <el-button type="primary" @click="showProduct = true">添加商品</el-button>
            </div>
            <el-table :data="productList">
                <el-table-column label="商品ID" prop="id" show-overflow-tooltip />
                <el-table-column label="商品图片" prop="image" min-width="80">
                    <template #default="{ row }">
                        <el-image
                            style="width: 50px; height: 50px"
                            :src="row.image"
                            :preview-teleported="true"
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    label="商品名称"
                    prop="store_name"
                    min-width="180"
                    show-overflow-tooltip
                />
                <el-table-column
                    label="分类"
                    prop="cate_name"
                    min-width="80"
                    show-overflow-tooltip
                />
                <el-table-column
                    label="单位"
                    prop="unit_name"
                    min-width="80"
                    show-overflow-tooltip
                />
                <el-table-column label="数量" min-width="150">
                    <template #default="{ row }">
                        <el-input v-model="row.num" @change="handleChange(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="价格" min-width="150">
                    <template #default="{ row }">
                        <el-input v-model="row.price" @change="handleChange(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="总价" min-width="150">
                    <template #default="{ row }">
                        <el-input v-model="row.total_price" />
                    </template>
                </el-table-column>
                <el-table-column label="生产日期" min-width="140">
                    <template #default="{ row }">
                        <el-date-picker
                            :readonly="false"
                            class="flex-1 !flex"
                            v-model="row.manufacture"
                            clearable
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="选择生产日期"
                        >
                        </el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="保质期" min-width="140">
                    <template #default="{ row }">
                        <el-date-picker
                            :readonly="false"
                            class="flex-1 !flex"
                            v-model="row.expiration_date"
                            clearable
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="选择保质期"
                        >
                        </el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button type="danger" link @click="handleDeleteProdut(row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogShop = false">取消</el-button>
                <el-button type="primary" @click="appendAdd"> 确认 </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="showProduct" title="选择商品" width="70%">
        <product-pop
            @onBindStore="onBindProduct"
            :warehouse_id="warehouse_id"
            :is_warehouse="is_warehouse"
        ></product-pop>
    </el-dialog>

    <el-dialog v-model="generateOrderShow" title="生成支付订单设置" width="600">
        <el-form :model="generateOrderData" label-width="90px">
            <el-form-item label="用户">
                <el-select
                    v-model="generateOrderData.user_id"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="输入用户名称搜索"
                    remote-show-suffix
                    :remote-method="remoteMethodUser"
                    :loading="userloading"
                    style="width: 240px"
                >
                    <el-option
                        v-for="item in userList"
                        :key="item.id"
                        :label="`${item.real_name}|${item.mobile}  (ID:${item.id})`"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="门店" prop="store_id">
                <el-select
                    v-model="generateOrderData.store_id"
                    placeholder="请选择门店"
                    size="large"
                    style="width: 240px"
                >
                    <el-option
                        v-for="item in storeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="支付方式" prop="pay_type">
                <el-select
                    v-model="generateOrderData.pay_type"
                    placeholder="请选择支付方式"
                    size="large"
                    style="width: 240px"
                >
                    <el-option label="微信小程序支付" value="7" />
                    <el-option label="采购款支付" value="18" />
                    <el-option label="余额支付" value="3" />
                    <el-option label="现金支付" value="17" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="generateOrderShow = false">取消</el-button>
                <el-button type="primary" @click="generateOrderAdd"> 确认 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup name="storeOrderDETAILS">
import { ElMessage, type FormInstance } from 'element-plus'
import {
    apiBeforehandOrderCartInfoLists,
    apiBeforehandOrderCartInfoAppendAdd
} from '@/api/beforehand_order_cart_info'
import {
    apiPurchaseOrderExport,
    apiPurchaseOrderGenerateOrder,
    apiBeforehandOrderDetail
} from '@/api/beforehand_order'
import type { PropType } from 'vue'
import { usePaging } from '@/hooks/usePaging'
import { useRoute } from 'vue-router'
import goodsOffer from './component/goodsOffer.vue'
import orderCartInfo from './component/orderCartInfo.vue'
import warehousing from './component/warehousing.vue'
import outbound from './component/outbound.vue'
import returnWarehouse from './component/returnWarehouse.vue'
import returnSupplier from './component/returnSupplier.vue'
import { apiUserLists } from '@/api/user'
import { apiSystemStoreLists } from '@/api/system_store'
import printData from './template-files/template1'
import { hiprint } from 'vue-plugin-hiprint'

const demos = () => {
    apiBeforehandOrderCartInfoLists({ bhoid: formData.value.id }).then((res) => {
        printData.printData.details = { ...formData.value }
        printData.printData.table = res.lists
        const hiprintTemplate = new hiprint.PrintTemplate({
            template: printData.json
        })
        console.log(printData)
        hiprintTemplate.print(printData, { printer: '', title: 'hiprint测试打印' })
    })
}

const generateOrderShow = ref(false)

const goodsOfferRef = ref(null)
const warehousingRef = ref(null)
const outboundRef = ref(null)
const orderCartInfoRef = ref(null)
const returnWarehouseRef = ref(null)
const returnSupplierRef = ref(null)
const route = useRoute()
const tabChange = (type: any) => {
    if (type == 'second') {
        orderCartInfoRef.value?.getList(formData.value)
    }
    if (type == 'offer') {
        goodsOfferRef.value?.getList(formData.value.id)
    }
    if (type == 'warehousing') {
        warehousingRef.value?.getList(formData.value.id, formData.value.warehousing_id)
    }
    if (type == 'outbound') {
        outboundRef.value?.getList(formData.value.id, formData.value)
    }
    if (type == 'returnWarehouse') {
        returnWarehouseRef.value?.getList(formData.value)
    }
    if (type == 'returnSupplier') {
        returnSupplierRef.value?.getList(formData.value)
    }
}
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const emit = defineEmits(['success', 'close'])
const showDialog = ref(false)
const dialogShop = ref(false)
const activeName = ref('second')
const warehouse_id = ref(0)
const is_warehouse = ref(0)
const financial_pm = ref(0)
// 表单数据
const formData = ref({
    id: '',
    code: '',
    total_price: '',
    supplier_name: '',
    warehouse_name: '',
    system_store: '',
    financial_pm: '',
    order_sn: '',
    warehousing_id: '',
    top_cate: []
})
const generateOrderData = ref({
    id: '',
    user_id: '',
    pay_type: '',
    store_id: ''
})
const appendAdd = () => {
    const product_arr = productList.value.map((item: any) => {
        return {
            id: item.id,
            nums: item.num || 0,
            purchase: item.price || 0,
            prices: item.purchase || 0,
            total_price: item.total_price || 0,
            manufacture: item.manufacture,
            expiration_date: item.expiration_date
        }
    })
    apiBeforehandOrderCartInfoAppendAdd({
        id: queryParams.bhoid,
        product_arr: product_arr
    }).then((res) => {
        dialogShop.value = false
    })
}
const queryParams = reactive({
    bhoid: route.query.id,
    pay_type: '',
    top_cate: '',
    top_cate_value: ''
})

const getDetail = () => {
    apiBeforehandOrderDetail({ id: queryParams.bhoid }).then((row: any) => {
        formData.value = { ...row }
        warehouse_id.value = row.warehouse_id
        generateOrderData.value.id = row.id
        if (row.financial_pm == 0) {
            is_warehouse.value = 1
        } else {
            financial_pm.value = 1
        }
        productList.value = []
    })
}
getDetail()
const xlsx2 = (id) => {
    apiPurchaseOrderExport({
        id: id
    }).then((res) => {
        window.open(res.url, '_blank')
        ElMessage.success('导出成功')
    })
}
const showProduct = ref(false) // 选择商品列表是否显示
// 商品列表
const productList = ref([])
// 删除已有商品
const handleDeleteProdut = (id: number) => {
    productList.value = productList.value.filter((item: any) => item.id !== id)
}
// 选择商品
const onBindProduct = (e: any[]) => {
    e.forEach((item: any) => {
        if (!productList.value.find((t: any) => t.id == item.id)) {
            productList.value.push(item)
        }
    })
    showProduct.value = false
}
function handleChange(row) {
    row.total_price = row.num * row.price
}
//打开弹窗
const open = () => {
    showDialog.value = true
}

const userloading = ref(false)
const userList = ref([])
const remoteMethodUser = (e = '') => {
    userloading.value = true
    apiUserLists({
        nickname: e,
        page_size: 10
    })
        .then((res) => {
            userList.value = res.lists
            setTimeout(() => {
                userloading.value = false
            }, 300)
        })
        .catch((err) => {
            setTimeout(() => {
                userloading.value = false
            }, 300)
        })
}
const storeList = ref([])
const generateOrderClick = () => {
    generateOrderShow.value = true
    apiSystemStoreLists({ page_no: 1, page_size: 100 }).then((res) => {
        storeList.value = res.lists
    })
}
const generateOrderAdd = () => {
    apiPurchaseOrderGenerateOrder(generateOrderData.value).then((res) => {})
}

defineExpose({
    open
})
</script>
