var util = require('../../../utils/util.js')
const app = getApp();
Page({

  data: {
    customerNameList: [
      // {id: 11, name: "海文牧场"}, {id: 22, name: "成宏牧场"}, {id: 32, name: "瑞福牧业"}
    ],
    customerIndex:'',
    customerId:'',
    receiverNameList: [
      // {id: 56, name: "苗舒怡"},{id: 57, name: "颛孙洋洋"},{id: 58, name: "李涛"}
    ],
    receiverIndex:'',
    receiverId:'',
    nextNameList: [
      // {id: 222, name: "拜访"}, {id: 223, name: "远程服务"}, {id: 224, name: "现场服务"}
    ],
    nextIndex:'',
    nextId:'',
    groupId: '', 
    groupName: '',
    typeNameList: [
      // {id: 225, name: "定时回访",checked:true,disabled:false},
      // {id: 226, name: "服务回访",checked:false,disabled:false},
      // {id: 227, name: "投诉回访",checked:false,disabled:false}
    ],
    
    allDisabled:true,
    receiverShow:false,
    r_txt_Show:false,
    receiverChoose:'false',
    telephone:"",
   
   
 
    rules: {
      customerName: [{ required: true, message: '客户必填', trigger: 'blur' }],
      tdate: [{ required: true, message: '日期必填', trigger: 'blur' }],
      visiterName: [{ required: true, message: '回访人必填', trigger: 'blur' }],
 
      receiverName: [{ required: true, message: '被回访人必填', trigger: 'blur' }],
      receiverTel: [{ required: true, message: '电话必填', trigger: 'blur' }],
      typeIdsArr: [{ required: true, message: '回访类型必填', trigger: 'blur' }],
      statusName: [{ required: true, message: '回访状态必填', trigger: 'blur' }],
      content: [{  required: true, message: '情况说明必填', trigger: 'blur' }],
    },
    // 新增/编辑
    create: {
        dialogStatus: '',
        temp: {
           customerId: '', 
           customerName: '', 
           groupId: '', 
           groupName: '', 
           tdate: util.getToday(), 
           visiterId: '', 
           visiterName: '', 
           receiverId: '', 
           receiverName: '', 
           receiverTel: '', 
           remark: '', 
           content: '', 
           nextId: '', 
           nextName: '', 
           statusName: '', 
           typeIdsArr:'',
           typeIds:'',

           created: util.getToday(), 
           receiverChoose: 'true' 
        },
        
    }
  },

  onLoad: function (options) {
    // 表单初始化
    wx.lin.initValidateForm(this)
 
    var id = options.id;
    //获取编辑内容
    util.getDataByName({ name:'getTelvisitById', parammaps: {"id":id} }, this.getShowList)

    
  },

  getShowList:function(res){
    console.log('展示数据======>', res.data.list)
    var customerId = res.data.list[0].customerId
    this.setData({
      ['create.temp']:  res.data.list[0],
   
      customerId: res.data.list[0].customerId, 
      // receiverId: res.data.list[0].receiverId, 
      nextId: res.data.list[0].nextId
    })
    
    //下一步
    util.getDataByName({ name: 'getDictListSelect4', parammaps: { "pid": "55" } }, this.getPickerList3)
    //回访类型
    util.getDataByName({ name: 'getDictListSelect2',  parammaps: { "pid": "56" } }, this.getPickerList4)
     //获取被回访人
     //util.getDataByName({name: 'getContacts',returntype: 'Map',parammaps: { customerId: customerId }}, this.getPickerList2)

    
  },
 
  // getPickerList2:  function (res) {
  //   console.log('被回访人下拉数据======>', res.data.list)
  //   const id = this.data.receiverId
  //   const receiverIndex = res.data.list.findIndex(obj => obj.id == id) 
  //   this.setData({
  //     receiverNameList: res.data.list,
  //     receiverIndex: receiverIndex
  //   })
  // },
  getPickerList3:  function (res) {
    console.log('下一步下拉数据======>', res.data.list)
    const id = this.data.nextId
    console.log('下一步id======>',id)
    const nextIndex = res.data.list.findIndex(obj => obj.id == id) 
    this.setData({
      nextNameList: res.data.list,
      nextIndex: nextIndex
    })
  },
  getPickerList4:  function (res) {
    console.log('回访类型下拉数据======>', res.data.list)
      const typeIds = this.data.create.temp.typeIds

     var Idsarr  = typeIds.split(",")
     console.log('Idsarr====>', Idsarr)
      
      res.data.list.map(function(i){
        return i.checked = false
      })
        
      res.data.list.map(function(i){
        Idsarr.forEach(function(j){
          if(i.id == j){
            return i.checked = true
          }
        })
      })
      res.data.list.map(function(i){
        return i.disabled = false
      })
    this.setData({
      typeNameList: res.data.list
    })
  },
  
  //日期选择触发
  on_tdate_tap:function(e){
    this.setData({
      ['create.temp.tdate']:e.detail.value
    })
  },
   
  //下拉框：被回访人
  change_receiver:function(e){
    console.log('receiver的选项', e.detail.value)
    var newId = this.data.receiverNameList[e.detail.value]['id']
     this.setData({
       receiverIndex: e.detail.value,
       receiverId: newId,
       ['create.temp.receiverId']: newId,
     })
  },
//多选：回访类型
  change_typeName:function(e){
    const status = e.detail.checked
    const id = e.detail.key
    var typeNameList = this.data.typeNameList
    
    typeNameList.map(function(i){
        if(i.id == id){
          return i.checked = status
        }
    })
    this.setData({
      typeNameList:typeNameList
    })
  

  },
  //下拉框：下一步计划
  change_next:function(e){
    console.log('next的选项', e.detail.value)
    var newId = this.data.nextNameList[e.detail.value]['id']
     this.setData({
       nextIndex: e.detail.value,
       nextId: newId,
       ['create.temp.nextId']: newId,
     })
  },


  
//接待人文本框输入
change_receiver_input:function(e){
  var value =e.detail.value
  var customerId = this.data.customerId
  console.log(value)
  //接待人列表框
  util.getDataByName({ name:'getContactsByNameApp',parammaps: {"customerId":customerId,"contactName":value,} }, this.getPickerList2)
},

getPickerList2:  function (res) {
  console.log('接待人下拉数据======>', res.data.list)
  var receiverNameList = res.data.list
  this.setData({
    receiverShow:true,
    allDisabled:false,
    receiverNameList: receiverNameList
  })
  if(receiverNameList !== null){
    this.setData({r_txt_Show:false})
  } else {
    this.setData({r_txt_Show:true})
  }
},

//接待人列表点击
on_rece_tap: function (e) {
  console.log("接待人列表点击",e )
  var newId = e.currentTarget.dataset.id;
  var name = e.currentTarget.dataset.name;
  var that = this

  this.setData({
    receiverShow:false,
    allDisabled:true,
    ['create.temp.receiverName']: name,
    ['create.temp.receiverId']: newId,
    receiverChoose: 'true' 
  })
  //获取电话
  util.getDataByName({name: 'getTelById',returntype: 'Map',parammaps: { id: newId }
  }, function(e){
    console.log(e)
 
    var telephone = e.data.list[0].telephone
    that.setData({
      ['create.temp.receiverTel']: telephone, 
      telephone: telephone 
    })
  })
 
},
//接待人完成
confirm_receiver_input:function(e){
  console.log("接收人直接输入")
  this.setData({
    receiverShow:false,
    allDisabled:true,
    receiverChoose: 'false' 
  })
},

  //保存
  submit:function(e){
    
    var detail_value = e.detail.values
    var detail_errors = e.detail.errors
    var detail_errors = e.detail.errors
    console.log("detail_value",detail_value)
    console.log("create.temp",this.data.create.temp)


    const submit_data = Object.assign({}, this.data.create.temp, detail_value)

    const typeNameList = this.data.typeNameList 
   
    console.log("保存发送：",submit_data)
    console.log("保存typeNameList：",typeNameList)

    var typeIdsArr = []
    typeNameList.forEach(function(i){
      if(i.checked == true){
        typeIdsArr.push(i.id)
      }
    })
    var typeIds = typeIdsArr.join(",")

    console.log("typeIds",typeIds)
    submit_data.typeIds = typeIds
    submit_data.receiverChoose = this.data.receiverChoose
 
    var send_data = {
      "common": { "returnmap": "0" },
      "data": [
        {
          "name": "insertContactsNewApp", "type": "e",
          "parammaps": {
            "customerId":submit_data.customerId,
            "contactName": submit_data.receiverName,
            "telephone": submit_data.receiverTel,
            "address": "",
            "remark": submit_data.remark,
            "receiverChoose": this.data.receiverChoose 
          }
        },
        {
          "name": "updateTelvisitApp",
          "resultmaps": {
            "list": [submit_data]
          },
          "children": [{
            "name": "updateTelvisitApp",
            "type": "e",
            "parammaps": {
              "tdate": "@updateTelvisitApp.tdate",
              "visiterId": "@updateTelvisitApp.visiterId",
              "receiverName": "@updateTelvisitApp.receiverName",
              "receiverTel": "@updateTelvisitApp.receiverTel",
              "typeIds": "@updateTelvisitApp.typeIds",
              "statusName": "@updateTelvisitApp.statusName",
              "remark": "@updateTelvisitApp.remark",
              "content": "@updateTelvisitApp.content",
              "nextId": "@updateTelvisitApp.nextId",
              "id": "@updateTelvisitApp.id"


            }
          }]
        }
      ]
    }

     


    //验证必填项是否为空
    if(submit_data.customerId == ""){
      wx.showToast({title: '客户名称必填',icon: 'none',duration: 2000})
    } else if(submit_data.tdate == ""){
      wx.showToast({title: '回访日期必填',icon: 'none',duration: 2000})
    } else if(submit_data.receiverName == ""){
      wx.showToast({title: '被回访人必填',icon: 'none',duration: 2000})
    } else if(submit_data.receiverTel == ""){
      wx.showToast({title: '被回访人电话必填',icon: 'none',duration: 2000})
    } else if(submit_data.typeIds == ""){
      wx.showToast({title: '回访类型必填',icon: 'none',duration: 2000})
    } else if(submit_data.statusName == ""){
      wx.showToast({title: '回访状态必填',icon: 'none',duration: 2000})
    } else if(submit_data.content == ""){
      wx.showToast({title: '情况说明必填',icon: 'none',duration: 2000})
    } else {
      if( wx.getStorageSync('isLoading')  == "true"){
        wx.showToast({
          title: '正在保存中，请稍等！',
          icon: 'none',
          duration: 2000
        })
      } else {
        util.execDataByConfig(send_data, this.getListSuccess)
      }
    }
  },

  getListSuccess:  function (res) {
    console.log('table数据======>', res)
    if (res.msg !== 'fail') {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000,
        success: function(){
          wx.redirectTo({ url:"../telephoneFollow/telephoneFollow"})
        }
      })
    } else {
      wx.showToast({
        title: '保存失败'+res.data,
        icon: 'error',
        duration: 2000,
      })
    }
  },

 
  
  onReady: function () {

  },

  
  onShow: function () {

  },

 
  onHide: function () {

  },

   
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 
  onShareAppMessage: function () {

  }
})