<template>
    <el-card>
        <div class="mb-4 text-lg font-bold">预定单添加</div>
        <div>
            <el-form ref="formRef" :model="formData" label-width="90px" :inline="true">
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="用户">
                            <el-input v-model="formData.nickname" type="input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="电话">
                            <el-input v-model="formData.phone" type="input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="地址">
                            <el-input
                                v-model="formData.address"
                                type="input"
                                style="width: 400px"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单类型" prop="order_type">
                            <el-radio-group v-model="formData.order_type">
                                <el-radio :label="1">铺货订单</el-radio>
                                <el-radio :label="2">摊贩订单</el-radio>
                                <el-radio :label="3">一条龙订单</el-radio>
                                <!-- <el-radio :label="4">线上订单</el-radio> -->
                                <el-radio :label="5">仓库补货</el-radio>
                                <el-radio :label="6">往期补单</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="门店" prop="store_id" style="width: 300px">
                            <el-select
                                v-model="formData.store_id"
                                placeholder="请选择门店"
                                size="large"
                            >
                                <el-option
                                    v-for="item in storeList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="到货时间">
                            <el-date-picker
                                v-model="formData.arrival_time"
                                type="datetime"
                                :readonly="false"
                                clearable
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="请选择到货时间"
                                style="width: 180px"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="桌数">
                            <el-input-number v-model="formData.tables" type="input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="办事天数">
                            <el-input-number v-model="formData.days" type="input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="厨师">
                            <el-input v-model="formData.chef" type="input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="电话">
                            <el-input v-model="formData.chef_phone" type="input" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="采购事由">
                            <el-input
                                v-model="formData.purpose"
                                type="input"
                                style="width: 480px"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input v-model="formData.mark" type="input" style="width: 480px" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="商品" prop="product_id" class="w-full">
                    <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="id" show-overflow-tooltip>
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.id"
                                        @keydown.enter="enterProduct(row)"
                                        :ref="(el) => (labelRefs[$index + 'id'] = el)"
                                        @keyup="moveFocus($event, $index, 'id')"
                                    />
                                </template>
                            </el-table-column>
                            <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"
                                show-overflow-tooltip
                            >
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.store_name"
                                        @keydown.enter="enterStoreName(row)"
                                        :ref="(el) => (labelRefs[$index + 'store_name'] = el)"
                                        @keyup="moveFocus($event, $index, 'store_name')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="数量">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.nums"
                                        @change="handleChange(row)"
                                        :ref="(el) => (labelRefs[$index + 'nums'] = el)"
                                        @keyup="moveFocus($event, $index, 'nums')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="价格">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.price"
                                        @change="handleChange(row)"
                                        :ref="(el) => (labelRefs[$index + 'price'] = el)"
                                        @keyup="moveFocus($event, $index, 'price')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="总价">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.total_price"
                                        :ref="(el) => (labelRefs[$index + 'total_price'] = el)"
                                        @keyup="moveFocus($event, $index, 'total_price')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="型号">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.marques"
                                        :ref="(el) => (labelRefs[$index + 'marques'] = el)"
                                        @keyup="moveFocus($event, $index, 'marques')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="包装">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.package"
                                        :ref="(el) => (labelRefs[$index + 'package'] = el)"
                                        @keyup="moveFocus($event, $index, 'package')"
                                    />
                                </template>
                            </el-table-column>

                            <el-table-column
                                label="单位"
                                prop="unit_name"
                                min-width="80"
                                show-overflow-tooltip
                            />
                            <el-table-column label="毛重">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.gross_weight"
                                        :ref="(el) => (labelRefs[$index + 'gross_weight'] = el)"
                                        @keyup="moveFocus($event, $index, 'gross_weight')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="净重">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.net_weight"
                                        :ref="(el) => (labelRefs[$index + 'net_weight'] = el)"
                                        @keyup="moveFocus($event, $index, 'net_weight')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="规格">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.store_info"
                                        :ref="(el) => (labelRefs[$index + 'store_info'] = el)"
                                        @keyup="moveFocus($event, $index, 'store_info')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="售后">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.after_sales"
                                        :ref="(el) => (labelRefs[$index + 'after_sales'] = el)"
                                        @keyup="moveFocus($event, $index, 'after_sales')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="损耗">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.loss"
                                        :ref="(el) => (labelRefs[$index + 'loss'] = el)"
                                        @keyup="moveFocus($event, $index, 'loss')"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="备注">
                                <template #default="{ row, $index }">
                                    <el-input
                                        v-model="row.mark"
                                        :ref="(el) => (labelRefs[$index + 'mark'] = el)"
                                        @keyup="moveFocus($event, $index, 'mark')"
                                    />
                                </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-row>
                    <el-button @click="handleSubmit" type="primary" class="w-40 ml-20"
                        >提交</el-button
                    >
                    <el-form-item label="总价" prop="total_price">
                        <div>
                            {{ formData.total_price }}
                            <span class="ml-4">该金额只做前台展示,后台会从新计算</span>
                        </div>
                    </el-form-item>
                </el-row>
            </el-form>
        </div>
        <el-dialog v-model="showProduct" title="选择商品" width="70%">
            <product-warehouse-pop @onBindStore="onBindProduct"></product-warehouse-pop>
        </el-dialog>
    </el-card>
    <el-dialog v-model="dialogProductShow" title="选择商品" width="1200">
        <el-table :data="dialogProductLists" @current-change="handleCurrentChange" :height="300">
            <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="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>
    </el-dialog>
