<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="supplierRemoteMethod"
                    :loading="data.supplierLoading"
                    placeholder="请选择卖方"
                    style="width: 100%"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    :max-collapse-tags="2"
                >
                    <el-option
                        v-for="item in data.supplierOptions"
                        :key="item.id"
                        :label="item.username + ' / ' + item.mobile + ' (' + item.tenantName + ')'"
                        :value="item.id"
                    >
                    </el-option>
                    <el-pagination
                        style="padding: 0px 20px"
                        @current-change="supplierHandleCurrentChange"
                        :page-size="10"
                        :current-page="data.supplierPageNum"
                        layout="total, prev, pager, next"
                        :total="data.supplierTotal"
                    >
                    </el-pagination>
                </el-select>
            </el-form-item>
            
            <el-form-item label="买方" prop="buyerId">
                <el-select
                    v-model="ruleForm.buyerId"
                    clearable
                    filterable
                    remote
                    :remote-method="purchaserRemoteMethod"
                    :loading="data.purchaserLoading"
                    placeholder="请选择买方"
                    style="width: 100%"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    :max-collapse-tags="2"
                >
                    <el-option
                        v-for="item in data.purchaserOptions"
                        :key="item.id"
                        :label="item.username + ' / ' + item.mobile + ' (' + item.tenantName + ')'"
                        :value="item.id"
                    >
                    </el-option>
                    <el-pagination
                        style="padding: 0px 20px"
                        @current-change="purchaserHandleCurrentChange"
                        :page-size="10"
                        :current-page="data.purchaserPageNum"
                        layout="total, prev, pager, next"
                        :total="data.purchaserTotal"
                    >
                    </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>
        
        <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 { 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,
    supplierOptions: [],
    purchaserOptions: [],
    driverLoading: false,
    driverName: '',
    driverPageNum: 1,
    driverTotal: 0,
    purchaserLoading: false,
    purchaserPageNum: 1,
    purchaserTotal: 0,
    purchaserName: '',
    supplierLoading: false,
    supplierPageNum: 1,
    supplierTotal: 0,
    supplierName: '',
});

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

const rules = reactive({
    buyerId: [{ required: true, message: '请选择买方', trigger: 'change' }],
    sellerId: [{ required: true, message: '请选择卖方', trigger: 'change' }],
    settlementType: [{ required: true, message: '请选择结算方式', trigger: 'change' }],
});

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

// ----------------
// 供应商远程搜索
const supplierRemoteMethod = (e) => {
    data.supplierName = e;
    data.supplierPageNum = 1;
    getSupplierList();
};

// 供应商 列表
const getSupplierList = () => {
    data.supplierLoading = true;
    const params = {
        pageNum: data.supplierPageNum,
        pageSize: 10,
        type: 2, // 供应商类型
        username: data.supplierName,
    };
    memberListByType(params)
        .then((res) => {
            data.supplierLoading = false;
            data.supplierOptions = res.data.rows;
            data.supplierTotal = res.data.total;
        })
        .catch(() => {
            data.supplierLoading = false;
        });
};

// 选择供应商分页
const supplierHandleCurrentChange = (val) => {
    data.supplierPageNum = val;
    getSupplierList();
};

// ----------------
// 采购商远程搜索
const purchaserRemoteMethod = (e) => {
    data.purchaserName = e;
    data.purchaserPageNum = 1;
    getPurchaserList();
};

// 采购商 列表
const getPurchaserList = () => {
    data.purchaserLoading = true;
    const params = {
        pageNum: data.purchaserPageNum,
        pageSize: 10,
        type: 4, // 采购商类型
        username: data.purchaserName,
    };
    memberListByType(params)
        .then((res) => {
            data.purchaserLoading = false;
            data.purchaserOptions = res.data.rows;
            data.purchaserTotal = res.data.total;
        })
        .catch(() => {
            data.purchaserLoading = false;
        });
};

// 采购商分页
const purchaserHandleCurrentChange = (val) => {
    data.purchaserPageNum = val;
    getPurchaserList();
};

// 保存
const onClickSave = () => {
    if (formDataRef.value) {
        formDataRef.value.validate((valid) => {
            if (valid) {
                const params = {
                    id: ruleForm.id,
                    buyerId: ruleForm.buyerId.join(','), // 将数组转为逗号分隔的字符串
                    sellerId: ruleForm.sellerId.join(','), // 将数组转为逗号分隔的字符串
                    settlementType: ruleForm.settlementType,
                };
                
                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 (Array.isArray(orderData.buyerId)) {
            ruleForm.buyerId = orderData.buyerId;
        } else if (typeof orderData.buyerId === 'string' && orderData.buyerId.trim() !== '') {
            ruleForm.buyerId = orderData.buyerId.split(',').map(id => id.trim()).filter(id => id !== '');
        } else {
            ruleForm.buyerId = [];
        }
    } else {
        ruleForm.buyerId = [];
    }
    
    // 处理sellerId：支持字符串和数组两种格式
    if (orderData?.sellerId) {
        if (Array.isArray(orderData.sellerId)) {
            ruleForm.sellerId = orderData.sellerId;
        } else if (typeof orderData.sellerId === 'string' && orderData.sellerId.trim() !== '') {
            ruleForm.sellerId = orderData.sellerId.split(',').map(id => id.trim()).filter(id => id !== '');
        } else {
            ruleForm.sellerId = [];
        }
    } else {
        ruleForm.sellerId = [];
    }
    
    ruleForm.settlementType = orderData?.settlementType || 1;
    
    data.dialogVisible = true;
    getSupplierList();
    getPurchaserList();
};

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

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