//Page Object
import agentApi from '../../apis/agent'
let app =  getApp();

  
let KEYPOP = {
    user_phone_belong:[{
        id:'',
        name:'海外'
    },{
        id:'',
        name:'国内'
    }],
    buy_house_address:[{
        id:'',
        name:'香洲区'
    },{
        id:'',
        name:'斗门区'
    }],
    purpose:[{
        id:'',
        name:'改善'
    },{
        id:'',
        name:'刚需'
    }],
    rooms:[{
        id:'',
        name:'1室'
    },{
        id:'',
        name:'2室'
    },{
        id:'',
        name:'3室'
    }]
}

Page({
    data: {
        popArray:[],
        show: false,
        genterShow: false,
        pp_type:'',
        value: 0,
        isHideNum:false,
        StrGenter: ['男性', '女性'],
        genderMap: {
            M: '男性',
            F: '女性'
        },
        first_budget_p1:'',
        first_budget_p2:'',
        ideal_area_1:'',
        ideal_area_2:'',
        params:{
            user_name:"",
            user_id: "",
            user_phone: "",
            user_phone_belong: "",
            user_gender: "M",
            user_wish: 0,
            user_requires: "",
            first_budget: "",
            total_budget: "",
            buy_house_address: "",
            ideal_area: "",
            purpose: "",
            rooms: "",
            property_type: "",
            remarks: "",
            cur_step: "",
            is_valid: "",
            agency_user_id: getApp().globalData.userinfo.user_id
        }
    },
    onLoad: function(options) {
        // const { customer_id, agency_user_id } = options
        const { id } = options 

        console.log(options)
        // if (customer_id && agency_user_id) {
            this.fetchCustomerDetail(id)
        // }
    },
    fetchCustomerDetail (id) {
        agentApi.fetchCustomerDetail({id}).then(res => {
            if (res.data) {
                const exg = /(\d*)-(\d*)/
              this.setData({
                is_edit: true,
                params: res.data,
                first_budget_p1: res.data.first_budget ? res.data.first_budget.match(exg)[1] : '',
                first_budget_p2: res.data.first_budget ? res.data.first_budget.match(exg)[2] : '',
                ideal_area_1: res.data.ideal_area ? res.data.ideal_area.match(exg)[1] : '',
                ideal_area_2: res.data.ideal_area ? res.data.ideal_area.match(exg)[2] : ''
              })
            }
          }).finally(data=>{
            wx.hideLoading()
          })
    },
    bindInput:function (event) {
        var obj = {},
        key = event.target.dataset['key'];
        obj[key] = event.detail.value;
        this.setData(obj);
    },
    onRateChange(event) {
        this.setData({
            'params.user_wish':event.detail
        })
    },
    changeSwitch:function (e) {
        let isHideNum = e.detail.value
        this.setData({
            isHideNum
        })
    },
    showPopup(e) {
        let {type} = e.currentTarget.dataset
         
        this.setData({ 
            show: true,
            pp_type:type,
            popArray:KEYPOP[type]
        });
    },

    getUserList(){
        agentApi.fetchUserByPhone({
            phone_num: this.data.params.user_phone
        }).then(res => {
            if (res.code===0&&res.data) {
                this.setData({ 
                    show: true,
                    popArray:[{
                        name: res.data.phone,
                        item: res.data
                    }]
                });
            }
            else{
                app.ShowModel('提示','获取该手机号码用户失败，无法新增客户');
            }
        }).finally(() => {
            wx.hideLoading()
        })
       
    },
    handleItem(e){
        let {val,item} = e.currentTarget.dataset
        let params = this.data.params
        if (item) {
            params['user_gender'] = item.gender
            params['user_phone_belong'] = item.phone_belong
            params['user_id'] = item.user_id
        }
        else{
            params[this.data.pp_type] = val
        }
        let obj = {
            show: false,
            params
        }
       
        console.log(obj);
        this.setData(obj)
    },
    onClose() {
        this.setData({ show: false });
    },
    handleSubmit () {
        if (this.data.is_edit) {
            return this.updateCustomer()
        }
        return this.addCustomer()
    },
    addCustomer(){
        this.setData({
            'params.first_budget':`${this.data.first_budget_p1}-${this.data.first_budget_p2}万元`,
            'params.ideal_area':`${this.data.ideal_area_1}-${this.data.ideal_area_1}平`
        })

        let params = this.data.params
        // if (!params['user_id']) {
        //     return app.ShowModel('提示',`请输入电话号码后选择用户信息`);
        // }
        let NONULL = [{
           name:'手机号码',
           id: 'user_phone'
        },{
            name:'姓名',
            id: 'user_name'
        }]
        for (let i = 0; i < NONULL.length; i++) {
            const item = NONULL[i];
            if (!params[item.id]) {
                return app.ShowModel('提示',`${item.name}不能为空`);
            }
        }
        agentApi.addCustomer(params).then(res => {
            console.log(res)
            if (res.code == 0) {
                wx.showModal({
                    title: '提示',
                    content: '添加成功',
                    showCancel: false,
                    success (res) {
                        wx.navigateBack()
                    }
                })
            }
            else{
                app.ShowModel('提示','添加失败，请检查输入信息是否有误或重复添加');
            }
        }).catch(() => {
            app.ShowModel('提示','添加失败，请检查输入信息是否有误或重复添加');
        }).finally(() => {
            wx.hideLoading()
        })
    },
    updateCustomer () {
        this.setData({
            'params.first_budget':`${this.data.first_budget_p1}-${this.data.first_budget_p2}万元`,
            'params.ideal_area':`${this.data.ideal_area_1}-${this.data.ideal_area_2}平`
        })
        let params = this.data.params
        if (!params.user_name) {
            app.ShowModel('姓名不能为空')
            return
        }
        agentApi.updateCustomer(params).then(res => {
            if (res.code == 0) {
                wx.showModal({
                    title: '提示',
                    content: '修改成功',
                    showCancel: false,
                    success (res) {
                        wx.navigateBack()
                    }
                })
            } else {
                app.ShowModel('修改失败');
            }
        })
    },
    //item(index,pagePath,text)
    onTabItemTap:function(item) {

    },
    showGender () {
        this.setData({
            genterShow: true
        })
    },
    changeGenter (e) {
        console.log(e)
        let { value } = e.detail
        value = this.data.StrGenter[value]
        this.setData({
            genterShow: false,
            'params.user_gender': value === '男性' ? 'M' : 'F'
        })
    },
    showText () {
        this.setData({
            textShow: true
        })
    },
    hideText () {
        this.setData({
            textShow: false
        })
    },
});
  
