<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.order_id }}</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> -->
        </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">
                <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="warehouse_stock"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                label="需要数量"
                                prop="cart_num"
                                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="是否需采购"
                                prop="is_buyer"
                                show-overflow-tooltip
                                width="100"
                            >
                                <template #default="{ row }">
                                    <div v-if="row.is_buyer == 0">
                                        <el-button
                                            type="danger"
                                            round
                                            size="small"
                                            @click="handleBuyer(-1, row)"
                                            >否</el-button
                                        >
                                        <el-button
                                            type="success"
                                            round
                                            size="small"
                                            @click="handleBuyer(1, row)"
                                            >是</el-button
                                        >
                                    </div>
                                    <div v-else>
                                        <span v-if="row.is_buyer == 1">{{ row.status_name }}</span>
                                        <span v-if="row.is_buyer == -1">无需采购</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <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-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-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 />
                <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.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>
                <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>
    <edit-popup v-if="showEdit" ref="editRef" @success="getLists" @close="showEdit = false" />
    <el-dialog v-model="dialogBuyer" title="设置采购" width="600">
        <el-form ref="formRef" :model="purchase_product_offer" label-width="90px">
            <el-form-item label="采购人员">
                <el-select
                    v-model="purchase_product_offer.buyer_id"
                    placeholder="请选择采购人员"
                    size="large"
                    style="width: 240px"
                >
                    <el-option
                        v-for="item in delivery_list"
                        :label="item.nickname"
                        :value="item.uid"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="采购数量" prop="need_num">
                <el-input
                    v-model="purchase_product_offer.need_num"
                    clearable
                    placeholder="请输入采购数量"
                    :readonly="false"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogBuyer = false">取消</el-button>
                <el-button type="primary" @click="goodsOfferUpdate"> 确认 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup name="storeOrderDETAILS">
import { ElMessage, type FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {
    apiPurchaseProductOfferLists,
    apiPurchaseProductOfferAdd
} from '@/api/purchase_product_offer'
import {
    apiBeforehandOrderCartInfoLists,
    apiBeforehandOrderCartInfoDelete,
    apiBeforehandOrderCartInfoAppendAdd,
    apiBeforehandOrderCartInfoProcurementStatus
} from '@/api/beforehand_order_cart_info'
import { apiWarehouseOrderRentryExport, apiWarehouseOrderExport } 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'
import { apiDeliveryServiceLists } from '@/api/delivery_service'
import goodsOffer from './component/goodsOffer.vue'
import warehousing from './component/warehousing.vue'
import outbound from './component/outbound.vue'

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

const goodsOfferRef = ref(null)
const warehousingRef = ref(null)
const outboundRef = ref(null)

const route = useRoute()
const tabChange = (type: any) => {
    if (type == 'offer') {
        goodsOfferRef.value?.getLists()
    }
    if (type == 'warehousing') {
        warehousingRef.value?.getLists()
    }
    if (type == 'outbound') {
        outboundRef.value?.getLists()
    }
}
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 purchase_product_offer = ref({
    order_id: '',
    product_id: '',
    need_num: '',
    unit: '',
    is_buyer: '',
    buyer_id: ''
})
const goodsOfferUpdate = () => {
    apiPurchaseProductOfferAdd(purchase_product_offer.value).then((res) => {
        getLists()
        dialogBuyer.value = false
    })
}
const appendAdd = () => {
    const product_arr = productList.value.map((item: any) => {
        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
        }
    })
    apiBeforehandOrderCartInfoAppendAdd({
        id: queryParams.bhoid,
        product_arr: product_arr
    }).then((res) => {
        console.log(res)
        dialogShop.value = false
        getLists()
    })
}
const queryParams = reactive({
    bhoid: '',
    pay_type: ''
})
// 获取详情
const setFormData = async (data: Record<any, any>) => {
    formData.value = { ...data }
}

const getDetail = async (row: Record<string, any>) => {
    formData.value = { ...row }
    queryParams.bhoid = 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 delivery_list = ref([])
const DeliveryService = () => {
    apiDeliveryServiceLists({ type: 3 }).then((res) => {
        delivery_list.value = res.lists
    })
}
/**
 * 是否需采购
 * @param e
 */
const handleBuyer = (e, row) => {
    if (e == 1) {
        purchase_product_offer.value.order_id = row.bhoid
        purchase_product_offer.value.product_id = row.product_id
        purchase_product_offer.value.unit = row.unit
        purchase_product_offer.value.need_num = row.cart_num
        purchase_product_offer.value.is_buyer = '1'
        DeliveryService()
        dialogBuyer.value = true
    } else {
        apiBeforehandOrderCartInfoProcurementStatus({
            id: row.id
        }).then(() => {
            getLists()
        })
    }
}
// 编辑
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 apiBeforehandOrderCartInfoDelete({ id })
    getLists()
}
//打开弹窗
const open = () => {
    showDialog.value = true
}
// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiBeforehandOrderCartInfoLists,
    params: queryParams
})

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
