<template>
    <el-dialog v-model="data.dialogVisible" title="创建订单" :before-close="handleClose" width="600px">
        <el-form ref="formDataRef" :model="ruleForm" :rules="rules" label-width="120px">
            <el-form-item label="卖方" prop="sellerId">
                <el-select
                    v-model="ruleForm.sellerId"
                    clearable
                    filterable
                    remote
                    :remote-method="sellerRemoteMethod"
                    :loading="data.sellerLoading"
                    placeholder="请选择卖方"
                    style="width: 100%"
                >
                    <el-option
                        v-for="item in data.sellerOptions"
                        :key="item.id"
                        :label="item.username + ' / ' + item.mobile + ' (' + item.tenantName + ')'"
                        :value="item.id"
                    >
                    </el-option>
                    <el-pagination
                        style="padding: 0px 20px"
                        @current-change="sellerHandleCurrentChange"
                        :page-size="10"
                        :current-page="data.sellerPageNum"
                        layout="total, prev, pager, next"
                        :total="data.sellerTotal"
                    >
                    </el-pagination>
                </el-select>
            </el-form-item>
            
            <el-form-item label="买方" prop="buyerId">
                <el-select
                    v-model="ruleForm.buyerId"
                    clearable
                    filterable
                    remote
                    :remote-method="buyerRemoteMethod"
                    :loading="data.buyerLoading"
                    placeholder="请选择买方"
                    style="width: 100%"
                >
                    <el-option
                        v-for="item in data.buyerOptions"
                        :key="item.id"
                        :label="item.username + ' / ' + item.mobile + ' (' + item.tenantName + ')'"
                        :value="item.id"
                    >
                    </el-option>
                    <el-pagination
                        style="padding: 0px 20px"
                        @current-change="buyerHandleCurrentChange"
                        :page-size="10"
                        :current-page="data.buyerPageNum"
                        layout="total, prev, pager, next"
                        :total="data.buyerTotal"
                    >
                    </el-pagination>
                </el-select>
            </el-form-item>
            
            <el-form-item label="结算方式" prop="settlementType">
                <el-select v-model="ruleForm.settlementType" placeholder="请选择结算方式" style="width: 100%">
                    <el-option label="上车重量" :value="1"></el-option>
                    <el-option label="下车重量" :value="2"></el-option>
                    <el-option label="按肉价结算" :value="3"></el-option>
                </el-select>
            </el-form-item>
            
            <el-form-item label="约定价格(元/斤)" prop="firmPrice">
                <el-input-number
                    v-model="ruleForm.firmPrice"
                    :precision="2"
                    :min="0"
                    :max="9999999.99"
                    placeholder="请输入约定价格"
                    style="width: 100%"
                ></el-input-number>
            </el-form-item>
        </el-form>
        
        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="data.saveLoading" type="primary" @click="onClickSave">保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { orderAddNew, orderUpdate } from '@/api/shipping.js';
import { memberListByType } from '@/api/userManage.js';

const emits = defineEmits();
const formDataRef = ref(null);

const data = reactive({
    dialogVisible: false,
    saveLoading: false,
    sellerOptions: [],
    buyerOptions: [],
    sellerLoading: false,
    sellerPageNum: 1,
    sellerTotal: 0,
    sellerName: '',
    buyerLoading: false,
    buyerPageNum: 1,
    buyerTotal: 0,
    buyerName: '',
});

const ruleForm = reactive({
    id: null, // 订单ID（编辑时使用）
    buyerId: null, // 买方ID（单选）
    sellerId: null, // 卖方ID（单选）
    settlementType: 1, // 结算方式：1-上车重量，2-下车重量，3-按肉价结算
    firmPrice: null, // 约定价格（元/斤）
});

// 验证买方和卖方不能是同一用户
const validateBuyerSeller = (rule, value, callback) => {
    if (value && value === ruleForm.sellerId) {
        callback(new Error('买方和卖方不能是同一用户'));
    } else {
        callback();
    }
};

