<template>
    <div class="p-4 bg-white">
        <el-button type="text" @click="goBack">返回</el-button>
        <!-- <h2 class="text-center my-4">发货管理</h2> -->
        <div class="text-center my-4">
            <!--  <Vue3Barcode v-if="barcodeValue" :value='barcodeValue' width="1" height='30'></Vue3Barcode> -->
            <!--  <p>RYKS_DDD-20240527-00201</p> -->
        </div>
        <el-form :model="goodsInventoryAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
            style="max-width: 600px">
            <el-form-item prop="inventory_time" label="盘点时间:" class="change-form-item">
                <el-date-picker v-model="goodsInventoryAddForm.inventory_time" style="width: 170px" size="small"
                    type="datetime" placeholder="Select date and time" :default-time="defaultTime" />
            </el-form-item>
            <el-form-item prop="warehouse_id" label="仓库:" class="change-form-item">
                <span>{{ warehouseName(goodsInventoryAddForm.warehouse_id) }}</span>
            </el-form-item>
            <el-form-item label="盘点人:" prop="inventory_person_id" class="change-form-item">
                <span> {{ getadminList(goodsInventoryAddForm.inventory_person_id) }}</span>
            </el-form-item>
            <el-form-item label="制单人:" prop="creator_id" class="change-form-item">
                <span>{{ getadminList(goodsInventoryAddForm.creator_id) }}</span>
            </el-form-item>
            <el-form-item label="盘点类型:" prop="inventory_type" class="change-form-item">
                <span>{{ deliveryName(goodsInventoryAddForm.inventory_type) }}</span>
            </el-form-item>
            <el-button type="primary" size="large" @click="scanCode">商品扫码</el-button>
            <el-table :data="goodsInventoryAddForm.product_list" style="width: 100%">
                <el-table-column prop="goods_vo.name" label="商品名称" />
                <el-table-column prop="product_vo.sku" label="SKU" />
                <el-table-column prop="inventory_num" label="盘点数量">
                    <template #default="scope">
                            <span :style="{ color: scope.row.inventory_num > 0 ? 'red' : 'black' }">
                                {{ scope.row.inventory_num }}
                            </span>
                        </template>
                </el-table-column>
                <el-table-column prop="actual_stock"  label="库存数量">
                    <!-- <template #default="scope">
                        <span style="color: red;">{{ scope.actual_stock }}</span>
                    </template> -->
                </el-table-column>
            </el-table>
        </el-form>
        <el-dialog v-model="dialogVisible" :modal=false title="商品扫码" :close-on-click-modal="false" top="80px"
            width="90%" style="height: 200px" :before-close="handleClose">
            <el-form :model="snCodeForm" label-width="auto" style="max-width: 600px">
                <el-form-item label="SKU">
                    <el-input v-model="snCodeForm.bar_code" ref="inputRef" clearable :inputmode="inputmode" @keyup.enter="toSearch()" >
                        <template #append> <img src="../../assets/images/JP.png" @click="getInfo" class="w-8 h-8" /> </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="序列号">
                    <el-input v-model="snCodeForm.sn_code" ref="snInputRef" clearable :inputmode="inputmode"
                        @keyup.enter="toSnCode()" />
                </el-form-item>
            </el-form>
            <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false"></el-button>
                    <el-button type="primary" @click="dialogVisible = false">
                        Confirm
                    </el-button>
                </div>
            </template> -->
        </el-dialog>
        <div class="flex justify-center mt-4">

            <el-button type="primary" size="large" @click="getOrderNumber(ruleFormRef)">保存</el-button>
            <!-- <el-button type="primary" size="large" @click="ship">发货</el-button> -->
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, reactive, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { orderApi, infoApi, dictionaryAPI, inventoryAPI } from '@/api/api'
//引入
import Vue3Barcode from 'vue3-barcode'
//定义要生成条形码的值
import { ElMessage, FormRules, FormInstance } from 'element-plus'
const appointment_time = ref('')
const defaultTime = new Date()
let dialogVisible = ref(false)
const tableData = ref([])
let inputmode = ref('text')
let barcodeValue = ref('')
const router = useRouter();
const route = useRoute()
const activeTab = ref('basic-info');
const id = ref(route.params.id);
const goodsInventoryAddForm: any = reactive({
    warehouse_id: '',
    inventory_person_id: '',
    product_list: [],
    creator_id: '',
    inventory_type: '',
    inventory_time: new Date(),
})
interface RuleForm {
    warehouse_id: string,
    type: string
}
const ruleFormRef = ref<FormInstance>()
//校验表单
const rules = reactive<FormRules<RuleForm>>({
    warehouse_id: [
        {
            required: true,
            message: 'Please select Activity zone',
            trigger: 'change',
        },
    ],
    type: [
        {
            required: true,
            message: 'Please select Activity count',
            trigger: 'change',
        },
    ],
})
//表单
const snCodeForm = reactive({
    bar_code: "",
    sn_code: '',
})
const inputRef = ref<any>(null);
const snInputRef = ref<any>(null)
const customerList: any = ref([])//初始化客户列表
const warehouseList: any = ref([])//初始化客户列表
const collectingAccountList: any = ref([])//初始化客户列表
const typeList: any = ref([])//初始化客户列表
const orderTypeList: any = ref([])//初始化客户列表
const index = ref(-1);
let sku = ref('');
const adminList: any = ref([])
watch(activeTab, (newValue, oldValue) => {
    console.log(`Tab changed from ${oldValue} to ${newValue}`);
    // 这里可以添加一些逻辑，但要确保不会再次修改 activeTab
});
const getInfo = () => {
    if (inputmode.value == 'none') {
        inputmode.value = 'text'
        inputRef.value.focus();
    } else {
        inputmode.value = 'none'
        inputRef.value.focus();
    }
}
/* 扫sku */
const toSearch = async () => {
    activeTab.value = 'product-info'
    try {
        const res: any = await orderApi.getProduct(
            goodsInventoryAddForm.warehouse_id,
            snCodeForm.bar_code.replace(/\s+/g, '')
        );
        res.data.sn_code_list = [];
        sku.value = res.data.product_vo.sku;
        // 查找当前商品是否已存在于列表中
        const indexs = goodsInventoryAddForm.product_list.findIndex(
            (el) => {
                console.log("Comparing with:", el);
                return (
                    el.goods_vo.id === res.data.goods_id &&
                    el.product_id === res.data.product_id &&
                    el.product_vo.sku === res.data.product_vo.sku
                );
            }
        );
        // 如果商品不存在，则添加到列表
        if (indexs === -1) {
            index.value = goodsInventoryAddForm.product_list.length;
            goodsInventoryAddForm.product_list.push(res.data);
        } else {
            index.value = indexs;
        }
        if (res.data.product_vo.have_sn) {
            nextTick(() => {
                snInputRef.value.focus();
            });
        } else {
            /* this.scanDialogVisible = false; */
        }
    } catch (error) {
        goodsInventoryAddForm.product_list[index.value].inventory_num += 1
        console.error('Error fetching product:', error);
    }
};
//扫描序列号
const toSnCode = async () => {
    if(!sku.value) return  ElMessage.error('请先扫描sku!')
    try {
        const res: any = await orderApi.getsnCode(
            "inventory",
            sku.value,
            snCodeForm.sn_code.replace(/\s+/g, '')
        );

        snCodeForm.sn_code = "";
        const exists = goodsInventoryAddForm.product_list[index.value].sn_code_list.find(
            item => item.sn_code === res.sn_code && item.sku === res.sku
        );

        if (!exists) {
            await infoApi.skuRedis({ send_order_id: id.value, item_id: goodsInventoryAddForm.product_list[index.value].id, sku: res.data }).then((respons: any) => {
                goodsInventoryAddForm.product_list[index.value].sn_code_list.push(res.data);
            })
        }
        goodsInventoryAddForm.product_list[index.value].inventory_num = goodsInventoryAddForm.product_list[index.value].sn_code_list.length;
        snCodeForm.bar_code = "";
        nextTick(() => {
            inputRef.value.focus();
        });
    } catch (error) {
        console.error('Error fetching SN code:', error);
    }
}

