<template>
    <div class="operationMCR-Box">
        <div class="operationMCRtitle">保存公司客户资料</div>
        <div>
            <el-form :model="requestData" label-width="110px" :rules="rules" ref="BindData">
                <div>
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="客户区域:" prop="lvlid">
                                    <el-select v-model="requestData.lvlid" placeholder="请选择客户级别"
                                        @change="(val) => { requestData.category = ''; territoryChangeSecond() }">
                                        <el-option v-for="item in level" :key="item.id" :label="item.name"
                                            :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="客户类别:" prop="category">
                                    <el-select v-model="requestData.category" placeholder="请选择客户类别">
                                        <el-option v-for="item in customerClass" :key="item.id" :label="item.name"
                                            :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="权重:">
                                    <el-select v-model="requestData.weight" placeholder="权重">
                                        <el-option label="A" value="393"></el-option>
                                        <el-option label="B" value="392"></el-option>
                                        <el-option label="C" value="391"></el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div>
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="联系人" prop="contact">
                                    <el-input v-model="requestData.contact" placeholder="请输入真实名称"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="性别" prop="gender">
                                    <el-select v-model="requestData.gender" placeholder="请选择活动区域">
                                        <el-option label="男" :value="0"></el-option>
                                        <el-option label="女" :value="1"></el-option>
                                        <el-option label="暂无" :value="2"></el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="手机号" prop="telephone">
                                    <el-input v-model="requestData.telephone"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div>
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="座机号:">
                                    <el-input v-model="requestData.phone"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="邮箱:">
                                    <el-input v-model="requestData.email"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="职务:" prop="job">
                                    <el-input placeholder="只填入职务即可" v-model="requestData.job"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div>
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="单位名称:" prop="client">
                                    <el-input v-model="requestData.client"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="单位名称缩写:">
                                    <el-input v-model="requestData.clientshort"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="所在城市:" prop="location">
                                    <el-autocomplete
                                    style="width: 100%;"
                                    class="inline-input"
                                    v-model="requestData.location"
                                    :fetch-suggestions="querySearch"
                                    placeholder="请输入内容"
                                    @select="handleSelect"
                                    ></el-autocomplete>
                                    <!-- <el-cascader
                                    show-all-levels="false"
                                    filterable
                                    size="large"
                                    @input="cascaderinput"
                                    :options="pcaTextArr"
                                    v-model="selectedOptions">
                                    </el-cascader> -->
                                    <!-- <el-input v-model="requestData.location"></el-input> -->
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div>
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="具体地址:" prop="address">
                                    <el-input v-model="requestData.address"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="护照:">
                                    <el-input v-model="requestData.passport"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple"><el-form-item label="护照有效期:">
                                    <el-date-picker value-format="yyyy-MM-dd" v-model="requestData.passportDate"
                                        type="date" placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item></div>
                        </el-col>
                    </el-row>
                </div>
                <div>
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="生日信息:">
                                    <el-date-picker value-format="yyyy-MM-dd" v-model="requestData.birthday" type="date"
                                        placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item label="今年预计出团:">
                                    <el-input v-model="requestData.predele"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple"><el-form-item label="今年已出团:">
                                    <el-input v-model="requestData.finlishedDele"></el-input>
                                </el-form-item></div>
                        </el-col>
                    </el-row>
                </div>
                <div id="BiTian">
                    <el-row>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item prop="ascribedUser" label="负责人:">
                                    <el-select v-model="requestData.ascribedUser" multiple placeholder="请选择">
                                        <el-option v-for="item in users" :key="item.id" :label="item.name"
                                            :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="grid-content bg-purple">
                                <el-form-item prop="ascribedDepartment" label="业务归属:">
                                    <el-select v-model="requestData.ascribedDepartment" multiple placeholder="请选择"
                                        width="300px">
                                        <el-option v-for="item in serviceClass" :key="item.id" :label="item.name"
                                            :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div>
                    <el-row>
                        <el-col :span="24">
                            <div class="grid-content bg-purple">
                                <el-form-item label="备注:">
                                    <el-input v-model="requestData.remark" type="textarea" :rows="5"></el-input>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>
        <div class="operationMCR-topOper">
            <el-button type="primary" @click="Getback">返回</el-button>
            <el-button type="primary" @click="save">{{ BtnTitle }}</el-button>
        </div>
    </div>
</template>