const validateSellerBuyer = (rule, value, callback) => {
    if (value && value === ruleForm.buyerId) {
        callback(new Error('卖方和买方不能是同一用户'));
    } else {
        callback();
    }
};

const rules = reactive({
    buyerId: [
        { required: true, message: '请选择买方', trigger: 'change' },
        { validator: validateBuyerSeller, trigger: 'change' }
    ],
    sellerId: [
        { required: true, message: '请选择卖方', trigger: 'change' },
        { validator: validateSellerBuyer, trigger: 'change' }
    ],
    settlementType: [{ required: true, message: '请选择结算方式', trigger: 'change' }],
    firmPrice: [
        { required: true, message: '请输入约定价格', trigger: 'blur' },
        { type: 'number', min: 0, message: '约定价格不能小于0', trigger: 'blur' }
    ],
});

const handleClose = () => {
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    // 重置表单数据
    ruleForm.id = null;
    ruleForm.buyerId = null;
    ruleForm.sellerId = null;
    ruleForm.settlementType = 1;
    ruleForm.firmPrice = null;
    data.dialogVisible = false;
};

// ----------------
// 卖方远程搜索（同时查询 type=2 和 type=4）
const sellerRemoteMethod = (e) => {
    data.sellerName = e;
    data.sellerPageNum = 1;
    getSellerList();
};

// 卖方列表（合并 type=2 和 type=4 的用户）
const getSellerList = () => {
    data.sellerLoading = true;
    const searchName = data.sellerName || '';
    
    // 同时查询供应商（type=2）和采购商（type=4）
    Promise.all([
        memberListByType({
            pageNum: data.sellerPageNum,
            pageSize: 10,
            type: 2,
            username: searchName,
        }),
        memberListByType({
            pageNum: data.sellerPageNum,
            pageSize: 10,
            type: 4,
            username: searchName,
        })
    ])
        .then(([supplierRes, purchaserRes]) => {
            // 合并结果并去重（根据 id）
            const supplierList = supplierRes.data.rows || [];
            const purchaserList = purchaserRes.data.rows || [];
            const mergedList = [...supplierList, ...purchaserList];
            
            // 去重：使用 Map 根据 id 去重
            const uniqueMap = new Map();
            mergedList.forEach(item => {
                if (!uniqueMap.has(item.id)) {
                    uniqueMap.set(item.id, item);
                }
            });
            data.sellerOptions = Array.from(uniqueMap.values());
            
            // 总数取两个查询的总和（实际可能包含重复，但用于分页显示）
            data.sellerTotal = (supplierRes.data.total || 0) + (purchaserRes.data.total || 0);
            data.sellerLoading = false;
        })
        .catch(() => {
            data.sellerLoading = false;
        });
};

// 卖方分页
const sellerHandleCurrentChange = (val) => {
    data.sellerPageNum = val;
    getSellerList();
};

// ----------------
// 买方远程搜索（同时查询 type=2 和 type=4）
const buyerRemoteMethod = (e) => {
    data.buyerName = e;
    data.buyerPageNum = 1;
    getBuyerList();
};

// 买方列表（合并 type=2 和 type=4 的用户）
const getBuyerList = () => {
    data.buyerLoading = true;
    const searchName = data.buyerName || '';
    
    // 同时查询供应商（type=2）和采购商（type=4）
    Promise.all([
        memberListByType({
            pageNum: data.buyerPageNum,
            pageSize: 10,
            type: 2,
            username: searchName,
        }),
        memberListByType({
            pageNum: data.buyerPageNum,
            pageSize: 10,
            type: 4,
            username: searchName,
        })
    ])
        .then(([supplierRes, purchaserRes]) => {
            // 合并结果并去重（根据 id）
            const supplierList = supplierRes.data.rows || [];
            const purchaserList = purchaserRes.data.rows || [];
            const mergedList = [...supplierList, ...purchaserList];
            
            // 去重：使用 Map 根据 id 去重
            const uniqueMap = new Map();
            mergedList.forEach(item => {
                if (!uniqueMap.has(item.id)) {
                    uniqueMap.set(item.id, item);
                }
            });
            data.buyerOptions = Array.from(uniqueMap.values());
            
            // 总数取两个查询的总和（实际可能包含重复，但用于分页显示）
            data.buyerTotal = (supplierRes.data.total || 0) + (purchaserRes.data.total || 0);
            data.buyerLoading = false;
        })
        .catch(() => {
            data.buyerLoading = false;
        });
};

