<template>
    <div class="p-4 bg-white dark:bg-[#0e1726]">
        <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-tabs v-model="activeTab" class="dark:bg-[#0e1726]">
            <el-tab-pane label="基本信息" name="basic-info">
                <div class="p-4">
                    <span>预约类型:</span>
                    <el-select v-model="shippingForm.appointment_type" clearable placeholder="Select" size="small"
                        style="width: 100px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <p class="mt-1 mb-1" v-if="shippingForm.appointment_type !== 0"><span>上门时间:</span>
                        <el-date-picker v-model="shippingForm.appointment_time" style="width: 170px" size="small"
                            type="datetime" placeholder="Select date and time" :default-time="defaultTime" />
                    </p>
                    <p>订单状态：{{ orderTypeName(shippingForm.order_vo.status) }}</p>
                    <p>订单类型：{{ shippingForm.order_vo.type == 'TO_B' ? '销售订单' : '租赁订单' }}</p>
                    <p>下单客户：{{ customerName(shippingForm.order_vo.member_id) }}</p>
                    <p>付款方式：{{ collectingAccountName(shippingForm.order_vo.pay_type) }}</p>
                    <p>实付金额：{{ shippingForm.order_vo.pay_price }}</p>
                    <p>仓库：{{ warehouseName(shippingForm.warehouse_id) }}</p>
                    <p>收货人：{{ shippingForm.order_vo.customer_name }}</p>
                    <p>联系电话：{{ shippingForm.order_vo.customer_phone }}</p>
                    <p>地址：{{ shippingForm.order_vo.province_city_area_address }}</p>
                    <p>商品总数:{{ good_total }}</p>
                    <p>客户备注：{{ shippingForm.order_vo.remark }}</p>
                    <p v-if="send_type !== 'EXPRESS_DELIVERY'">
                        <span v-if="shippingForm.order_vo.send_type !== 'SELF_PICKUP'">运单号：{{
                            shippingForm.kdn_order_code }}</span>
                        <span v-else>自提单号：{{ shippingForm.self_pickup_num }}</span>
                    </p>
                    <div v-else>
                        <p>
                            快递公司: <el-select v-model="params.logistics_type" clearable>
                                <el-option v-for="(item, index) in deliveryTypeList" :key="index" :label="item.name"
                                    :value="item.code"></el-option>
                            </el-select>
                        </p>
                        <p>
                            物流单号: <el-input v-model="params.logistics_code" :minlength="1" :maxlength="20"
                                placeholder="请输入物流单号"></el-input>
                        </p>
                        <p>
                            寄件人手机号: <el-input v-model="params.logistics_phone" :minlength="1" :maxlength="20"
                                placeholder="请输入寄件人手机号后四位"></el-input>
                        </p>
                    </div>
                    <p class="mt-1 mb-1">物品总重量:<el-input v-model.number="params.total_weight" size="small"
                            :minlength="1" style="width: 170px" :maxlength="20" type="number" max="50" clearable
                            placeholder="请输入物品总重量"><template #append>KG</template></el-input>
                    </p>
                    <p class="mt-1 mb-1">物品总体积: <el-input v-model="params.total_volume" ref="totalInput" size="small"
                            :minlength="1" style="width: 170px" :maxlength="20" clearable
                            placeholder="请输入物品总体积"><template #append>m³</template></el-input>
                    </p>
                    <p>物品价格: <el-input v-model="params.declared_value" size="small" :minlength="1" style="width: 170px"
                            :maxlength="20" clearable placeholder="请输入物品价格"><template #append>元</template></el-input>
                    </p>

                </div>
                <!-- <div class="p-4">
                    <p>3.12 快递已收货</p>
                    <p>3.13 快递已到达中转站</p>
                </div> -->
            </el-tab-pane>
            <el-tab-pane label="商品信息" name="product-info">
                <el-table :data="shippingForm.order_item_vos" style="width: 100%">
                    <el-table-column prop="goods_vo.name" label="商品名称" />
                    <el-table-column prop="product_vo.sku" label="SKU" />
                    <el-table-column prop="orderNum" label="订单数量" />
                    <el-table-column prop="num" label="出库数量">
                        <template #default="scope">
                            <span :style="{ color: scope.row.num > 0 ? 'red' : 'black' }">
                                {{ scope.row.num }}
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

        </el-tabs>
        <el-dialog v-model="dialogVisible" :modal=false title="扫码出库" :close-on-click-modal="false" top="80px"
            width="90%" style="height: 190px" :before-close="handleClose">
            <el-form :model="snCodeForm" label-width="auto" style="max-width: 600px">
                <el-form-item label="SKU">
                    <el-input class="hidden-input" v-model="snCodeForm.bar_code" @keyup.enter="toSearch()" clearable
                        :inputmode="inputmode" ref="inputRef">
                        <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" clearable :inputmode="inputmode" 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 pt-2 pb-2 mt-4 w-full fixed bottom-0 bg-white left-0 z-50 dark:bg-[#0e1726]"
            v-if="send_type !== 'EXPRESS_DELIVERY'">
            <el-button type="primary" size="large" @click="scanCode">扫码出库</el-button>
            <el-button type="primary" size="large"
                v-if="shippingForm.kdn_order_code == '' || shippingForm.kdn_order_code == undefined"
                @click="getOrderNumber">获取运单号</el-button>
            <div v-else class="pl-2">
                <el-button type="primary" v-if="activeTab == 'basic-info'" size="large" @click="ship">发货</el-button>
            </div>
        </div>
        <div class="flex justify-center pt-2 pb-2 mt-4 w-full fixed bottom-0 bg-white left-0 z-50" v-else>
            <el-button type="primary" size="large" @click="scanCode">扫码出库</el-button>
            <el-button type="primary" size="large" v-if="activeTab == 'basic-info'" @click="ship">发货</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, reactive, nextTick, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { orderApi, infoApi, dictionaryAPI } from '@/api/api'