//关闭弹窗
const handleClose = (done: () => void) => {
    done()
}
onMounted(async () => {
    await getInforList();
    init();
});
const goBack = () => {
    router.push({ name: 'Inventory' });
};

const scanCode = () => {
    dialogVisible.value = true
    nextTick(() => {
        if (inputRef.value) {
            try {
                inputRef.value.focus(); // 先尝试聚焦 input 元素
                setTimeout(() => {
                    if (inputRef.value) {
                        inputRef.value.select();
                        inputmode.value='none'
                    }
                }, 100);
            } catch (error) {
                console.error('Failed to select input:', error);
            }
        }
    });
};
// 格式化日期时间为本地格式
function formatDate(date) {
    const y = date.getFullYear();
    const m = date.getMonth() + 1; // 月份是从0开始的
    const d = date.getDate();
    const hr = date.getHours();
    const min = date.getMinutes();
    const sec = date.getSeconds();
    return `${y}-${pad(m)}-${pad(d)} ${pad(hr)}:${pad(min)}:${pad(sec)}`;
}

// 补零函数
function pad(n) {
    return n < 10 ? '0' + n : n;
}
const getOrderNumber = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (!goodsInventoryAddForm.product_list.length) {
                ElMessage.error("请选择商品！");
                return;
            }
            goodsInventoryAddForm.product_list.map(el => {
                el.diff_num = el.usable_stock - el.inventory_num
            })
            goodsInventoryAddForm.inventory_time = formatDate(goodsInventoryAddForm.inventory_time)
            inventoryAPI.editInventory(id.value, goodsInventoryAddForm).then(res => {
                ElMessage.success("保存成功！");
                router.replace({
                    name: 'Inventory',
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};

const ship = () => {
    console.log('发货');
};
const init = async () => {
    try {
        const res: any = await inventoryAPI.inventory(id.value);
        await infoApi.skuRedis({ send_order_id: id.value, type: 'enter' }).then((response: any) => {
            res.data.product_list.map(el => {
                Object.keys(response.data).map(item => {
                    if (el.id == item) {
                        el.sn_code_list = response.data[item]
                        el.num = el.sn_code_list.length
                    }
                })
                if (!el.sn_code_list) {
                    el.sn_code_list = []
                }

            })
        })
        goodsInventoryAddForm.warehouse_id = res.data.warehouse_id;
        goodsInventoryAddForm.inventory_person_id = res.data.inventory_person_id;
        goodsInventoryAddForm.creator_id = res.data.creator_id;
        goodsInventoryAddForm.inventory_type = res.data.inventory_type;
        //goodsInventoryAddForm.inventory_time = res.data.inventory_time;
        goodsInventoryAddForm.type = res.data.type;
        goodsInventoryAddForm.product_list = res.data.product_list;
        console.log(goodsInventoryAddForm);
    } catch (error) {
        console.error("Failed to fetch order details:", error);
    }
}
/* 处理客户名称 */
const customerName = (value) => {
    if (value && customerList.value && customerList.value.data && customerList.value.data.data) {
        const type = customerList.value.data.data.find(type => type.id === value);
        return type ? type.name : '';
    }
}
/* 仓库名称 */
const warehouseName = (value) => {
    if (value && warehouseList.value) {
        const type = warehouseList.value.find(type => type.id === value);
        return type ? type.name : '';
    }
}
/* 支付列表*/
const collectingAccountName = (value) => {
    if (value && collectingAccountList.value && collectingAccountList.value.data && collectingAccountList.value.data.data) {
        const type = collectingAccountList.value.data.data.find(type => type.id === value);
        return type ? type.name : '';
    }
}
/* 盘点类型*/
const deliveryName = (value) => {
    if (value && typeList.value) {
        const type = typeList.value.find(type => type.id === value);
        return type ? type.label : '';
    }
}
/* 订单状态*/
const orderTypeName = (value) => {
    if (value && orderTypeList.value && orderTypeList.value.data && orderTypeList.value.data.data) {
        const type = orderTypeList.value.data.data.find(type => type.value === value);
        return type ? type.label : '';
    }
}
const getadminList = (value) => {
    if (value && adminList.value && adminList.value.data && adminList.value.data.data) {
        // Access orderTypeList directly from the component's data
        const type = adminList.value.data.data.find(type => type.id === value);
        return type ? type.real_name : '未知类型';
    }
}
/* 获取仓库,字典,客户信息 */
const getInforList = async () => {
    const warehouseData: any = await infoApi.warehouseList({})//获取仓库列表
    warehouseList.value = warehouseData.data
    customerList.value = await infoApi.customer({})//获取客户列表
    adminList.value = await infoApi.getAdmin({
        page_no: 1,
        page_size: 9999,
        user_state: 0
    })//获取管理员列表
    console.log(adminList);
    collectingAccountList.value = await infoApi.collectingAccount({})//获取支付方式列表
    const typeData: any = await dictionaryAPI.getPage({ dictType: "inventory_type" })//获取配送方式
    typeList.value = typeData.data.data
    orderTypeList.value = await dictionaryAPI.getPage({ dictType: "Sale_order_send_status" })//获取订单状态
}
</script>

<style scoped>
.text-center {
    text-align: center;
}

.my-4 {
    margin-top: 1rem;
    margin-bottom: 1rem;
}

.mx-auto {
    margin-left: auto;
    margin-right: auto;
}

.p-4 {
    padding: 1rem;
}
</style>