<script>
import { pcaTextArr } from 'element-china-area-data'
export default {
    data() {
        const validName = (rule, value, callback) => {
            if (value.includes('先生') || value.includes('女士') || value.includes('小姐')) {
                callback(new Error('请输入真实姓名！'))
            } else {
                callback()
            }
            // 如果是编辑需要排除自己
            // console.log(rule, value, callback);
            // let{ list } = this
            // const { formData, isEdit } = this
            // list = isEdit ? list.filter(item => item.id !== formData.id) : list
            // list.filter(item => item.pid * 1 === formData.pid).some(it => it.name.trim() === value.trim())
            //     ? callback(new Error(value + '重复了'))
            //     : callback()

        }
        return {
            token: '',
            userId: '',
            requestData: {
                "portType": 1,
                "status": 0,
                "id": 0,
                "number": 0,
                "lvlid": "",
                "client": "",
                "weight": "",
                "clientshort": "",
                "contact": "",
                "gender": 0,
                "passport": "",
                "passportDate": "",
                "job": "",
                "telephone": "",
                "phone": "",
                "email": "",
                "location": "",
                "address": "",
                "birthday": "",
                "otherinfo": "",
                "wechat": "",
                "category": "",
                "predele": "",
                "finlishedDele": "",
                "createUserId": JSON.parse(localStorage.getItem("userinif")).userInfo.userId,
                "remark": "",
                "ascribedUser": [

                ],
                "ascribedDepartment": [

                ]
            },
            BtnTitle: '保存新增数据',
            customerClass: [],//客户类别
            level: [], //客户级别
            clientTypeList: [],
            serviceClass: [],//业务归属
            users: [],//负责人
            rules: { //校验规则
                lvlid: [
                    { required: true, message: '请选择客户区域', trigger: 'blur' },
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'blur' },
                ],
                category: [
                    { required: true, message: '请选择客户类别', trigger: 'blur' },
                ],
                ascribedDepartment: [
                    { required: true, message: '请选择业务归属', trigger: 'blur' },
                ],
                ascribedUser: [
                    { required: true, message: '请选择负责人', trigger: 'blur' },
                ],
                weight: [
                    { required: true, message: '权重级别', trigger: 'blur' },
                ],
                contact: [
                    { required: true, message: '请输入联系人名称', trigger: 'blur' },
                    { validator: validName, trigger: 'blur' }
                ],
                telephone: [
                    { required: true, message: '请输入联系人手机号', trigger: 'blur' },
                ],
                job: [
                    { required: true, message: '请输入联系人职务', trigger: 'blur' },
                ],
                client: [
                    { required: true, message: '请输入单位名称', trigger: 'blur' },
                ],
                location: [
                    { required: true, message: '请输入所在城市', trigger: 'change' },
                ],
                address: [
                    { required: true, message: '请输入具体位置', trigger: 'blur' },
                ],
            },
            pcaTextArr,
            selectedOptions: [],
            restaurants:[]
        }
    },
    methods: {
        querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return restaurant.value.replace("  ", "").toLowerCase().match(queryString.toLowerCase());
            };
        },
        Getback() {
            this.$router.push('/home/MCR');
        },
        handleSelect(item) {
            this.requestData.location=''
            if (item.value.split(' ')[1]=='市辖区'||item.value.split(' ')[1]=='县') {
                this.requestData.location=(item.value.split(' ')[0]).substring(0, (item.value.split(' ')[0]).length - 1)+' '+item.value.split(' ')[2];
            }else{
                this.requestData.location=(item.value.split(' ')[1]).substring(0, (item.value.split(' ')[1]).length - 1)+' '+item.value.split(' ')[2];
            }
            // console.log(item);
            
            
          
        },
        QueryPageData() {
            var that = this;
            //初始化界面数据
            this.$axios.post('/api/MarketCustomerResources/QuerySelectAndSingleData', { Id: this.requestData.id, portType: 1, userId: this.userId }, {
                headers: {
                    'Authorization': that.token,
                }
            }).then(resp => {
                console.log(resp);
                if (resp.data.code == 200) {
                    //下拉列表
                    that.customerClass = resp.data.data.customerClass;//客户类别
                    that.level = resp.data.data.level;//客户级别

                    that.serviceClass = resp.data.data.serviceClass;//业务分类
                    that.users = resp.data.data.users; //负责人

                    if (resp.data.data.data != null) { //单条数据
                        var obj = resp.data.data.data;
                        that.requestData.lvlid = obj.lvlid;
                        that.requestData.portType = 1;
                        that.requestData.category = obj.category;
                        that.requestData.weight = obj.weight;
                        that.requestData.contact = obj.contact;
                        that.requestData.gender = obj.gender;
                        that.requestData.telephone = obj.telephone;
                        that.requestData.phone = obj.phone;
                        that.requestData.email = obj.email;
                        that.requestData.job = obj.job;
                        that.requestData.client = obj.client;
                        that.requestData.clientshort = obj.clientShort;
                        that.requestData.location = obj.location;
                        that.requestData.address = obj.address;
                        that.requestData.passport = obj.passport;
                        that.requestData.passportDate = obj.passportDate;
                        that.requestData.birthday = obj.birthday;
                        that.requestData.predele = obj.preDele;
                        that.requestData.finlishedDele = obj.finlishedDele;
                        that.requestData.ascribedUser = obj.ascribedUser.map(x => x.userId);
                        that.requestData.ascribedDepartment = obj.ascribedDepartment.map(x => x.id);
                        that.requestData.remark = obj.remark;
                    }

                    this.territoryChangeSecond();
                }
            })
        },
        cascaderinput(val){
            console.log(pcaTextArr);
            // this.selectedOptions=val[1]+val[2]+''
        },
        save() {
            var that = this;

            var p = new Promise((resolve, reject) => {
                this.$refs.BindData.validate((valid) => {
                    if (valid) {
                        resolve(true);
                    } else {
                        reject(false);
                    }
                });
            })

            p.then(resolve => {
                this.portType = 1;
                if (this.requestData.id == 0) {
                    //添加
                    this.requestData.status = 1;
                } else {
                    //修改
                    this.requestData.status = 2;
                }

                var pred = parseInt(that.requestData.predele);
                var inli = parseInt(that.requestData.finlishedDele);

                that.requestData.predele = isNaN(pred) ? 0 : pred;
                that.requestData.finlishedDele = isNaN(inli) ? 0 : inli;
                console.log(JSON.stringify(this.requestData))
                this.$axios.post('/api/MarketCustomerResources/NewClientOp', this.requestData, {
                    headers: {
                        'Authorization': that.token,
                    }
                }).then(resp => {
                    if (resp.data.code == 200) {
                        that.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.$router.push('/home/MCR');
                    } else {
                        that.$message.error(resp.data.msg);
                    }
                })

            }).catch(reject => {
                console.log("未通过表单校验");
            })
        },
        territoryChangeSecond() {
            var sid = this.requestData.lvlid;
            if (!sid) {
                sid = 0;
            }
            this.$axios.post('/api/MarketCustomerResources/QueryClientTypeSecond', {
                SetDataIdArr: [sid]
            }, {
                headers: {
                    'Authorization': this.token,
                },
            }).then(resp => {
                if (resp.data.code == 200) {
                    this.customerClass = resp.data.data; //客户类别
                } else {
                    //js抛异常
                    throw new Error(resp.data.msg);
                }
            }).catch(err => {
                this.$message.error('网络异常！');
            })
        },
        restaurantsfz(){
            for(let i=0;i<pcaTextArr.length;i++){
                for (let j = 0; j < pcaTextArr[i].children.length; j++) {
                    for (let x = 0; x < pcaTextArr[i].children[j].children.length; x++) {
                        this.restaurants.push({'value':pcaTextArr[i].value+' '+pcaTextArr[i].children[j].value+' '+pcaTextArr[i].children[j].children[x].value})
                    }
                }
            }
            console.log(this.restaurants);
            
        }
    },
    mounted() {
        console.log(pcaTextArr);
        this.restaurantsfz()
        // this.restaurants=pcaTextArr.map((terminal) => {
        //     pcaTextArr.children
        //     // return {
        //     //     value: terminal.contact +'   '+ terminal.client +'   '+terminal.telephone+'   '+terminal.wechat,
        //     // };
        // });
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.userId = JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.requestData.ascribedUser.push(this.userId);
        try {
            this.requestData.id = parseInt(this.$route.query.id);
        } catch (err) {
            this.requestData.id = 0;
            console.log('未获取id');
        }

        if (this.requestData.id == 0) {
            this.BtnTitle = '保存新增数据';
        } else {
            this.BtnTitle = '保存修改数据';
        }

        this.QueryPageData();
    }
}
</script>
<style>
body {
    margin: 0;
    padding: 0;
}

.operationMCR-Box {
    background-color: #fff;
    padding: 30px 30px 20px 0px;
    border-radius: 10px;
    min-height: 800px;
}

.operationMCR-topOper {
    text-align: right;
    padding: 0 10px 20px 0px;

}

.operationMCR-Box .el-date-editor.el-input {
    width: 100%;
}

.operationMCR-Box .el-select {
    width: 100%;
}
.operationMCR-Box .el-cascader{
    width: 100%;
}

.operationMCRtitle {
    font-size: 17px;
    font-weight: 600;
    color: #555;
    margin-left: 30px;
    margin-bottom: 25px;
}
</style>