import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import { recommendClient, getTypeData } from '@services/client'
import { getItemList } from '@services/item'
import { getCardList } from '@services/card'
import { savePoint, updatePoint } from '@services/common'

import { connect } from '@tarojs/redux'
@connect(({ user, card, project }) => ({ ...user, ...card, ...project }))
export default class Index extends Component {
  config = {
    navigationBarTitleText: '新增客户'
  }
  state = {
    name: '',//客户姓名 
    sex: '',//性别
    phone: '',//电话
    floor: '',//楼盘
    adviser: '',//置业顾问
    type: '',//需求
    property: '',//物业
    price: '',//价格
    remarks: '',//备注
    sexArray: ['请选择', '男', '女'],
    sexID: 0,
    floorArray: ['请选择'],
    floorID: 0,
    adviserArray: ['请选择'],
    adviserID: 0,
    typeArray: ['(选填)'],
    typeID: 0,
    propertyArray: ['(选填)'],
    propertyID: 0,
    priceArray: ['(选填)'],
    priceID: 0,
    date: '请选择',
    sexColor: 'color:#716D6D',
    floorColor: 'color:#716D6D',
    typeColor: 'color:#716D6D',
    propertyColor: 'color:#716D6D',
    priceColor: 'color:#716D6D',
    timeColor: 'color:#716D6D',
    recordId: null,
    radioList: [
      {
        value: '1',
        text: '男',
        checked: false,
        color: '#ffc70c'
      },
      {
        value: '2',
        text: '女',
        checked: false,
        color: '#ffc70c'
      }
    ],
    reType: '',
    intention: ''
  }
  componentWillMount() {
    // const defaultHouseVal = Taro.getStorageSync('targetHouse')

    const { type } = this.$router.params

    this.setState({
      reType: type,

    }, () => {
      console.log(this.state.sex, "sex")
      console.log('buildingName' + this.props.proList.records[0].buildingName)
      if (this.state.reType != 'index') {
        this.setState({
          intention: this.props.projectDetail.buildingName ? this.props.projectDetail.buildingName : this.props.proList.records[0].buildingName,
          floor: this.props.projectDetail.buildingId ? this.props.projectDetail.buildingId : this.props.proList.records[0].buildingId
        }, () => {
          if (this.state.floorID != 0 || this.state.intention) {
            this.loadCardList()
          } else {
            this.setState({
              adviserArray: [{ name: '请选择', id: 0 }]
            })
          }
        })
      }
    })

    this.loadData()

    savePoint({
      event: 'recommend',
      eventType: 'agent',
      propertyName: '新增客户',
      data: '{}'
    }).then(res => {
      this.setState({
        recordId: res.recordId
      })
      console.log('新增客户')
    })
  }
  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

  loadData() {

    this.loadAgentList()


    this.loadSelectOpts()
  }
  loadAgentList() {
    // //获取楼盘列表

    const params = {
      pageNumber: 1,
      pageSize: 50,
      cityId: this.$router.params.cityId || ''
    }
    getItemList(params).then(res => {
      res.records.unshift({ buildingName: '请选择', orderNo: 0 })
      this.setState({
        floorArray: res.records,//楼盘
      }, () => {
        console.log(this.state.floorArray)
      })
    })

  }

  loadCardList() {
    const params = {
      pageNumber: 1,
      pageSize: 50,
      buildingId: this.state.floor || this.props.projectDetail.buildingId
    }
    getCardList(params).then(res => {
      res.records.unshift({ name: '请选择', id: 0 })
      console.log(res, "res")
      this.setState({
        adviserArray: res.records
      })
    })
  }

