<template>
    <el-drawer v-model="showDialog" title="订单详情" :size="1200">
        <div class="flex items-center justify-between m-4">
            <div class="flex flex-col">
                <div style="color: gray">仓库：</div>
                <div style="color: black">{{ formData.warehouse_name }}</div>
            </div>
            <div class="flex flex-col" v-if="formData.financial_pm == 1">
                <div style="color: gray">供应商：</div>
                <div style="color: black">{{ formData.supplier_name }}</div>
            </div>
            <div class="flex flex-col" v-else>
                <div style="color: gray">门店：</div>
                <div style="color: black">{{ formData.system_store }}</div>
            </div>
            <div class="flex flex-col">
                <div style="color: gray">单号：</div>
                <div style="color: black">{{ formData.code }}</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="xlsx(formData.id, 2)"> 打印供货单 </el-button>
            <el-button @click="xlsx(formData.id, 3)"> 打印商户/会员单 </el-button>
            <el-button @click="xlsx(formData.id, 4)"> 打印零售单 </el-button>
            <el-button @click="xlsx2(formData.id)"> 打印商品标签 </el-button>
        </div>
        <el-button type="primary" @click="dialogShop = true" v-if="formData.financial_pm == 1">
            入库
        </el-button>
        <el-button type="primary" @click="dialogShop = true" v-else> 出库 </el-button>

        <el-tabs v-model="activeName" class="demo-tabs mt-3" type="border-card">
            <el-tab-pane label="明细" name="second">
                <div>
                    <div>
                        <el-table :data="pager.lists" v-loading="pager.loading">
                            <el-table-column
                                label="商品信息"
                                prop="store_name"
                                show-overflow-tooltip
                            >
                                <template #default="{ row }">
                                    <div class="flex items-center">
                                        <el-image
                                            :src="row.image"
                                            class="w-16 h-16 mr-2"
                                            :preview-teleported="true"
                                        ></el-image>
                                        <div>{{ row.store_name }}</div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" prop="nums" show-overflow-tooltip />
                            <el-table-column label="采购价" prop="purchase" show-overflow-tooltip />
                            <el-table-column label="零售价" prop="price" show-overflow-tooltip />
                            <el-table-column
                                label="合计"
                                prop="total_price"
                                show-overflow-tooltip
                            />
                            <el-table-column label="操作" width="120" fixed="right">
                                <template #default="{ row }">
                                    <el-button
                                        v-perms="['warehouse_product.warehouse_product/edit']"
                                        type="primary"
                                        link
                                        @click="handleEdit(row)"
                                    >
                                        编辑
                                    </el-button>
                                    <el-button
                                        v-perms="['warehouse_product.warehouse_product/delete']"
                                        type="danger"
                                        link
                                        @click="handleDeletes(row.id)"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="flex mt-4 justify-end" v-if="pager.lists.length < pager.count">
                        <pagination v-model="pager" @change="getLists" />
                    </div>
                </div>
            </el-tab-pane>
        </el-tabs>
    </el-drawer>
    <el-dialog v-model="dialogShop" title="追加商品" width="1200">
        <el-form ref="formRef" :model="updateInfo" 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
                    v-if="formData.financial_pm == 1"
                />
                <el-table-column label="商品ID" prop="product_id" show-overflow-tooltip v-else />

                <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
                />
                <template v-if="formData.financial_pm == 1">
                    <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.purchases" @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>
                </template>
                <template v-else>
                    <el-table-column
                        label="商品价格"
                        prop="price"
                        min-width="100"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        label="库存"
                        prop="stock"
                        min-width="100"
                        show-overflow-tooltip
                    />
                    <el-table-column label="分配库存" min-width="150">
                        <template #default="{ row }">
                            <el-input v-model="row.num" />
                        </template>
                    </el-table-column>
                </template>
                <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="goodsOfferUpdate"> 确认 </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>
    <edit-popup v-if="showEdit" ref="editRef" @success="getLists" @close="showEdit = false" />
</template>

<script lang="ts" setup name="storeOrderDETAILS">
import { ElMessage, type FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiWarehouseProductLists, apiWarehouseProductDelete } from '@/api/warehouse_product'
import {
    apiWarehouseOrderRentryExport,
    apiWarehouseOrderExport,
    apiWarehouseOrderEdit,
    apiWarehouseOrderExportTags
} from '@/api/warehouse_order'
import type { PropType } from 'vue'
import { usePaging } from '@/hooks/usePaging'
import { useRoute } from 'vue-router'
import feedback from '@/utils/feedback'
import EditPopup from './editProduct.vue'

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
// 是否显示编辑框
const showEdit = ref(false)

const route = useRoute()

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: ''
})
const updateInfo = ref({})
const goodsOfferUpdate = () => {
    const product_arr = productList.value.map((item: any) => {
        if (financial_pm.value == 1) {
            return {
                id: item.id,
                nums: item.num || 0,
                purchase: item.purchases || 0,
                prices: item.purchase || 0,
                total_price: item.total_price || 0,
                manufacture: item.manufacture,
                expiration_date: item.expiration_date
            }
        } else {
            return {
                id: item.product_id,
                nums: item.num || 0,
                purchase: item.purchases || 0,
                prices: item.purchase || 0,
                total_price: item.total_price || 0,
                manufacture: item.manufacture,
                expiration_date: item.expiration_date
            }
        }
    })
    apiWarehouseOrderEdit({
        id: queryParams.oid,
        product_arr: product_arr
    }).then((res) => {
        console.log(res)
        dialogShop.value = false
        getLists()
    })
}
const queryParams = reactive({
    oid: '',
    pay_type: ''
})
// 获取详情
const setFormData = async (data: Record<any, any>) => {
    formData.value = { ...data }
}

const getDetail = async (row: Record<string, any>) => {
    formData.value = { ...row }
    queryParams.oid = row.id
    warehouse_id.value = row.warehouse_id
    if (row.financial_pm == 0) {
        is_warehouse.value = 1
    } else {
        financial_pm.value = 1
    }
    productList.value = []
    // setFormData(data)
    getLists()
}
const xlsx = (id, type) => {
    if (formData.value.financial_pm == 1) {
        apiWarehouseOrderRentryExport({
            id: id
        }).then((res) => {
            window.open(res.url, '_blank')
            ElMessage.success('导出成功')
        })
    } else {
        apiWarehouseOrderExport({
            id: id,
            type: type
        }).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.purchases
}
const isSubmit = ref(true)

const handleStock = () => {
    // const counts = storeList.value.length
    const product_arr = productList.value.map((item: any) => {
        return {
            id: item.product_id,
            stock: item.new_stock || 0,
            stocks: item.stock || 0
        }
    })
    if (product_arr.length > 0) {
        try {
            product_arr.forEach((item) => {
                const stock = item.stock * 1
                if (stock > item.stocks) {
                    isSubmit.value = false
                    throw new Error('超出仓库库存,请重新设置')
                }
            })
        } catch (e) {
            ElMessage.error('超出仓库库存,请重新设置')
            return
        }
    }
    isSubmit.value = true
}
// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.setFormData(data)
}
// 删除
const handleDeletes = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiWarehouseProductDelete({ id })
    getLists()
}
//打开弹窗
const open = () => {
    showDialog.value = true
}
// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiWarehouseProductLists,
    params: queryParams
})
const xlsx2 = (id) => {
    apiWarehouseOrderExportTags({
        id: id
    }).then((res) => {
        window.open(res.url, '_blank')
        ElMessage.success('导出成功')
    })
}
defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
