<template>
    <div>
        <el-form label-position="left" ref="assistForm" :model="assistForm"  label-width="120px" v-if="!flag">
            <el-form-item label="未添加协作客户" >
                <span>{{this.noAssistCount}}个</span>
            </el-form-item>
            <el-form-item label="未添加协作客户" >
                <span>{{this.assistCount}}个</span>
            </el-form-item>

            <el-form-item label="协作人" prop="users" label-width="60px">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button @click="handleUserSelect">添加协作人</el-button>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item  label-width="0">
                <el-table border  :data="users">
                    <el-table-column label="ID" align="center" prop="userId"/>
                    <el-table-column label="员工帐号" align="center" prop="userName" width="100px"/>
                    <el-table-column label="员工姓名" align="center" prop="nickName" />
                    <el-table-column label="所属部门" align="center" prop="deptName"/>
                    <el-table-column label="添加数量" align="center"  prop="count" width="150px" v-if="!flag">
                        <template slot-scope="scope">
                            <div>
                                <el-input-number ref="stepTxtNum" :min="0" v-model="scope.row.count"  @change="changeVal(scope.row)"   size="mini"   ></el-input-number>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作"   align="center" fixed="right"  width="60px" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button
                            size="mini"
                            type="text"
                            @click="handleRemoveUser(scope.row.$index)"
                            >删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>
        <div   class="footer" v-if="!flag">
            <el-button type="primary" @click="submitAssistForm">确 定</el-button>
        </div>
        <el-dialog :title="userSelect.title" :visible.sync="userSelect.open" width="1000px" append-to-body>
            <user-select ref="userSelects" @selectUser="selectUser"  ></user-select>
        </el-dialog>

        <!-- 手动分佣模式 -->
        <el-form label-position="left" ref="assistForm2" :model="assistForm2"  label-width="120px" v-if="flag">
            <el-form-item  label-width="0">
                <div v-for="(customer, customerIndex) in customers" :key="customer.customerId || customerIndex" class="customer-section">
                    <el-card class="customer-card" shadow="hover">
                        <div slot="header" class="customer-header">
                            <span class="customer-title">
                                <strong>{{ customer.customerName }}</strong>
                                <span class="customer-code">({{ customer.customerCode }})</span>
                            </span>
                            <el-button
                                size="mini"
                                type="primary"
                                @click="handleAddCollaborator(customerIndex)"
                                icon="el-icon-plus">
                                添加协作人
                            </el-button>
                        </div>

                        <div class="collaborator-content">
                            <el-table
                                :data="customer.collaborators"
                                border
                                size="small"
                                v-if="customer.collaborators && customer.collaborators.length > 0">
                                <el-table-column label="员工姓名" align="center" prop="companyUserName" width="100px"/>
                                <el-table-column label="员工ID" align="center" prop="companyUserId" width="80px"/>
                                <el-table-column label="分佣比例(%)" align="center" width="160px">
                                    <template slot-scope="scope">
                                        <el-input-number
                                            v-model="scope.row.rate"
                                            :min="0"
                                            :max="100"
                                            size="mini"
                                            @input="handleRateChange(customerIndex, scope.$index, scope.row)">
                                        </el-input-number>
                                    </template>
                                </el-table-column>
                                <el-table-column label="状态" align="center" width="80px">
                                    <template slot-scope="scope">
                                        <el-tag :type="scope.row.isNew ? 'success' : 'info'" size="mini">
                                            {{ scope.row.isNew ? '新增' : '原有' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" align="center" width="80px">
                                    <template slot-scope="scope">
                                        <el-button
                                            size="mini"
                                            type="text"
                                            @click="handleRemoveCollaborator(customerIndex, scope.$index)">
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <div v-else class="no-collaborator">
                                <i class="el-icon-user" style="font-size: 48px; color: #ddd;"></i>
                                <p>暂无协作人员</p>
                            </div>

                            <!-- 分佣比例汇总 -->
                            <div class="rate-summary-container">
                                <div class="rate-summary">
                                    <div class="rate-item">
                                        <span class="rate-label">协作人员总分佣比例:</span>
                                        <span :class="getTotalRateClass(customerIndex)">
                                            {{ getTotalRate(customerIndex) }}%
                                        </span>
                                        <span v-if="getTotalRate(customerIndex) > 100" class="rate-warning">
                                            (超出100%，请调整)
                                        </span>
                                    </div>
                                    <div class="rate-item owner-rate">
                                        <span class="rate-label">本人佣金比例:</span>
                                        <span :class="getOwnerRateClass(customerIndex)">
                                            {{ getOwnerRate(customerIndex) }}%
                                        </span>
                                        <span v-if="getOwnerRate(customerIndex) < 0" class="rate-warning">
                                            (协作人员分佣超出100%，请调整)
                                        </span>
                                    </div>
                                    <div class="rate-item total-check" v-if="customer.collaborators && customer.collaborators.length > 0">
                                        <span class="rate-label">总计:</span>
                                        <span class="rate-total">
                                            {{ getTotalRate(customerIndex) + getOwnerRate(customerIndex) }}%
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-card>
                </div>
            </el-form-item>
        </el-form>

        <div class="footer" v-if="flag">
            <el-button @click="$emit('close')">取 消</el-button>
            <el-button type="primary" @click="submitAssistForm2" :loading="submitLoading">确 定</el-button>
        </div>
    </div>
</template>

<script>
import { assistToUser,selectByCustomerIds,allOperation } from "@/api/crm/customer";
import userSelect from '../../company/components/userSelect.vue';
export default {
    components: {userSelect },
    name: "visit",
    data() {
        return {
            originalCollaborators: {}, // 确保初始化为空对象
            flag:false,
            noAssistCount:0,
            assistCount:0,
            customerIds:[],
            currentCustomerIndex: -1,
            submitLoading: false,
            userSelect:{
                title:"选择员工",
                open:false,
            },
            assistForm: {
            },
            assistForm2:{},
            // 表单校验
            assistRules: {

            },
            users:[],
            customers:[]

        };
    },
    created() {

    },
    methods: {
         // 检查并更新所有协作者的操作状态
         checkAndUpdateOperations() {
            // 确保 originalCollaborators 存在
            if (!this.originalCollaborators) {
                this.originalCollaborators = {};
            }
            this.customers.forEach(customer => {
                if (customer.collaborators) {
                    customer.collaborators.forEach(collaborator => {
                        if (collaborator.id && (!collaborator.operation || collaborator.operation === 'NONE')) {
                            const originalKey = `${collaborator.customerId}_${collaborator.companyUserId}`;
                            const originalCollaborator = this.originalCollaborators[originalKey];

                            if (originalCollaborator &&
                                (originalCollaborator.rate !== collaborator.rate ||
                                 originalCollaborator.remark !== (collaborator.remark || ''))) {
                                collaborator.operation = 'UPDATE';
                            } else if (!originalCollaborator && collaborator.id) {
                                // 如果找不到原始数据但有ID，说明可能是数据加载问题，标记为UPDATE
                                collaborator.operation = 'UPDATE';
                            }
                        }
                    });
                }
            });
        },
         // 处理分佣比例变化
         handleRateChange(customerIndex, collaboratorIndex, collaborator) {
            // 确保 originalCollaborators 存在
            if (!this.originalCollaborators) {
                this.originalCollaborators = {};
            }
            // 如果是原有协作者且分佣比例发生变化，标记为UPDATE
            if (collaborator.operation === 'NONE' || !collaborator.operation) {
                const originalKey = `${collaborator.customerId}_${collaborator.companyUserId}`;
                const originalCollaborator = this.originalCollaborators[originalKey];



                if (originalCollaborator) {
                    // 检查分佣比例或备注是否发生变化
                    if (originalCollaborator.rate !== collaborator.rate ||
                        originalCollaborator.remark !== (collaborator.remark || '')) {
                        collaborator.operation = 'UPDATE';
                    }
                } else {
                    // 如果找不到原始数据，但有id，说明是原有数据，标记为UPDATE
                    if (collaborator.id) {
                        collaborator.operation = 'UPDATE';
                    }
                }
            }

            this.validateTotalRate(customerIndex);
        },
        validateTotalRate(customerIndex) {
            const total = this.getTotalRate(customerIndex);
            const ownerRate = this.getOwnerRate(customerIndex);

            if(total > 100) {
                this.$message.warning(`客户 ${this.customers[customerIndex].customerName} 的协作人员总分佣比例不能超过100%`);
            } else if(ownerRate < 10) {
                this.$message.warning(`客户 ${this.customers[customerIndex].customerName} 的本人佣金比例过低，建议调整协作人员分佣比例`);
            }
        },
        // 获取本人佣金比例（100% - 协作人员总分佣比例）
        getOwnerRate(customerIndex) {
            const collaboratorTotalRate = this.getTotalRate(customerIndex);
            return Math.max(0, 100 - collaboratorTotalRate);
        },
        // 获取本人佣金比例的样式类
        getOwnerRateClass(customerIndex) {
            const ownerRate = this.getOwnerRate(customerIndex);
            if(ownerRate < 0) return 'rate-error';
            if(ownerRate === 0) return 'rate-warning';
            return 'rate-success';
        },
        getTotalRateClass(customerIndex) {
            const total = this.getTotalRate(customerIndex);
            if(total > 100) return 'rate-error';
            if(total === 100) return 'rate-success';
            return 'rate-normal';
        },
        handleAddCollaborator(customerIndex) {
            // 为特定客户添加协作人
            this.currentCustomerIndex = customerIndex;
            var that = this;
            this.userSelect.open = true;
            setTimeout(() => {
                that.$refs.userSelects.getList();
            }, 500);
        },
        handleRemoveCollaborator(customerIndex, collaboratorIndex) {
            const customer = this.customers[customerIndex];
            const collaborator = customer.collaborators[collaboratorIndex];
            if (collaborator.operation === 'ADD') {
                // 如果是新增的协作者，直接从列表中移除
                customer.collaborators.splice(collaboratorIndex, 1);
            } else {
                // 如果是原有的协作者，标记为删除但不从列表中移除
                collaborator.operation = 'DELETE';
                // 可以选择隐藏已删除的项目或者用特殊样式显示
                // 这里我们从界面上移除，但在提交时会包含删除操作
                customer.collaborators.splice(collaboratorIndex, 1);

                // 将删除的协作者添加到待删除列表中
                if (!customer.deletedCollaborators) {
                    this.$set(customer, 'deletedCollaborators', []);
                }
                customer.deletedCollaborators.push(collaborator);
            }
        },
        getTotalRate(customerIndex) {
            const customer = this.customers[customerIndex];
            if(!customer.collaborators) return 0;

            return customer.collaborators.reduce((total, collaborator) => {
                // 只计算未删除的协作者
                if (collaborator.operation !== 'DELETE') {
                    return total + (collaborator.rate || 0);
                }
                return total;
            }, 0);
        },
        async loadCustomerCollaborators() {
            // 确保 originalCollaborators 存在
            if (!this.originalCollaborators) {
                this.originalCollaborators = {};
            }

            // 加载每个客户的协作者信息
            let customerIds = this.customers.map(customer => customer.customerId || null);
            this.customerIds = customerIds;

            if(customerIds && customerIds.length > 0){
                try {
                    //查询用户分佣信息
                    selectByCustomerIds(customerIds).then(response => {
                        if(response && response.code == 200){
                            // 清空原始数据
                            this.originalCollaborators = {};

                            // 遍历每个客户，匹配对应的协作者数据
                            this.customers.forEach(customer => {
                                // 查找当前客户的协作者数据
                                const customerData = response.data.find(item => item.customerId === customer.customerId);

                                if(customerData && customerData.assistList && customerData.assistList.length > 0) {
                                    // 将协作者数据转换为组件需要的格式
                                    const collaborators = customerData.assistList.map(item => {
                                        const collaborator = {
                                            id: item.id,
                                            companyId: item.companyId,
                                            companyUserId: item.companyUserId,
                                            companyUserName: item.companyUserName,
                                            customerId: item.customerId,
                                            rate: item.rate || 0,
                                            remark: item.remark || '',
                                            operation: 'NONE' // 标记为原有数据，无变化
                                        };

                                        // 保存原始数据用于对比
                                        const originalKey = `${item.customerId}_${item.companyUserId}`;
                                        this.originalCollaborators[originalKey] = {
                                            id: item.id,
                                            rate: item.rate || 0,
                                            remark: item.remark || ''
                                        };


                                        return collaborator;
                                    });

                                    // 设置客户的协作者列表
                                    this.$set(customer, 'collaborators', collaborators);
                                    // 初始化删除列表
                                    this.$set(customer, 'deletedCollaborators', []);
                                } else {
                                    // 如果没有协作者数据，设置为空数组
                                    this.$set(customer, 'collaborators', []);
                                    this.$set(customer, 'deletedCollaborators', []);
                                }
                            });

                        } else {
                            // 如果查询失败，确保 originalCollaborators 是空对象
                            this.originalCollaborators = {};
                        }
                    }).catch(error => {
                        this.originalCollaborators = {};
                        this.$message.error("加载协作者数据失败，请重试");
                    });
                } catch(error) {
                    // 异常情况下，确保 originalCollaborators 是空对象
                    this.originalCollaborators = {};
                    // 异常情况下，为所有客户设置空的协作者列表
                    this.customers.forEach(customer => {
                        this.$set(customer, 'collaborators', []);
                        this.$set(customer, 'deletedCollaborators', []);
                    });
                    this.$message.error("加载协作者数据失败，请重试");
                }
            } else {
                // 如果没有客户ID，确保 originalCollaborators 是空对象
                this.originalCollaborators = {};
            }
        },
        changeVal(row) {
            this.$forceUpdate();//解决点击计数器失效问题
            this.computeCount();
            if(this.assistCount>this.customerIds.length){
                this.$nextTick(() => {
                        row.count=0;
                        this.computeCount();
                });

            }
        },
        handleRemoveUser(index){
            this.users.splice(index,1);
            this.computeCount();
            this.$refs.userSelects.delUser(index);
        },
        selectUser(data){
            if(this.flag){
                // 手动分佣模式 - 为特定客户添加协作人
                if(this.currentCustomerIndex >= 0) {
                    const customer = this.customers[this.currentCustomerIndex];
                    if(!customer.collaborators) {
                        this.$set(customer, 'collaborators', []);
                    }
                    data.forEach(user => {
                        // 检查是否已存在
                        const exists = customer.collaborators.some(c => c.userId === user.userId);
                        const existsInDeleted = customer.deletedCollaborators &&
                            customer.deletedCollaborators.some(c => c.companyUserId === user.userId);
                        if(!exists && !existsInDeleted) {
                            const collaborator = {
                                companyUserId: user.userId,
                                companyUserName: user.nickName,
                                customerId: customer.customerId,
                                rate: 0,
                                remark: '',
                                operation: 'ADD' // 标记为新增
                            };
                            customer.collaborators.push(collaborator);
                        } else if (existsInDeleted) {
                            // 如果在删除列表中存在，则恢复该协作者
                            const deletedIndex = customer.deletedCollaborators.findIndex(c => c.companyUserId === user.userId);
                            if (deletedIndex >= 0) {
                                const restoredCollaborator = customer.deletedCollaborators[deletedIndex];
                                restoredCollaborator.operation = 'NONE'; // 恢复为原有状态
                                customer.collaborators.push(restoredCollaborator);
                                customer.deletedCollaborators.splice(deletedIndex, 1);
                            }
                        }
                    });
                    this.userSelect.open=false;
                }
            } else{
                var users=[];
                var number=parseInt(this.customerIds.length/data.length);
                data.forEach(element => {
                    var user={
                        userId:element.userId,
                        userName:element.userName,
                        nickName:element.nickName,
                        deptName:element.dept.deptName,
                        nowDayCustomerCount:element.nowDayCustomerCount,
                        phonenumber:element.phonenumber,
                        count:number,
                    }
                    users.push(user)
                });
                this.users=users;
                this.userSelect.open=false;
                this.computeCount()
            }

        },
        computeCount(){
            this.assistCount=0;
            var that=this;
            this.users.forEach(element => {
                that.assistCount+=element.count;
            });
            this.noAssistCount=this.customerIds.length-this.assistCount
        },
        handleUserSelect(){
            var that=this;
            this.userSelect.open=true;
            setTimeout(() => {
                that.$refs.userSelects.getList();
            }, 500);
        },
        async init(customerIds,flag){
            this.flag = flag //是否设置分佣
            if(flag){
                this.customers = customerIds;
                await this.loadCustomerCollaborators();
            } else {
                this.customerIds =  customerIds;
                this.assistCount=0;
                this.noAssistCount=this.customerIds.length;
                this.users=[];
            }

        },
        async submitAssistForm2(){
            // 提交前检查并更新操作状态
            this.checkAndUpdateOperations();
            // 验证数据
            let hasError = false;
            for(let i = 0; i < this.customers.length; i++) {
                const customer = this.customers[i];
                const totalRate = this.getTotalRate(i);

                if(totalRate > 100) {
                    this.$message.error(`客户 ${customer.customerName} 的协作人员总分佣比例不能超过100%`);
                    hasError = true;
                    break;
                }
            }

            if(hasError) return;

            this.submitLoading = true;

            try {
                // 准备提交数据 - 包含所有操作类型
                const submitData = {
                    customerIds: this.customers.map(c => c.customerId), // 包含所有客户ID
                    operations: []
                };

                this.customers.forEach(customer => {
                    if(customer.collaborators && customer.collaborators.length > 0) {
                        customer.collaborators.forEach(collaborator => {
                            if (collaborator.operation !== 'DELETE') {
                                 // 确保每个协作者都有正确的operation字段
                                 let operation = collaborator.operation;
                                 // 如果没有operation字段，根据是否有id来判断
                                if (!operation) {
                                    if (collaborator.id) {
                                        // 有id说明是原有数据，检查是否有变化
                                        const originalKey = `${collaborator.customerId}_${collaborator.companyUserId}`;
                                        const originalCollaborator = this.originalCollaborators[originalKey];

                                        if (originalCollaborator &&
                                            (originalCollaborator.rate !== collaborator.rate ||
                                             originalCollaborator.remark !== (collaborator.remark || ''))) {
                                            operation = 'UPDATE';
                                        } else {
                                            operation = 'NONE';
                                        }
                                    } else {
                                        // 没有id说明是新增数据
                                        operation = 'ADD';
                                    }
                                }
                                submitData.operations.push({
                                    operation: operation, // ADD, UPDATE, NONE
                                    id: collaborator.id || null,
                                    companyId: collaborator.companyId,
                                    companyUserId: collaborator.companyUserId,
                                    companyUserName: collaborator.companyUserName,
                                    customerId: customer.customerId,
                                    rate: collaborator.rate,
                                    remark: collaborator.remark || ''
                                });
                            }
                        });
                    }
                    // 处理已删除的协作者
                    if(customer.deletedCollaborators && customer.deletedCollaborators.length > 0) {
                        customer.deletedCollaborators.forEach(collaborator => {
                            submitData.operations.push({
                                operation: 'DELETE',
                                id: collaborator.id,
                                companyUserId: collaborator.companyUserId,
                                customerId: customer.customerId
                            });
                        });
                    }

                });

                console.log("提交的完整分佣数据:", JSON.stringify(submitData, null, 2));

                // 这里需要根据你的实际更新接口来调用
                const response = await allOperation(submitData.operations);

                if(response.code === 200) {
                    this.$message.success("分佣设置保存成功");
                    this.$emit('close');
                } else {
                    this.$message.error(response.msg || "保存失败");
                }
            } catch(error) {
                this.$message.error("保存失败，请重试");
            } finally {
                this.submitLoading = false;
            }
        },
        /** 提交按钮 */
        submitAssistForm() {
            var that=this;
            this.$refs["assistForm"].validate(valid => {
                if (valid) {
                    var users=[];
                    var customerIds=[];
                    var idIndex=0;
                    var totalAssistCount=0;
                    console.log("qxj users",JSON.stringify(this.users));
                    this.users.forEach(element => {
                        if(element.count>0){
                            var ids=that.customerIds.slice(idIndex,idIndex+element.count)
                            console.log("qxj customerIds:"+that.customerIds+" count:"+element.count);
                            console.log("qxj ids:"+ids);
                            customerIds=customerIds.concat(ids);
                            idIndex=idIndex+element.count;
                            var data={companyUserId:element.userId,count:element.count};
                            users.push(data);
                            totalAssistCount+=element.count;
                        }
                    });
                    if(users.length==0){
                        this.msgError("请选择员工");
                        return;
                    }
                    if(totalAssistCount>(this.assistCount+this.noAssistCount)){
                        this.msgError("添加数量有误");
                        return;
                    }
                    this.myloading = this.$loading({
                        lock: true,
                        text: '处理中...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    var data={customerIds:customerIds,users:users}
                    console.log("qxj data:",JSON.stringify(data));
                    assistToUser(data).then(response => {
                        this.myloading.close()
                        if (response.code === 200) {
                            this.msgSuccess("操作成功");
                            this.$emit('close');
                        }
                    });
                }
            });
        },
        closeAction(){
            this.$refs.userSelects.users=[];
        }
    }
};
</script>
<style lang="scss" scoped>
.contents{
    height: 100%;
    background-color: #fff;
    padding: 20px;

}
.footer{
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
</style>



