<template>
    <el-card>
        <div class="mb-4 text-lg font-bold">出库商品到门店</div>
        <div>
            <el-form ref="formRef" :model="formData" label-width="90px">
                <el-form-item label="仓库" prop="uid">
                    <el-select v-model="warehouse_id" style="width: 240px">
                        <el-option
                            v-for="item in warehouseList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="送货时间">
                    <el-date-picker
                        :readonly="false"
                        class="flex-1 !flex"
                        v-model="formData.manufacture"
                        clearable
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="选择生产日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="formData.remark" type="input" rows="4" />
                </el-form-item>
                <el-form-item label="门店" prop="store_id">
                    <div class="flex-1 w-full">
                        <div class="mb-2">
                            <el-button type="primary" @click="showStore = true">添加门店</el-button>
                        </div>
                        <el-table :data="storeList">
                            <el-table-column label="ID" prop="id" show-overflow-tooltip />
                            <el-table-column label="门店名称" prop="name" show-overflow-tooltip />
                            <el-table-column label="手机号码" prop="phone" show-overflow-tooltip />
                            <el-table-column
                                label="详细地址"
                                prop="detailed_address"
                                show-overflow-tooltip
                            />
                            <el-table-column label="门店logo" prop="image" show-overflow-tooltip>
                                <template #default="{ row }">
                                    <el-image
                                        :src="row.image"
                                        class="w-[40px] h-[40px]"
                                        :preview-teleported="true"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="营业状态" prop="is_show" show-overflow-tooltip>
                                <template #default="{ row }">
                                    {{ row.is_show ? '营业' : '打烊' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="120" fixed="right">
                                <template #default="{ row }">
                                    <el-button
                                        v-perms="['system_store.system_store/delete']"
                                        type="danger"
                                        link
                                        @click="handleDelete(row.id)"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
                <el-form-item label="商品" prop="store_id">
                    <div class="flex-1 w-full">
                        <div class="mb-2">
                            <el-button type="primary" @click="showProduct = true"
                                >添加商品</el-button
                            >
                        </div>
                        <el-table :data="productList">
                            <el-table-column
                                label="商品ID"
                                prop="product_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="200"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                label="分类"
                                prop="cate_name"
                                min-width="120"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                label="单位"
                                prop="unit_name"
                                min-width="80"
                                show-overflow-tooltip
                            />
                            <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.new_stock" @change="handleStock" />
                                </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>
                    </div>
                </el-form-item>
                <el-form-item label="库存类型" prop="stock_type">
                    <el-radio-group v-model="stock_type" class="ml-6">
                        <el-radio :value="1" :label="1">分配售卖库存</el-radio>
                        <el-radio :value="2" :label="2">分配兑换库存</el-radio>
                    </el-radio-group>
                    <span class="text-info text-xs ml-6"
                        >默认为分配售卖库存, 如需分配兑换库存请选择分配兑换库存</span
                    >
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="handleSubmit" type="primary" class="w-40">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-dialog v-model="showStore" title="选择门店" width="70%">
            <store-pop @onBindStore="onBindStore" :is_selection="0"></store-pop>
        </el-dialog>
        <el-dialog v-model="showProduct" title="选择商品" width="70%">
            <product-pop
                @onBindStore="onBindProduct"
                is_warehouse="1"
                :warehouse_id="warehouse_id"
            ></product-pop>
        </el-dialog>
    </el-card>
</template>

<script lang="ts" setup name="storeProductEdit">
import { ElMessage, type FormInstance } from 'element-plus'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import { apiWarehouseOrderOutbound } from '@/api/warehouse_order'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiStoreCategoryLists } from '@/api/store_category'
import { apiStoreProductUnitLists } from '@/api/store_product_unit'
import { apiWarehouseLists } from '@/api/warehouse'

const route = useRoute()
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const { removeTab } = useMultipleTabs()
const mode = ref('add')
const warehouse_id = ref('')
const warehouseList = ref([])
const stock = ref(0)

// 表单数据
const formData = reactive({
    store_id: '',
    manufacture: '',
    remark: ''
})
if (route.query.warehouse_id) {
    warehouse_id.value = parseInt(route.query.warehouse_id)
}

const warehouse = () => {
    apiWarehouseLists({}).then((res) => {
        warehouseList.value = res.lists
    })
}
const showStore = ref(false) // 选择门店列表是否显示
// 门店列表
const storeList = ref([])
// 删除已有门店
const handleDelete = (id: number) => {
    storeList.value = storeList.value.filter((item: any) => item.id !== id)
}
// 选择门店
const onBindStore = (e: any[]) => {
    storeList.value = []
    storeList.value.push(e)
    handleStock()
    showStore.value = false
}

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
}

const unitList = ref([])
const getUnitList = () => {
    apiStoreProductUnitLists({}).then((res) => {
        unitList.value = res.lists
    })
}
getUnitList()

const stock_type = ref(1)
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
        }
    })
    // const store_arr = storeList.value.length
    // if (store_arr > 0 && product_arr.length > 0) {
    //     try {
    //         product_arr.forEach((item) => {
    //             const stock = item.stock * store_arr
    //             if (stock > item.stocks) {
    //                 isSubmit.value = false
    //                 throw new Error('超出仓库库存,请重新设置')
    //             }
    //         })
    //     } catch (e) {
    //         ElMessage.error('超出仓库库存,请重新设置')
    //         return
    //     }
    // }
    // isSubmit.value = true
}

const router = useRouter()
// 提交按钮
const handleSubmit = async () => {
    if (warehouse_id.value == '') {
        ElMessage.error('请选择仓库')
        return
    }
    handleStock()
    if (isSubmit.value == false) {
        return
    }
    const product_arr = productList.value.map((item: any) => {
        return {
            id: item.product_id,
            stock: item.new_stock || 0,
            batch: item.batch || 0
        }
    })
    const store_arr = storeList.value.map((item: any) => item.id)
    if (store_arr.length > 1) {
        ElMessage.error('门店不能超过一个')
        return
    }
    apiWarehouseOrderOutbound({
        product_arr,
        store_arr,
        stock_type: stock_type.value,
        warehouse_id: warehouse_id.value,
        delivery_time: formData.manufacture,
        mark: formData.remark
    }).then((res) => {
        // removeTab()
        // if (res.code == 1) {
        // ElMessage.success(res.msg)
        setTimeout(() => {
            router.push({
                path: '/warehouse/outbound_order'
            })
        }, 2000)
        // } else {
        //     ElMessage.error(res.msg)
        // }
    })
}
warehouse()
</script>
