<template>
    <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="线索来源" prop="source">
                <el-select v-model="form.source" :disabled="form.source !== null" placeholder="请选择线索来源" clearable size="small">
                <el-option
                    v-for="item in clueSourceOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
                </el-select>
            </el-form-item>
            <el-form-item label="客户经理" prop="manager">
                <el-input v-model="form.manager" placeholder="请输入客户经理" />
            </el-form-item>
            <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="form.companyName"  placeholder="请输入公司名称(只填公司全称,个人用户就填名字)" />
            </el-form-item>
            <el-form-item label="联系电话" v-show="form.customerId !== null" prop="mobile">
                <el-input  v-model="form.mobile" :disabled="form.customerId !== null" placeholder="请输入电话号码"/>
            </el-form-item>
            <el-form-item label="其他联系方式">
                <el-button type="text" @click="showAddContactDialog">添加其他联系电话</el-button>
            </el-form-item>
            <el-table border v-loading="loading" :data="mobileList" v-if="mobileList && mobileList.length > 0" >
                <el-table-column label="姓名" align="center" prop="name" />
                <el-table-column label="手机" align="center" prop="mobile" />
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['crm:customerContacts:remove']"
                    v-if="scope.row.contactsId == null"
                    >删除</el-button>
                </template>
                </el-table-column>
            </el-table>

            <el-form-item label="接口人角色" prop="contactRole">
                <el-select v-model="form.contactRole" placeholder="请选择" clearable size="small">
                    <el-option
                        v-for="item in contactRoleOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="业务场景" prop="businessScenario">
                <el-select v-model="form.businessScenario"  placeholder="请选择线索业务场景" clearable size="small">
                <el-option
                    v-for="item in businessScenarioOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
                </el-select>
            </el-form-item>
            <el-form-item label="意向产品" prop="product">
                <el-input v-model="form.product" placeholder="请输入方案涉及产品" />
            </el-form-item>
            <el-form-item label="采购周期" prop="purchaseCycle">
                <el-input v-model="form.purchaseCycle" placeholder="请输入采购周期(单位:天)" />
            </el-form-item>
            <el-form-item label="跟进状态" prop="businessStatus">
                <el-radio-group v-model="form.businessStatus">
                    <el-radio label=0>跟进中</el-radio>
                    <el-radio label=1>已流失</el-radio>
                    <el-radio label=2>已赢单</el-radio>
                    <el-radio label=3>待验证</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="项目阶段" prop="projectPhase">
                <!-- 移除 filteredProjectPhaseOptions，直接使用 projectPhaseOptions -->
                <el-select v-model="form.projectPhase" placeholder="请选择" clearable size="small">
                    <el-option
                        v-for="item in projectPhaseOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="意向等级" prop="level">
                <el-select v-model="form.level" placeholder="请选择" clearable size="small">
                    <el-option
                        v-for="item in levelOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="是否绑定BP">
                <el-radio-group v-model="form.isBp">
                    <el-radio label="0">未注册</el-radio>
                    <el-radio label="1">已注册未绑定</el-radio>
                    <el-radio label="2">不明确</el-radio>
                    <el-radio label="3">已绑定</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="预计成单时间" prop="preTime">
                <el-date-picker clearable size="small" style="width: 200px"
                    v-model="form.preTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择预计成单时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="预计成交金额" prop="preMoney">
                <el-input v-model="form.preMoney" placeholder="请输入预计成交金额(元)" />
            </el-form-item>
            <el-form-item label="首次跟进内容" prop="content" v-if="form.businessId == null">
                <el-input v-model="form.content" placeholder="请输入首次跟进内容" />
            </el-form-item>
            <el-form-item label="下次跟进时间" prop="nextTime">
                <el-date-picker clearable size="small" style="width: 200px"
                    v-model="form.nextTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择下次跟进时间">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <div class="footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
        <el-dialog  :title=title :visible.sync="open" width="500px" append-to-body>
            <el-form ref="contactForm" :model="contactForm" :rules="contactRules" label-width="120px">
            <el-form-item label="联系人名称" prop="name">
                <el-input v-model="contactForm.name" placeholder="请输入联系人名称" />
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="contactForm.mobile" placeholder="请输入手机" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="contactForm.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitContactForm">确 定</el-button>
                <el-button @click="cancelContact">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { addBusiness, updateBusiness } from "@/api/crm/business";
    import { listCustomerContacts, getCustomerContacts, addCustomerContacts, exportCustomerContacts } from "@/api/crm/customerContacts";
    export default {
        name: "business",
        data() {
            return {
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 遮罩层
                loading: true,
                mobileList: [],
                // dialogVisible:false,
                //联系方式表格
                contactForm: {
                    contactsId: null,
                    customerId: null,
                    businessId: null,
                    name: null,
                    mobile: null,
                    remark: null
                },
                businessScenarioOptions: [],
                clueSourceOptions: [],
                contactRoleOptions: [],
                projectPhaseOptions: [],
                levelOptions: [],
                // 添加标志位防止循环触发 - 确保初始化为 false
                isUpdatingStatus: false,
                isUpdatingPhase: false,
                form: {
                    businessId: null,
                    customerId: null,
                    source: null,
                    manager: null,
                    companyName: null,
                    mobile: null,
                    mobileList: [],
                    contactRole: null,
                    businessScenario: null,
                    product: null,
                    purchaseCycle: null,
                    // businessStatus: 0,
                    remark: null,
                    projectPhase: null,
                    level: null,
                    isBp: '0',
                    bpAccount: null,
                    preTime: null,
                    preMoney: null,
                    nextTime: null,
                    createTime: null,
                    updateTime: null,
                    createBy: null,
                    recoveryTime: null,
                    status: '1'
                },
                // 表单校验
                rules: {
                    source: [
                        { required: true, message: "客户来源不能为空", trigger: "change" }
                    ],
                    companyName: [
                        { required: true, message: "客户名称不能为空", trigger: "blur" }
                    ],
                    businessScenario: [
                        { required: true, message: "业务场景不能为空", trigger: "change" }
                    ],
                    businessStatus: [
                        { required: true, message: "请选择跟进状态", trigger: "change" }
                    ],
                    projectPhase: [
                        { required: true, message: "请选择项目阶段", trigger: "change" }
                    ],

                },
                //联系方式表单校验
                contactRules: {
                    name: [
                        { required: true, message: "联系人不能为空", trigger: "blur" }
                    ],
                    mobile: [
                        { required: true, message: "手机不能为空", trigger: "blur" },
                        { min: 8, max: 11, message: '长度在 8 到 11 个字符', trigger: 'blur' }
                    ]
                }

            };
        },
        created() {
            this.getDicts("crm_customer_source").then((response) => {
                this.clueSourceOptions = response.data;
            });
            this.getDicts("crm_contact_role").then((response) => {
                this.contactRoleOptions = response.data;
            });
            this.getDicts("crm_project_phase").then((response) => {
                this.projectPhaseOptions = response.data;
            });
            this.getDicts("crm_level").then((response) => {
                this.levelOptions = response.data;
            });
            this.getDicts("business_scenario_type").then((response) => {
                this.businessScenarioOptions = response.data;
            });
        },
        // 修改监听器：实现正确的自动匹配逻辑
        watch: {
            // 监听跟进状态变化，自动匹配项目阶段
            'form.businessStatus': {
                handler: function(newVal, oldVal) {

                    if (this.isUpdatingStatus) {
                        return;
                    }

                    // 设置标志位防止循环触发
                    this.isUpdatingPhase = true;

                    if (newVal == 2) {
                        // 已赢单 -> 自动设置为100%转商
                        const winOption = this.projectPhaseOptions.find(item => {
                            return item.dictLabel === '100%转商' ||
                                   item.dictValue === 'A';
                        });
                        if (winOption) {
                            this.form.projectPhase = winOption.dictValue;
                        }
                    } else if (newVal == 1) {
                        // 已流失 -> 自动设置为丢单
                        const lostOption = this.projectPhaseOptions.find(item => {
                            return item.dictLabel === '丢单' ||
                                   item.dictValue === 'L' ;
                        });
                        if (lostOption) {
                            this.form.projectPhase = lostOption.dictValue;
                        }
                    }

                    // 重置标志位
                    this.$nextTick(() => {
                        this.isUpdatingPhase = false;
                    });
                },
                immediate: false
            },

            // 监听项目阶段变化，自动匹配跟进状态
            'form.projectPhase': {
                handler: function(newVal, oldVal) {

                    if (this.isUpdatingPhase) {
                        return;
                    }

                    // 设置标志位防止循环触发
                    this.isUpdatingStatus = true;

                    // 根据项目阶段自动匹配跟进状态
                    const selectedPhase = this.projectPhaseOptions.find(item => item.dictValue === newVal);

                    if (selectedPhase) {
                        if (selectedPhase.dictLabel == '100%转商' ||
                            selectedPhase.dictValue == 'A') {
                            // 100%转商 -> 自动设置为已赢单
                            this.form.businessStatus = '2';
                        } else if (selectedPhase.dictLabel == '丢单' ||
                                  selectedPhase.dictValue == 'L' ) {
                            // 丢单 -> 自动设置为已流失
                            this.form.businessStatus = '1';
                        }
                    }

                    // 重置标志位
                    this.$nextTick(() => {
                        this.isUpdatingStatus = false;
                    });
                },
                immediate: false
            }
        },
        methods: {
            addProduct() {
            },
            delCustomerContacts(mobile) {
                const index = this.mobileList.findIndex(phone => phone.id === mobile);
                if (index !== -1) {
                    this.mobileList.splice(index, 1); // 删除找到的对象
                }
                this.open = false;
                this.loading = false;
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                this.loading = true;
                const mobile = row.mobile;
                const index = this.mobileList.findIndex(phone => phone.mobile === mobile);
                if (index !== -1) {
                    this.mobileList.splice(index, 1); // 删除找到的对象
                }
                this.open = false;
                this.loading = false;

            },

            /** 提交按钮 */
            submitContactForm() {
                this.$refs["contactForm"].validate(valid => {
                    if (valid) {
                        //新增
                        const newMobile = {
                            mobile: this.contactForm.mobile,
                            name: this.contactForm.name,
                            remark: this.contactForm.remark,
                        };
                        this.mobileList.push(newMobile);
                        this.open = false;
                        this.loading = false;
                    }
                });
            },
            updateMobileList(mobile, newMobileData) {
                // 查找要修改的对象
                const index = this.mobileList.findIndex(phone => phone.mobile === mobile);
                if (index !== -1) {
                    // 更新找到的对象
                    this.$set(this.mobileList, index, { ...this.mobileList[index], ...newMobileData });
                }
            },
            // 取消按钮
            cancelContact() {
                this.open = false;
                this.resetContact();
            },
            resetContact() {
                this.contactForm = {
                    contactsId: null,
                    customerId: null,
                    name: null,
                    mobile: null,
                    email: null,
                    weixin: null,
                    address: null,
                    remark: null,
                    createUserId: null,
                    createTime: null,
                    updateTime: null,
                    isDel: null,
                    companyId: null
                };
            },
            //添加联系方式
            showAddContactDialog() {
                this.open = true; // 显示弹窗
                this.contactForm.mobile = ''; // 清空表单数据
            },
            addContact() {
                // 添加联系方式逻辑
                this.form.mobile = this.contactForm.mobile; // 将联系方式添加到form.mobile
                this.open = false; // 关闭弹窗
            },
            updateReset(row){
                // 重置标志位
                this.isUpdatingStatus = false;
                this.isUpdatingPhase = false;

                this.form = row;
                if(row.source != null){
                    this.form.source = String(row.source);
                }
                if(row.contactRole != null){
                    this.form.contactRole = String(row.contactRole);
                }
                if(row.businessScenario != null){
                    this.form.businessScenario = String(row.businessScenario);
                }
                this.mobileList = this.form.mobileList;
                if(row.level != null){
                    this.form.level = String(row.level);
                }
                if(row.isBp != null){
                    this.form.isBp = String(row.isBp);
                }
                this.loading = false;
            },
            reset(row) {
                // 重置标志位
                this.isUpdatingStatus = false;
                this.isUpdatingPhase = false;

                this.form = row;
                this.form.source=String(row.source);
                // 电话
                this.getContact(row.customerId,this.form.businessId);
                // // 跟进状态
                // this.form.businessStatus = 0
                // 客户名字
                if(row.customerCompanyName){
                    this.form.companyName = row.customerCompanyName
                }
            },
            getContact(customerId,businessId){
                this.loading = true;
                listCustomerContacts({ customerId: customerId, businessId: businessId }).then(response => {
                    if (response.code === 200) {
                        if (response.rows.length > 0)
                            this.mobileList = response.rows;
                        this.loading = false;
                    } else {
                        this.mobileList = []
                    }
                })
            },
            businessReset() {
                // 重置标志位
                this.isUpdatingStatus = false;
                this.isUpdatingPhase = false;

                this.form = {
                    businessId: null,
                    customerId: null,
                    source: null,
                    manager: null,
                    companyName: null,
                    mobile: null,
                    contactRole: null,
                    businessScenario: null,
                    product: null,
                    purchaseCycle: null,
                    remark: null,
                    projectPhase: null,
                    level: null,
                    isBp: null,
                    bpAccount: null,
                    preTime: null,
                    preMoney: null,
                    nextTime: null,
                    createTime: null,
                    updateTime: null,
                    createBy: null,
                    recoveryTime: null,
                    status: 0,
                    content:null
                };
                this.resetContact();
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        this.form.mobileList = this.mobileList;
                        if (this.form.businessId != null) {
                            updateBusiness(this.form).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("修改成功");
                                    this.businessReset();
                                    this.$emit('closeBusiness');
                                }
                            });
                        } else {
                            addBusiness(this.form).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("提交成功");
                                    this.businessReset();
                                    this.$emit('closeBusiness');
                                }
                            });
                        }

                    }
                });
            },
        }
    };
</script>

<style lang="scss" scoped>
.contents {
    height: 100%;
    background-color: #fff;
    padding: 20px;

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

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
</style>
