<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="goodsExchangeAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
            style="max-width: 600px">
            <el-form-item prop="warehouse_id" label="入库仓库" class="change-form-item">

                <el-select v-model="goodsExchangeAddForm.warehouse_id" clearable>
                    <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="类型" prop="type" class="change-form-item">
                <el-select v-model="goodsExchangeAddForm.type" filterable allow-create clearable default-first-option
                    :disabled="goodsExchangeAddForm.type == 'SALE_AFTER' || goodsExchangeAddForm.type == 'HAIL_ENTRY'">
                    <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.value"
                        :disabled="item.value == 'TRANSFER_ENTRY' || item.value == 'HAIL_ENTRY' || item.value == 'SALE_AFTER'" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="change_desc" class="change-form-item" style="width: 100%">
                <el-input style="flex: 1" v-model="goodsExchangeAddForm.memo" type="textarea"
                    :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入"></el-input>
            </el-form-item>
            <el-button type="primary" size="large" @click="scanCode">扫码入库</el-button>
            <el-table :data="goodsExchangeAddForm.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="num" label="入库数量" />
                <el-table-column prop="orderNum" label="待入库数量" />
            </el-table>
        </el-form>
        <el-dialog v-model="dialogVisible" :modal=false title="扫码入库" :close-on-click-modal="false" width="80%"
            :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" @keyup.enter="toSearch()" />
                </el-form-item>
                <el-form-item label="序列号">
                    <el-input v-model="snCodeForm.sn_code" ref="snInputRef" @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="save(ruleFormRef)">保存</el-button>
            <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, entryOutAPI } from '@/api/api'
//引入
import Vue3Barcode from 'vue3-barcode'
//定义要生成条形码的值
import { ElMessage, FormRules, FormInstance } from 'element-plus'
const appointment_time = ref('')
const defaultTime = new Date(2000, 1, 1, 12, 0, 0)
let dialogVisible = ref(false)
const tableData = ref([])
let barcodeValue = ref('')
const router = useRouter();
const route = useRoute()
const activeTab = ref('basic-info');
const id = ref(route.params.id);
const goodsExchangeAddForm: any = reactive({
    warehouse_id: '',
    type: '',
    memo: '',
    product_list: []
})
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('');
watch(activeTab, (newValue, oldValue) => {
    console.log(`Tab changed from ${oldValue} to ${newValue}`);
    // 这里可以添加一些逻辑，但要确保不会再次修改 activeTab
});

/* 扫sku */
const toSearch = async () => {
    activeTab.value = 'product-info'
    try {
        const res: any = await orderApi.getProduct(
            goodsExchangeAddForm.warehouse_id,
            snCodeForm.bar_code.replace(/\s+/g, '')
        );
        res.data.sn_code_list = [];
        sku.value = res.data.product_vo.sku;
        // 查找当前商品是否已存在于列表中
        const indexs = goodsExchangeAddForm.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 = goodsExchangeAddForm.product_list.length;
            goodsExchangeAddForm.product_list.push(res.data);
            console.log(goodsExchangeAddForm.product_list);
        } else {
            index.value = indexs;
        }
        if (res.data.product_vo.have_sn) {
            nextTick(() => {
                snInputRef.value.focus();
            });
        } else {
            /* this.scanDialogVisible = false; */
        }
    } catch (error) {
        console.error('Error fetching product:', error);
    }
};
//扫描序列号
const toSnCode = async () => {
    try {
        const res: any = await orderApi.getsnCode(
            "in",
            sku.value,
            snCodeForm.sn_code.replace(/\s+/g, '')
        );

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

        if (!exists) {
            goodsExchangeAddForm.product_list[index.value].sn_code_list.push(res.data);
        }
        goodsExchangeAddForm.product_list[index.value].num = goodsExchangeAddForm.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: 'InoutStorage' });
};

const scanCode = () => {
    dialogVisible.value = true
    nextTick(() => {
        if (inputRef.value) {
            try {
                inputRef.value.focus(); // 先尝试聚焦 input 元素
                setTimeout(() => {
                    if (inputRef.value) {
                        inputRef.value.select();
                    }
                }, 100);
            } catch (error) {
                console.error('Failed to select input:', error);
            }
        }
    });
};
//入库
const getOrderNumber = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (!goodsExchangeAddForm.product_list.length) {
                ElMessage.error("请选择商品！");
                return;
            }
            goodsExchangeAddForm.save_or_submit = "submit"
            goodsExchangeAddForm.product_list.map((el) => {
                el.product_stock_id = el.id;
                el.product_id = el.product_vo.id;
                el.id = "";
            });
            entryOutAPI.addWarehouseEntry(id.value,goodsExchangeAddForm).then(res => {
                ElMessage.success("入库成功！");
                router.replace({
                    name: 'InoutStorage',
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};
//保存
const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (!goodsExchangeAddForm.product_list.length) {
                ElMessage.error("请选择商品！");
                return;
            }
            goodsExchangeAddForm.save_or_submit = "save"
            goodsExchangeAddForm.product_list.map((el) => {
                el.product_stock_id = el.id;
                el.product_id = el.product_vo.id;
                el.id = "";
            });
            entryOutAPI.addWarehouseEntry(id.value,goodsExchangeAddForm).then(res => {
                ElMessage.success("保存成功！");
                router.replace({
                    name: 'InoutStorage',
                });
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};
const ship = () => {
    console.log('发货');
};
const init = async () => {
    try {
        const res: any = await entryOutAPI.warehouseEntry(id.value);
        res.data.product_list.map(el => {
            el.orderNum = el.num
            el.num=0
            el.sn_code_list = []
        })
        goodsExchangeAddForm.warehouse_id = res.data.warehouse_id;
        goodsExchangeAddForm.type = res.data.type;
        goodsExchangeAddForm.memo = res.data.memo;
        goodsExchangeAddForm.product_list = res.data.product_list;
        console.log(goodsExchangeAddForm);
    } 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 && warehouseList.value.data) {
        const type = warehouseList.value.data.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 && typeList.value.data && typeList.value.data.data) {
        const type = typeList.value.data.data.find(type => type.value === 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 getInforList = async () => {
    const warehouseData: any = await infoApi.warehouseList({})//获取仓库列表
    warehouseList.value = warehouseData.data
    customerList.value = await infoApi.customer({})//获取客户列表
    collectingAccountList.value = await infoApi.collectingAccount({})//获取支付方式列表
    const typeData: any = await dictionaryAPI.getPage({ dictType: "warehouse_entry_type" })//获取配送方式
    typeList.value = typeData.data.data
    console.log(typeList.value);
    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>