  loadSelectOpts() {
    // 获取下拉配置
    getTypeData().then(res => {
      res.priceRange.unshift({ name: '(选填)', id: 0 })
      res.demandType.unshift({ name: '(选填)', id: 0 })
      res.realtyManageType.unshift({ name: '(选填)', id: 0 })
      this.setState({
        priceArray: res.priceRange,//价格
        typeArray: res.demandType,//需求
        propertyArray: res.realtyManageType//物业
      })
    })
  }
  BindInfo(e) {
    console.log(e.currentTarget.dataset.id)
    switch (e.currentTarget.dataset.id) {
      case 'name':
        this.setState({
          name: e.detail.value
        })
        break;
      case 'sex':
        this.setState({
          sex: e.detail.value
        })
        break;
      case 'phone':
        this.setState({
          phone: e.detail.value
        })
        break;
      case 'remarks':
        this.setState({
          remarks: e.detail.value
        })
        break;
      default:
        break;
    }
  }
  // 清空inpput值
  clearInputEvent() {
    this.setState({
      name: '',
      phone: '',
      sexID: 0,
      // sex: '',
      floorID: 0,
      floor: '',
      adviserID: 0,
      adviser: '',
      typeID: 0,
      type: '',
      property: '',
      propertyID: 0,
      price: '',
      priceID: 0,
      remarks: '',
      date: '',
      sexColor: 'color:#716D6D',
      floorColor: 'color:#716D6D',
      typeColor: 'color:#716D6D',
      propertyColor: 'color:#716D6D',
      priceColor: 'color:#716D6D',
      timeColor: 'color:#716D6D',
      adviserColor: 'color:#716D6D',
    })
  }
  Alert(content, title) {
    title = title ? title : "温馨提示";
    content = content.toString();
    Taro.showModal({
      title: title,
      content: content,
      confirmColor: '#4f93ce',
      showCancel: false,
    })
  }
  Save() {
    const { projectDetail: { buildingId }, userInfo: { person: { personId } } } = this.props
    const { name, sex, phone, floor, adviser, date, type, property, price, remarks } = this.state
    if (name == "") {
      this.Alert('请输入客户姓名')
      return false;
    }
    if (sex == "") {
      this.Alert('请选择客户性别')
      return false;
    }
    if (phone == "") {
      this.Alert("请输入客户电话");
      return false;
    }
    if (!(/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(phone)) || phone.length != 11) {
      this.Alert('请输入正确的手机号码');
      return false;
    }
    if (floor == "") {
      this.Alert("请选择意向楼盘");
      return false;
    }
    // if (adviser == "") {
    //   this.Alert("请选择置业顾问");
    //   return false;
    // }
    // if (date == "请选择") {
    //   this.Alert("请选择预约到访时间");
    //   return false;
    // }
    var param = {
      name,//姓名
      sex,//性别
      phone,//电话
      intention: floor,//意向楼盘
      demandType: type,//需求类型
      realtyManageType: property,//物业类型
      price,//价格
      appointmentTime: '',//时间
      describe: remarks,//客户描述
      realtyConsultant: adviser,//置业顾问
      recommendPerson: personId,
      buildingId: buildingId || floor,
      status: 1
    }
    recommendClient(param).then(res => {
      Taro.showToast({
        title: '提交成功'
      })
      this.clearInputEvent()
      Taro.navigateTo({ url: '/pages/agent/client/index' })//测试用
    })

  }
  // 性别
  bindSexChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.detail.value != 0) {
      this.setState({
        sexID: e.detail.value,
        sex: e.detail.value,
        sexColor: 'color:#000'
      })
    } else {
      this.setState({
        sexID: e.detail.value,
        sex: "",
        sexColor: 'color:#716D6D'
      })
    }
  }
  // 楼盘
  bindFloorChange(e) {
    var index = e.detail.value;
    var ID = this.state.floorArray[index].buildingId;
    if (e.detail.value != 0) {
      this.setState({
        floorID: e.detail.value,
        floor: ID,
        floorColor: 'color:#000'
      }, () => {
        if (this.state.floorID != 0 || this.state.intention) {
          this.loadCardList()
        } else {
          this.setState({
            adviserArray: [{ name: '请选择', id: 0 }]
          })
        }
      })

    } else {
      this.setState({
        floorID: e.detail.value,
        floor: "",
        floorColor: 'color:#716D6D'
      })
    }
  }
  // 置业顾问
  bindAdviserChange(e) {

    var index = e.detail.value;
    var ID = this.state.adviserArray[index].id;
    if (e.detail.value != 0) {
      this.setState({
        adviserID: e.detail.value,
        adviser: ID,
        adviserColor: 'color:#000'
      })
    } else {
      this.setState({
        adviserID: e.detail.value,
        adviser: "",
        adviserColor: 'color:#716D6D'
      })
    }

  }
  // 物业
  bindPropertyChange(e) {
    var index = e.detail.value;
    var ID = this.state.propertyArray[index].id;
    if (e.detail.value != 0) {
      this.setState({
        propertyID: e.detail.value,
        property: ID,
        propertyColor: 'color:#000'
      })
    } else {
      this.setState({
        propertyID: e.detail.value,
        property: "",
        propertyColor: 'color:#716D6D'
      })
    }
  }
  // 需求
  bindTypeChange(e) {
    var index = e.detail.value;
    var ID = this.state.typeArray[index].id;
    if (e.detail.value != 0) {
      this.setState({
        typeID: e.detail.value,
        type: ID,
        typeColor: 'color:#000'
      })
    } else {
      this.setState({
        typeID: e.detail.value,
        type: "",
        typeColor: 'color:#716D6D'
      })
    }
  }
  // 价格
  bindPriceType(e) {
    var index = e.detail.value;
    var ID = this.state.priceArray[index].id;
    if (e.detail.value != 0) {
      this.setState({
        priceID: e.detail.value,
        price: ID,
        priceColor: 'color:#000'
      })
    } else {
      this.setState({
        priceID: e.detail.value,
        price: "",
        priceColor: 'color:#716D6D'
      })
    }
  }
  //到访时间
  bindDateChange(e) {
    this.setState({
      date: e.detail.value,
      timeColor: 'color:#000'
    })
  }
  // 性别
  radioChange(e) {
    console.log(e.detail.value)
    this.setState({
      sex: e.detail.value
    })
  }
  render() {
    const { reType } = this.state
    return (
      <View className='recommend__customers'>
        <View className='submit__infor ani'>
          <View className='info info__1'>
            <Text className='customers__txt'>客户姓名</Text>
            <Input className="input customers__name" name="name" data-id='name' value={this.state.name} onInput={this.BindInfo.bind(this)} placeholder="请输入" />
          </View>
          <View className='info info__2'>
            <Text className='customers__txt'>客户性别</Text>
            <View className='radio-list input'>
              <RadioGroup onChange={this.radioChange}>
                {this.state.radioList.map((item, i) => {
                  return (
                    <Label className='radio-list__label' for={i} key={i}>
                      <Radio className='radio-list__radio' color={item.color} value={item.value} checked={item.checked} >{item.text}</Radio>
                    </Label>
                  )
                })}
              </RadioGroup>
            </View>
          </View>
          <View className='info info__3'>
            <Text className='customers__txt'>电话号码</Text>
            <Input type='number' className="input customers__sex" name="phone" data-id="phone" value={this.state.phone} onInput={this.BindInfo.bind(this)} placeholder="请输入" />
          </View>
          <View className='info info__4'>
            <Text className='customers__txt'>意向楼盘</Text>
            {
              reType == 'index' ? (<Picker className='input customers__name' onChange={this.bindFloorChange} value={this.state.floorID} range={this.state.floorArray} range-key="buildingName">
                <View class="picker" style={this.state.floorColor}>
                  {this.state.floorArray[this.state.floorID].buildingName}
                </View>
              </Picker>) : (<Input className="input customers__name" style='color:#999;' disabled='disabled' name="name" value={this.state.intention} onInput={this.bindFloorChange.bind(this)} placeholder="" />)
            }

          </View>
          <View className='info info__4__1'>
            <Text className='customers__txt'>置业顾问</Text>
            <Picker className='input customers__adviser' onChange={this.bindAdviserChange} value={this.state.adviserID} range={this.state.adviserArray} range-key="name">
              <View class="picker" style={this.state.adviserColor}>
                {this.state.adviserArray[this.state.adviserID].name}
              </View>
            </Picker>
          </View>

          <View className='info info__6'>
            <Text className='customers__txt'>客户描述</Text>
            <Input className="input customers__remarks" data-id="remarks" name="remarks" value={this.state.remarks} onInput={this.BindInfo.bind(this)} placeholder="(选填)" />
          </View>
        </View>
        <View className='submit-btn'>
          <Button type="primary" className='submit' onClick={this.Save}>提交</Button>
        </View>

      </View>
    );
  }
}