</template>

<script lang="ts" setup name="storeProductEdit">
import { ElMessage, type FormInstance } from 'element-plus'
import type { PropType } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiBeforehandOrderAdd } from '@/api/beforehand_order'
import { apiSystemStoreLists } from '@/api/system_store'
import { apiStoreProductDetail, apiStoreProductLists } from '@/api/store_product'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
// 表单数据
const formData = reactive({
    warehouse_id: '',
    supplier_id: '',
    code: '',
    total_price: 0,
    order_type: 1,
    store_id: '',
    nickname: '',
    phone: '',
    address: '',
    arrival_time: '',
    purpose: '',
    tables: 0,
    days: 0,
    chef: '',
    chef_phone: '',
    mark: ''
})
const enterProduct = async (e: any) => {
    const data = await apiStoreProductDetail({ id: e.id })
    setData(e, data)
}

const setData = (e: any, data: any) => {
    console.log(e)
    console.log(data)
    e.id = data.id
    e.image = data.image
    e.marques = data.marques
    e.store_info = data.store_info
    e.price = data.price
    e.purchase = data.purchase
    e.after_sales = data.after_sales
    e.loss = data.loss
    e.mark = data.mark
    e.unit = data.unit
    e.store_name = data.store_name
    e.unit_name = data.unit_name
    e.gross_weight = data.gross_weight
    e.net_weight = data.net_weight
    e.package = data.package
    const ids: any[] = []
    productList.value.forEach((item: any) => {
        ids.push(item.id)
    })
    if (ids.includes(0) == false) {
        productList.value.push({ id: 0 })
    }
}
const showProduct = ref(false) // 选择商品列表是否显示
// 商品列表
const productList = ref([{ id: 0 }])
// 删除已有商品
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.nums * row.price).toFixed(2)
    if (row.total_price > 0) {
        formData.total_price = (
            parseFloat(formData.total_price) + parseFloat(row.total_price)
        ).toFixed(2)
    }
}