import { regionData, codeToText } from 'element-china-area-data'
//引入
import Vue3Barcode from 'vue3-barcode'
//定义要生成条形码的值
import { ElMessage } 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('')
let inputmode = ref('text')
const router = useRouter();
const route = useRoute()
const activeTab = ref('product-info');
const id = ref(route.params.id);
const send_type = ref(route.params.send_type);
let shippingForm: any = ref({
    order_vo: {
        status: '',
        type: '',
        member_id: '',
        pay_type: '',
        pay_price: '',
        customer_name: '',
        customer_phone: '',
        province_city_area_address: '',
        remark: ''
    },
    warehouse_id: '',
    appointment_type: 0,
    order_item_vos: []
});
const options = [
    {
        label: "立即单",
        value: 0,
    },
    {
        label: "预约上门",
        value: 1,
    },
]
//表单
const snCodeForm = reactive({
    bar_code: "",
    sn_code: '',
})
const inputRef = ref();
const snInputRef = ref<any>(null)
const customerList: any = ref([])//初始化客户列表
const warehouseList: any = ref([])//初始化客户列表
const collectingAccountList: any = ref([])//初始化客户列表
const deliveryList: any = ref([])//初始化客户列表
const orderTypeList: any = ref([])//初始化客户列表
const index = ref(-1);
const deliveryTypeList: any = ref([])
const params: any = ref({
    logistics_type: "shunfeng",
    logistics_code: "",
    logistics_phone: "",
    send_type: '',
    selfPickupNum: '',
    remark: "",//备注
    declared_value: "",//物品价格
    appointment_type: 0,
    total_weight: "",//物品总重量
    total_volume: "",//物品总体积
    //发货人
    sender: {
        name: "",
        phone: "",
        address: "",
        province_city_area_address: ""
    },
    //收货人
    receiver: {
        name: "",
        phone: "",
        address: "",
        province_city_area_address: ""
    },
    //商品信息列表
    order_item_vos: [],
    goods_list: [],
    warehouse_id: '',
    goods_num: '',
})
let isReadOnly: any = ref(false)
let sku = ref('');
watch(activeTab, (newValue, oldValue) => {
    console.log(`Tab changed from ${oldValue} to ${newValue}`);
    // 这里可以添加一些逻辑，但要确保不会再次修改 activeTab
});
const toggleReadOnly = () => {
    isReadOnly = !isReadOnly;
};
const enableVirtualKeyboard = (event) => {
    event.target.readOnly = false;
};
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 {
        if (!snCodeForm.bar_code) {
            console.log('扫码枪输入为空，忽略此次事件');
            return;
        }
        const res: any = await orderApi.getProduct(
            shippingForm.value.warehouse_id,
            snCodeForm.bar_code.replace(/\s+/g, '')
        );
        res.data.sn_code_list = [];
        sku.value = res.data.product_vo.sku;

        let indexs = shippingForm.value.order_item_vos.findIndex(el => (
            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) {
            let existingProduct = shippingForm.value.order_item_vos.find(el => (
                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 (!existingProduct) {
                //ElMessageBox.error('订单内没有该商品，请重新录入');
                nextTick(() => {
                    inputRef.value.focus();
                });
                return;
            }
            index.value = shippingForm.value.order_item_vos.length;
            shippingForm.value.order_item_vos.push(res.data);
        } else {
            index.value = indexs;
        }

        if (res.data.product_vo.have_sn) {
            nextTick(() => {
                // Assuming there's a ref named snInputRef
                snInputRef.value.focus();
            });
        } else {
            if (shippingForm.value.order_item_vos[index.value].num >= shippingForm.value.order_item_vos[index.value].orderNum) return ElMessage.warning('出库数量不能大于订单数量!')
            shippingForm.value.order_item_vos[index.value].num += 1
            snCodeForm.bar_code = ''
            //dialogVisible.value = false;
        }
    } catch (error) {
        console.error('Error fetching product:', error);
        snCodeForm.bar_code = ''
    }
};
//扫描序列号
const toSnCode = async () => {
    if (!sku.value) return ElMessage.error('请先扫描sku!')
    try {
        const res: any = await orderApi.getsnCode(
            "out",
            sku.value,
            snCodeForm.sn_code.replace(/\s+/g, '')
        );

        snCodeForm.sn_code = "";
        const exists = shippingForm.value.order_item_vos[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: shippingForm.value.order_item_vos[index.value].id, sku: res.data }).then((respons: any) => {
                shippingForm.value.order_item_vos[index.value].sn_code_list.push(res.data);
            })
        }
        shippingForm.value.order_item_vos[index.value].num = shippingForm.value.order_item_vos[index.value].sn_code_list.length;
        const indexs = shippingForm.value.order_item_vos.findIndex(el => (
            el.goods_id === res.goods_id &&
            el.product_id === res.product_id &&
            el.product_vo.sku === res.sku
        ));

        //shippingForm.value.order_item_vos[index.value].id = shippingForm.value.order_item_vos[indexs].id;
        if (shippingForm.value.order_item_vos[index.value].num === shippingForm.value.order_item_vos[index.value].orderNum) {
            snCodeForm.bar_code = "";
            return ElMessage.warning('录入完成,请录入下一条!')
            /*   dialogVisible.value = false; */
        } else {
            snCodeForm.bar_code = "";
            nextTick(() => {
                inputRef.value.focus();
            });
        }
    } catch (error) {
        console.error('Error fetching SN code:', error);
    }
}