// 买方分页
const buyerHandleCurrentChange = (val) => {
    data.buyerPageNum = val;
    getBuyerList();
};

// 保存
const onClickSave = () => {
    if (formDataRef.value) {
        formDataRef.value.validate((valid) => {
            if (valid) {
                const params = {
                    id: ruleForm.id,
                    buyerId: ruleForm.buyerId ? String(ruleForm.buyerId) : '', // 转为字符串格式（后端可能期望字符串）
                    sellerId: ruleForm.sellerId ? String(ruleForm.sellerId) : '', // 转为字符串格式
                    settlementType: ruleForm.settlementType,
                    firmPrice: ruleForm.firmPrice, // 约定价格（元/斤）
                };
                
                data.saveLoading = true;
                
                // 根据是否有ID判断是新增还是编辑
                const savePromise = ruleForm.id ? orderUpdate(params) : orderAddNew(params);
                
                savePromise.then((res) => {
                    data.saveLoading = false;
                    if (res.code === 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        });
                        emits('success');
                        handleClose();
                    } else {
                        ElMessage.error(res.msg);
                    }
                })
                .catch((err) => {
                    data.saveLoading = false;
                });
            } else {

            }
        });
    }
};

const onShowDialog = (orderData) => {
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    
    // 重置表单数据
    ruleForm.id = orderData?.id || null;
    
    // 处理buyerId：支持字符串、数组和数字格式，取第一个值（单选模式）
    if (orderData?.buyerId) {
        if (typeof orderData.buyerId === 'number') {
            ruleForm.buyerId = orderData.buyerId;
        } else if (Array.isArray(orderData.buyerId) && orderData.buyerId.length > 0) {
            ruleForm.buyerId = parseInt(orderData.buyerId[0]);
        } else if (typeof orderData.buyerId === 'string' && orderData.buyerId.trim() !== '') {
            const ids = orderData.buyerId.split(',').map(id => id.trim()).filter(id => id !== '');
            ruleForm.buyerId = ids.length > 0 ? parseInt(ids[0]) : null;
        } else {
            ruleForm.buyerId = null;
        }
    } else {
        ruleForm.buyerId = null;
    }
    
    // 处理sellerId：支持字符串、数组和数字格式，取第一个值（单选模式）
    if (orderData?.sellerId) {
        if (typeof orderData.sellerId === 'number') {
            ruleForm.sellerId = orderData.sellerId;
        } else if (Array.isArray(orderData.sellerId) && orderData.sellerId.length > 0) {
            ruleForm.sellerId = parseInt(orderData.sellerId[0]);
        } else if (typeof orderData.sellerId === 'string' && orderData.sellerId.trim() !== '') {
            const ids = orderData.sellerId.split(',').map(id => id.trim()).filter(id => id !== '');
            ruleForm.sellerId = ids.length > 0 ? parseInt(ids[0]) : null;
        } else {
            ruleForm.sellerId = null;
        }
    } else {
        ruleForm.sellerId = null;
    }
    
    ruleForm.settlementType = orderData?.settlementType || 1;
    ruleForm.firmPrice = orderData?.firmPrice != null ? orderData.firmPrice : null;
    
    data.dialogVisible = true;
    // 初始化时加载列表
    getSellerList();
    getBuyerList();
};

defineExpose({
    onShowDialog,
});
</script>

<style lang="less" scoped>
::v-deep .el-select-dropdown__list {
    padding-bottom: 40px;
}
</style>