const router = useRouter()
// 提交按钮
const handleSubmit = async () => {
    const product_arr = productList.value.map((item: any) => {
        return {
            product_id: item.id,
            nums: item.nums,
            price: item.price || 0,
            purchase: item.purchase || 0,
            total_price: item.total_price || 0,
            marques: item.marques,
            store_info: item.store_info,
            after_sales: item.after_sales,
            loss: item.loss,
            unit: item.unit,
            gross_weight: item.gross_weight,
            net_weight: item.net_weight,
            package: item.package,
            mark: item.mark
        }
    })
    apiBeforehandOrderAdd({
        product_arr,
        ...formData
    }).then((res) => {
        setTimeout(() => {
            router.push({
                path: '/order/beforehand_order'
            })
        }, 2000)
    })
}
const storeList = ref([])
apiSystemStoreLists({ page_no: 1, page_size: 100 }).then((res) => {
    storeList.value = res.lists
})

const dialogProductLists = ref([])
const dialogProductShow = ref(false)
const dialogProductData = ref()
const enterStoreName = (e: any) => {
    apiStoreProductLists({ store_name: e.store_name, product_type: 0 }).then((res) => {
        if (res.count == 1) {
            const data = res.lists[0]
            setData(e, data)
        }
        if (res.count > 1) {
            dialogProductLists.value = res.lists
            dialogProductShow.value = true
            dialogProductData.value = e
        }
    })
}
// 表格选择后回调事件
const handleCurrentChange = (val: any[]) => {
    if (val == null) {
        return
    }
    setData(dialogProductData.value, val)
    dialogProductShow.value = false
    dialogProductLists.value = []
    dialogProductData.value = []
}

const labelRefs = reactive<Record<string, HTMLElement>>({})
const moveFocus = (event: any, index: number, key: string) => {
    const keyField = [
        'id',
        'store_name',
        'nums',
        'price',
        'total_price',
        'marques',
        'gross_weight',
        'net_weight',
        'store_info',
        'after_sales',
        'loss',
        'package',
        'mark'
    ]

    // if (event.keyCode === 13) {
    //     // 回车向右
    //     if (index === productList.value.length - 1 && key === keyField[keyField.length - 1]) {
    //         return
    //     }
    //     labelRefs[index + key].blur()
    //     if (key === keyField[keyField.length - 1]) {
    //         labelRefs[index + 1 + keyField[0]].focus()
    //     } else {
    //         const nextKeyIndex = keyField.findIndex((item) => item === key) + 1
    //         nextTick(() => {
    //             labelRefs[index + keyField[nextKeyIndex]].focus()
    //         })
    //     }
    // }
    // 向上 38
    if (event.keyCode === 38) {
        if (index === 0) {
            return // 第一行无法向上
        }
        labelRefs[index + key].blur()
        nextTick(() => {
            labelRefs[index - 1 + key].focus()
        })
    }
    // 向下 40
    if (event.keyCode === 40) {
        if (index === productList.value.length - 1) {
            return // 最后一行无法向下
        }
        labelRefs[index + key].blur()
        nextTick(() => {
            labelRefs[index + 1 + key].focus()
        })
    }
    // 向左 37
    if (event.keyCode === 37) {
        if (index === 0 && key === keyField[0]) {
            return
        }
        labelRefs[index + key].blur()
        // 当前行第一个,跳转上一行最后一个
        if (key === keyField[0]) {
            labelRefs[index - 1 + keyField[keyField.length - 1]].focus()
        } else {
            // 跳转上一个
            const preKeyIndex = keyField.findIndex((item) => item === key) - 1
            nextTick(() => {
                labelRefs[index + keyField[preKeyIndex]].focus()
            })
        }
    }
    // // 向右 39
    if (event.keyCode === 39) {
        if (index === productList.value.length - 1 && key === keyField[keyField.length - 1]) {
            return
        }
        labelRefs[index + key].blur()
        // 最后一行最后一个,跳转下一行第一个
        if (key === keyField[keyField.length - 1]) {
            labelRefs[index + 1 + keyField[0]].focus()
        } else {
            // 跳转下一个
            const nextKeyIndex = keyField.findIndex((item) => item === key) + 1
            nextTick(() => {
                labelRefs[index + keyField[nextKeyIndex]].focus()
            })
        }
    }
}
</script>