//关闭弹窗
const handleClose = (done: () => void) => {
    done()
}
onMounted(() => {
    console.log(send_type);
    init()
    getInforList()
});
const goBack = () => {
    router.push({ name: 'order' });
};
const scanCode = () => {
    dialogVisible.value = true
    nextTick(() => {
        if (inputRef.value) {
            try {
                inputRef.value.focus(); // 先尝试聚焦 input 元素
                setTimeout(() => {
                    if (inputRef.value) {
                        // 首先，让输入框失去焦点，这会阻止键盘的唤起
                        //inputRef.value.removeAttribute('readonly');
                        inputRef.value.focus();
                        inputmode.value = 'none'
                    }
                }, 100);
            } catch (error) {
                console.error('Failed to select input:', error);
            }
        }
    });
};

const getOrderNumber = () => {
    if (params.value.total_weigh == 0) return ElMessage.error('请输入物品总重量!')
    if (params.value.total_volume == 0) return ElMessage.error('请输入物品总体积!')
    //发货详细地址
    if (params.value.receiver.city_name === '市辖区') {
        params.value.receiver.city_name = params.value.receiver.province_name;
    }
    if (params.value.sender.city_name === '市辖区') {
        params.value.sender.city_name = params.value.sender.province_name;
    }
    params.value.receiver.province_city_area_address =
        params.value.receiver.province_name +
        params.value.receiver.city_name +
        params.value.receiver.area_name +
        params.value.receiver.address;
    //收货详细地址
    params.value.sender.province_city_area_address =
        params.value.sender.province_name +
        params.value.sender.city_name +
        params.value.sender.area_name +
        params.value.sender.address;
    /*  params.value.order_item_vos = shippingForm.value.order_item_vos */
    //商品信息
    const item = {
        goods_name: '',
        quantity: '',
        unit: ''
    };
    shippingForm.value.order_item_vos.map((el) => {
        item.goods_name = el.goods_vo.name;
        /* item.goods_price = el.product_vo.price; */
        item.quantity = el.orderNum;
        item.unit = el.product_vo.unit;
        return params.value.goods_list.push(item);
    });
    params.value.goods_num = shippingForm.value.order_item_vos.reduce(
        (sum, e) => sum + Number(e.orderNum || 0),
        0
    );
    if (shippingForm.appointment_type !== 0) {
        params.value.appointment_time = shippingForm.appointment_time
    }
    params.value.warehouse_id = shippingForm.value.warehouse_id
    params.value.send_type = send_type.value
    params.value.order_code = id.value

    /*console.log(shippingForm);
   //商品信息
   const item = {};
    shippingForm.order_item_vos.map((el) => {
      item.goods_name = el.goods_vo.name;
      item.quantity = el.orderNum;
      item.unit = el.product_vo.unit;
      return params.goods_list.push(item);
    });
    params.goods_num = this.product_list.reduce(
      (sum, e) => sum + Number(e.orderNum || 0),
      0
    );
    params.total_weight = Number(params.total_weight);
    params.total_volume = Number(params.total_volume);
    params.declared_value = Number(params.declared_value);
    //地址
    params.send_address = this.send_address;
    params.receive_address = this.receive_address;
    params.order_code = this.id; */
    orderApi.getkdShip(id.value, params.value).then(res => {
        init()
        location.reload();
    })
};

