 <template>
    <div class="customer-dialog-content">
        <div class="dialog-header">
            <i class="el-icon-user header-icon"></i>
            <span class="header-title">{{ form.customerId ? '编辑客户' : '新增客户' }}</span>
        </div>
        
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="customer-form">
            <el-divider content-position="left">
                <span class="divider-title">
                    <i class="el-icon-info"></i> 基本信息
                </span>
            </el-divider>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="客户名称" prop="customerName">
                        <el-input v-model="form.customerName" placeholder="请输入客户名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机" prop="mobile">
                        <el-input maxlength="11" v-model="form.mobile" placeholder="请输入手机" />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="form.sex">
                            <el-radio :label="item.dictValue" v-for="item in sexOptions" :key="item.dictValue">{{item.dictLabel}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="微信号" prop="weixin">
                        <el-input v-model="form.weixin" placeholder="请输入微信号" />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="客户类型" prop="customerType">
                        <el-select v-model="form.customerType" placeholder="请选择客户类型" clearable style="width: 100%;">
                            <el-option
                                v-for="item in typeOptions"
                                :key="item.dictValue"
                                :label="item.dictLabel"
                                :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户来源" prop="source">
                        <el-select v-model="form.source" placeholder="请选择客户来源" clearable style="width: 100%;">
                            <el-option
                                v-for="item in sourceOptions"
                                :key="item.dictValue"
                                :label="item.dictLabel"
                                :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所在地区" prop="address">
                        <el-cascader
                            ref="citySelect"
                            v-model="cityIds"
                            :options="citys"
                            @change="handleCityChange"
                            style="width: 100%;"
                        ></el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="详细地址" prop="detailAddress">
                        <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-divider content-position="left">
                <span class="divider-title">
                    <i class="el-icon-price-tag"></i> 标签信息
                </span>
            </el-divider>
            
            <el-form-item label="标签" prop="tags">
                <div class="tags-container">
                    <el-tag
                        :key="tag"
                        v-for="tag in tags"
                        closable
                        :disable-transitions="false"
                        class="selected-tag"
                        @close="handleClose(tag)"
                    >
                        {{tag}}
                    </el-tag>
                    <el-input
                        class="input-new-tag"
                        v-if="inputVisible"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        placeholder="输入新标签"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" icon="el-icon-plus" @click="showInput">自定义标签</el-button>
                    <el-select v-model="tagId" @change="tagsChange" style="width:140px;margin-left: 10px;" placeholder="选择标签" clearable size="small">
                        <el-option
                            v-for="item in tagsOptions"
                            :key="item.dictValue"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        />
                    </el-select>
                </div>
            </el-form-item>
            
            <el-divider content-position="left">
                <span class="divider-title">
                    <i class="el-icon-connection"></i> 进线信息
                </span>
            </el-divider>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="进线日期" prop="registerDate">
                        <el-date-picker
                            value-format="yyyy-MM-dd"
                            v-model="form.registerDate"
                            type="date"
                            placeholder="请选择进线日期"
                            style="width: 100%;"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="进线填写时间" prop="registerSubmitTime">
                        <el-date-picker
                            value-format="yyyy-MM-dd HH:mm:ss"
                            v-model="form.registerSubmitTime"
                            type="datetime"
                            placeholder="请选择进线填写时间"
                            style="width: 100%;"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="进线链接" prop="registerLinkUrl">
                        <el-input v-model="form.registerLinkUrl" placeholder="请输入进线链接" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="进线方式" prop="registerType">
                        <el-input v-model="form.registerType" placeholder="请输入进线方式" />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-form-item label="进线客户详情" prop="registerDesc">
                <el-input v-model="form.registerDesc" placeholder="请输入进线客户详情" />
            </el-form-item>
            
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="来源渠道编码" prop="sourceCode">
                        <el-input v-model="form.sourceCode" placeholder="请输入来源渠道编码" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="推线时间" prop="pushTime">
                        <el-input v-model="form.pushTime" placeholder="请输入推线时间" />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-form-item label="推线编码" prop="pushCode">
                <el-input v-model="form.pushCode" placeholder="请输入推线编码" />
            </el-form-item>
            
            <el-divider content-position="left" v-if="exts.length > 0">
                <span class="divider-title">
                    <i class="el-icon-s-operation"></i> 扩展信息
                </span>
            </el-divider>
            
            <el-form-item :label="ext.name" v-for="ext in exts" :key="ext.extId">
                <el-input v-model="ext.value" placeholder="请输入内容" />
            </el-form-item>
            
            <el-divider content-position="left">
                <span class="divider-title">
                    <i class="el-icon-document"></i> 备注
                </span>
            </el-divider>
            
            <el-form-item label="备注" prop="remark">
                <el-input :rows="3" v-model="form.remark" type="textarea" placeholder="请输入备注内容" maxlength="500" show-word-limit />
            </el-form-item>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
            <el-button @click="$emit('close')">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
    </div>
</template>
  
<script>
    import { listCustomerExt } from "@/api/crm/customerExt";
    import { updateCustomer, addCustomer, addMyCustomer, getCustomerDetails } from "@/api/crm/customer";
    import { getCitys } from "@/api/store/city";
    
    export default {
        name: "AddOrEditCustomer",
        data() {
            return {
                addType: 1,
                tagId: null,
                tagsOptions: [],
                cityIds: [],
                citys: [],
                tags: [],
                inputVisible: false,
                inputValue: '',
                statusOptions: [],
                typeOptions: [],
                sourceOptions: [],
                sexOptions: [],
                customerExts: [],
                form: {
                    province: null,
                    city: null,
                    district: null,
                },
                exts: [],
                rules: {
                    mobile: [
                        { required: true, message: "手机号不能为空", trigger: "blur" }
                    ],
                    source: [
                        { required: true, message: "客户来源不能为空", trigger: "blur" }
                    ],
                }
            };
        },
        created() {
            this.getDicts("crm_customer_source").then((response) => {
                this.sourceOptions = response.data;
            });
            this.getDicts("sys_sex").then((response) => {
                this.sexOptions = response.data;
            });
            this.getDicts("crm_customer_tag").then((response) => {
                this.tagsOptions = response.data;
            });
            this.getDicts("crm_customer_status").then((response) => {
                this.statusOptions = response.data;
            });
            this.getDicts("crm_customer_type").then((response) => {
                this.typeOptions = response.data;
            });
            this.getCitys();
        },
        methods: {
            tagsChange(e) {
                var item = this.tagsOptions.find(val => val.dictValue === e);
                if (item && !this.tags.includes(item.dictLabel)) {
                    this.tags.push(item.dictLabel);
                    this.form.tags = this.tags.toString();
                }
                this.tagId = null;
            },
            handleCityChange(value) {
                var nodes = this.$refs.citySelect.getCheckedNodes();
                if (nodes && nodes.length > 0) {
                    this.form.address = nodes[0].pathLabels.join("-");
                    this.form.cityIds = value.toString();
                }
            },
            getCitys() {
                getCitys().then(res => {
                    this.citys = res.data;
                });
            },
            handleClose(tag) {
                this.tags.splice(this.tags.indexOf(tag), 1);
                this.form.tags = this.tags.toString();
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue.trim();
                if (inputValue && !this.tags.includes(inputValue)) {
                    this.tags.push(inputValue);
                    this.form.tags = this.tags.toString();
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            reset() {
                this.form = {
                    customerId: null,
                    customerCode: null,
                    customerName: null,
                    mobile: null,
                    sex: null,
                    weixin: null,
                    remark: null,
                    userId: null,
                    createUserId: null,
                    receiveUserId: null,
                    customerUserId: null,
                    address: null,
                    location: null,
                    detailAddress: null,
                    lng: null,
                    lat: null,
                    createTime: null,
                    updateTime: null,
                    status: 0,
                    isReceive: null,
                    deptId: null,
                    isDel: null,
                    customerType: null,
                    receiveTime: null,
                    poolTime: null,
                    companyId: null,
                    isLine: null,
                    source: null,
                    tags: null,
                };
                this.exts = [];
                this.tags = [];
                this.cityIds = [];
                this.resetForm("form");
            },
            handleAdd(addType) {
                this.addType = addType;
                this.reset();
                var data = { status: 1 };
                listCustomerExt(data).then(response => {
                    this.customerExts = response.data;
                    this.customerExts.forEach(element => {
                        var data = { extId: element.extId, name: element.name, value: "" };
                        this.exts.push(data);
                    });
                });
            },
            handleUpdate(customerId) {
                this.reset();
                var that = this;
                var data = { customerId: customerId };
                getCustomerDetails(data).then(response => {
                    this.form = response.customer;
                    if (this.form.status != null) {
                        this.form.status = this.form.status.toString();
                    }
                    if (this.form.customerType != null) {
                        this.form.customerType = this.form.customerType.toString();
                    }
                    if (this.form.sex != null) {
                        this.form.sex = this.form.sex.toString();
                    }
                    if (this.form.source != null) {
                        this.form.source = this.form.source.toString();
                    }
                    if (this.form.tags != null) {
                        this.tags = this.form.tags.split(",");
                    }
                    if (this.form.cityIds != null) {
                        var ids = this.form.cityIds.split(",");
                        this.cityIds = [];
                        ids.forEach(element => {
                            var id = parseInt(element);
                            that.cityIds.push(id);
                        });
                    }
                    listCustomerExt(data).then(response => {
                        this.customerExts = response.data;
                        this.customerExts.forEach(element => {
                            var data = { extId: element.extId, name: element.name, value: "" };
                            this.exts.push(data);
                        });
                        if (this.form.extJson != null) {
                            var extList = JSON.parse(this.form.extJson);
                            that.exts.forEach(item => {
                                extList.forEach(element => {
                                    if (item.extId == element.extId) {
                                        item.value = element.value;
                                    }
                                });
                            });
                        }
                    });
                });
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.customerId != null) {
                            this.form.extJson = JSON.stringify(this.exts);
                            updateCustomer(this.form).then(response => {
                                if (response.code === 200) {
                                    this.$message.success("操作成功");
                                    this.$emit('close');
                                }
                            });
                        } else {
                            this.form.extJson = JSON.stringify(this.exts);
                            if (this.addType == 1) {
                                addCustomer(this.form).then(response => {
                                    if (response.code === 200) {
                                        this.$message.success("操作成功");
                                        this.$emit('close');
                                    }
                                });
                            } else if (this.addType == 2) {
                                addMyCustomer(this.form).then(response => {
                                    if (response.code === 200) {
                                        this.$message.success("操作成功");
                                        this.$emit('close');
                                    }
                                });
                            }
                        }
                    }
                });
            },
        }
    };
</script>
<style lang="scss" scoped>
.customer-dialog-content {
    padding: 10px 0;
    
    .dialog-header {
        display: flex;
        align-items: center;
        margin-bottom: 24px;
        
        .header-icon {
            font-size: 24px;
            color: #409eff;
            margin-right: 12px;
        }
        
        .header-title {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
        }
    }
    
    .customer-form {
        .el-divider {
            margin: 20px 0;
            
            .divider-title {
                font-size: 14px;
                font-weight: 600;
                color: #606266;
                display: flex;
                align-items: center;
                gap: 6px;
                
                i {
                    color: #909399;
                }
            }
        }
        
        .tags-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
            min-height: 40px;
        }
        
        .selected-tag {
            margin: 0;
        }
        
        .button-new-tag {
            background: #f5f7fa;
            border: 1px dashed #d9d9d9;
            color: #606266;
            
            &:hover {
                background: #ecf5ff;
                border-color: #409eff;
                color: #409eff;
            }
        }
    }
}
</style>