const ship = () => {
    if (send_type.value !== 'EXPRESS_DELIVERY') {

    } else {
        if (params.value.logistics_type == '') return ElMessage.error('请选择快递公司!')
        if (params.value.logistics_code == '') return ElMessage.error('请填写物流单号!')
        if (params.value.logistics_phone == '') return ElMessage.error('请输入寄件人手机号后四位!')
    }
    if (params.value.total_weigh == 0) return ElMessage.error('请输入物品总重量!')
    if (params.value.total_volume == 0) return ElMessage.error('请输入物品总体积!')
    //发货详细地址
    params.value.receiver.province_city_area_address =
        params.value.receiver.province_name +
        params.value.receiver.city_name +
        params.value.receiver.area_name +
        params.value.receiver.address;
    //收货详细地址
    params.value.sender.province_city_area_address =
        params.value.sender.province_name +
        params.value.sender.city_name +
        params.value.sender.area_name +
        params.value.sender.address;
    params.value.order_item_vos = shippingForm.value.order_item_vos
    if (shippingForm.appointment_type !== 0) {
        params.value.appointment_time = shippingForm.appointment_time
    }
    const item = {
        goods_name: "",
        quantity: '',
        unit: "",
    };
    params.value.goods_list.map((el) => {
        item.goods_name = el.goods_vo.name;
        item.quantity = el.num;
        item.unit = el.product_vo.unit;
        return params.value.goods_list.push(item);
    });
    orderApi.orderSend(id.value, params.value).then(res => {
        ElMessage.success("发货成功！");
        router.push({ name: 'order' });
    })
    orderApi.queryLogistics({ shipper_code: params.value.logistics_type, logistic_code: params.value.logistics_code, customer_name: params.value.logistics_phone }).then(res => {
        console.log(res);
    })

};
const kdsShip = () => {

}
/* 商品总数 */
let good_total = 0
const init = async () => {
    try {
        const res: any = await orderApi.getSendOrderDetail(id.value);
        if (res && res.data && res.data.order_vo && res.data.order_vo.sn) {
            await infoApi.skuRedis({ send_order_id: id.value, type: 'enter' }).then((response: any) => {
                res.data.order_item_vos.map((el: any) => {
                    params.value.total_weight = Number(
                        el.product_vo.weight * el.num
                    );
                    if (params.value.total_weight == 0) {
                        params.value.total_weight = 1
                    }

                    el.orderNum = el.num
                    if (res.data.kdn_order_code == undefined || res.data.kdn_order_code == '') {
                        el.num = 0
                    }
                    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 = []
                    } else {
                        /* el.num = el.sn_code_list.length */
                    }
                })
            })
            barcodeValue.value = res.data.order_vo.sn;
            //物品价格
            if (res.data.total_volume !== undefined && res.data.total_volume !== 0) {
                params.value.total_volume = Number(res.data.total_volume)
            } else {

                params.value.total_volume = 0.01
            }

            params.value.declared_value = Number(res.data.order_vo.real_price)
            res.data.appointment_type = 0
            /* 发货人地址 */
            const addressLiat = res.data.warehouse_vo.ware_pro_city_area.split(",")
            params.value.sender.name = res.data.warehouse_vo.user_name;
            params.value.sender.phone = res.data.warehouse_vo.phone;
            params.value.sender.province_name = codeToText[addressLiat[0]]
            params.value.sender.city_name = codeToText[addressLiat[1]]
            params.value.sender.area_name = codeToText[addressLiat[2]]
            params.value.sender.address = res.data.warehouse_vo.warehouse_address;
            /* 收货地址 */
            const receiverList = res.data.order_vo.province_city_area.split(",")
            params.value.receiver.name = res.data.order_vo.customer_name;
            params.value.receiver.phone = res.data.order_vo.customer_phone;
            params.value.receiver.province_name = codeToText[receiverList[0]];
            params.value.receiver.city_name = codeToText[receiverList[1]];
            params.value.receiver.area_name = codeToText[receiverList[2]];
            params.value.receiver.address = res.data.order_vo.address;
            shippingForm.value = res.data;
            res.data.order_item_vos.map(el => {
                good_total += el.orderNum
            })
            console.log(good_total);
            console.log("Barcode value set to:", shippingForm);
        } else {
            console.error("Invalid response structure:", res);
        }
    } 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 && deliveryList.value && deliveryList.value.data && deliveryList.value.data.data) {
        const type = deliveryList.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 () => {
    warehouseList.value = await infoApi.warehouseList({})//获取仓库列表
    customerList.value = await infoApi.customer({})//获取客户列表
    collectingAccountList.value = await infoApi.collectingAccount({})//获取支付方式列表
    deliveryList.value = await dictionaryAPI.getPage({ dictType: "order_send_type" })//获取配送方式
    orderTypeList.value = await dictionaryAPI.getPage({ dictType: "Sale_order_send_status" })//获取订单状态
    const expressList: any = await infoApi.getExpressList({//获取物流公司
        page_no: 1,
        page_size: 9999,
    })
    deliveryTypeList.value = expressList.data.data
}
</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;
}

.hidden-input .el-input__inner {
    width: 0;
    padding: 0;
}
</style>