// TUIKit-WChat/Chat/index.js
import logger from '../../utils/logger';
import constant from '../../utils/constant';
const dayjs = require("../../utils/dayjs.js");
import {
  getRate
} from "../../../../api/consultOrder"
// eslint-disable-next-line no-undef
import {
  fllowDoctor,
  notfllowDoctor,
  doctorDetail,
} from "../../../../api/consultExpert"


import {
  chatMsg,serviceChatMsg
} from "../../../../api/common"
import {throttle} from "../../../../utils/util"

const app = getApp();
const inputStyle = `
  --padding: 25px
`;

let newInputStyle = `
--padding: 0px
`;

const setNewInputStyle = (number) => {
  const height = number;
  newInputStyle = `--padding: ${height}px`;
};
let pageY = 0;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    currentConversationID: {
      type: String,
      value: '',
      observer(currentConversationID) {
        this.setData({
          conversationID: currentConversationID,
        });
      },
    },
    order_inquiry_id: {
      type: String,
      value: '',
      observer(order_inquiry_id) {
        this.setData({
          order_inquiry_id,
        });
      },
    },
    fromType: {
      type: String,
      value: '',
      observer(newval) {
        this.setData({
          fromType: newval
        });
      },
    },
    inquiry_type: {
      type: String,
      value: '',
      observer(inquiry_type) {
        this.setData({
          inquiry_type
        });
      },
    },
    hasCallKit: {
      type: Boolean,
      value: false,
      observer(hasCallKit) {
        this.setData({
          hasCallKit,
        });
      },
    },
  },

  lifetimes: {
    attached() {
      if (app?.globalData?.reportType === constant.OPERATING_ENVIRONMENT) {
        this.setData({
          showTips: true,
        });
      }
    },
    ready() {
      
    }
  },
  pageLifetimes: {
    show: function() {
      this.setData({
        img_host:app.hostConfig().imghost
      });
      wx.onNetworkStatusChange((res) => {
        let msg = ''
        if (!res.isConnected) {
          msg = '当前网络不可用，请检查你的网络设置'
        } else if (res.networkType === 'none') {
          msg = '网络开小差了,请在网络良好后重试'
        }
        if (msg) {
          wx.showToast({
            title: msg,
            icon: 'none',
          })
        }
      })
      console.log(this.data.order_inquiry_id);
      this.handleChatMsg(this.data.order_inquiry_id);
      
     
    },
    hide: function() {
    this.setData({
      showAgain:false
    })
      // 页面被隐藏
    },
    resize: function(size) {
      // 页面尺寸变化
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    serviceInfo:{},
    conversationName: '',
    isEvaluation:false,
    conversation: {},
    doctor_info: '',
    messageList: [],
    isShow: false,
    showImage: false,
    showChat: true,
    commentDetail: null,
    conversationID: '',
    order_inquiry_id: '',
    comment_id:'',//评论订单id
    fromType: '',
    inquiry_type: '',
    inquiry_mode:'',
    patient_family_data: {},
    rest_rounds: 0,//剩余回合数
    msgData:{
     msg_round:0,
     msg_type:1
    },
    message: '',
    doctorChatData: {
      is_evaluation: false,
      inquiry_status: '',
      follow: false,
      times_number: 0,
      duration: 0,
      reception_time: null,
      rest_time: 0,
      inquiry_mode:'',
      doctor_id: '',
      doctor_user_id:'',
      timeData: {},
    },
    doctorDetail: {
      avatar: '',
      be_good_at: '',
      user_name: '',
      doctor_title_name: '',
      department_custom_name: '',
      doctor_inquiry_config: [],
      hospital: {},
      doctor_id:'',
      multi_point_status: '',
      multi_point_enable:0
    },
    current_inquiry_config: {},
    config: {
      sdkAppID: '',
      userID: '',
      userSig: '',
      type: 1,
      tim: null,
    },
    unreadCount: 0,
    hasCallKit: false,
    viewData: {
      style: inputStyle,
    },
    showHead: false,
    showDialog: false,
    overlay: false,
    blockHeight:"300rpx", //菜单卡片高度
    KeyboardHeight: 0,
    showPop: true,
    showTips: false,
    showGroupTips: false,
    showAll: false,
    displayServiceEvaluation: false,
    score: 0,
    startX: 0, //touchStart开始坐标
    startY: 0,
    isFlag:true,
    isEnd:false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleGetRate(id) {
      getRate(id).then(data => {
        if (data) {
          this.setData({
            isEvaluation:true,
            commentDetail: data,
            score: data.avg_score
          })
        }


      })
    },
    openHelp() {
      this.setData({
        showDialog: true
      })
    },
    closeHead() {
      this.setData({
        showHead: true
      })
    },
    // 显示遮罩层
    showModal() {
      this.setData({
        hideModal: true,
        blockHeight:"830rpx"
      })
    },
    // 隐藏遮罩层
    hideModal() {

      this.setData({
        hideModal: false,
       blockHeight:"300rpx"
      })
    },
    touchstart(e) {
      this.setData({
        startX: e.changedTouches[0].clientX,
        startY: e.changedTouches[0].clientY
      })
    },
    angle(start, end) {
      var _X = end.X - start.X,
        _Y = end.Y - start.Y;
      //返回角度 Math.atan()返回数字的反正切值
      return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    touchend(e) {
      let {startX,startY} = this.data;
      let slidingRange = 45; //
      let touchMoveX = e.changedTouches[0].clientX;
      let touchMoveY = e.changedTouches[0].clientY;
      let angle = this.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
      //为了方便计算取绝对值判断
      if (Math.abs(angle) > slidingRange && touchMoveY < startY) {
       
        this.showModal()
        // 向上滑动
      };
      if (Math.abs(angle) > slidingRange && touchMoveY > startY ) {
        this.hideModal()
        // 向下滑动
      }
    },
    onClose() {
      this.setData({
        showPop: false,
      });
    },
    changeTimeStatus(event){
     if(event.detail){
      this.setData({
        isEnd:true
      })
     }
    },
    goExpertDetail:throttle(function(){
      let id = this.data.doctorChatData.doctor_id;
      // wx.redirectTo({
      //   url: "/pages/expertDetail/expertDetail?doctor_id=" + id
      // })
      app.method.navigateTo({
          url: "/patient/pages/expertDetail/expertDetail?doctor_id=" + id
        })
    }),
    loopArr(arr,type){
      let inquiry_mode='';
      let inquiry_price='';
      let recieveStatus='';
      let order_type=type;
      for (let i = 0; i <  arr.length; i++) {
        if(arr[i].inquiry_type==type){
          recieveStatus=arr[i].work_num_day-arr[i].times_number;
          inquiry_mode=arr[i].inquiry_mode;
          inquiry_price=arr[i].inquiry_price;
        }
      };
        //如果公益问诊 次数为0 则去看是否有专家问诊
        if(type==3 && recieveStatus==0){
          for (let i = 0; i <  arr.length; i++) {
            if(arr[i].inquiry_type==1){
              order_type=1;
              recieveStatus=arr[i].work_num_day-arr[i].order_inquiry_count;
              inquiry_mode=arr[i].inquiry_mode;
              inquiry_price=arr[i].inquiry_price;
              duration=arr[i].duration;
              work_num_day=arr[i].work_num_day;
              times_number=arr[i].times_number;
              order_inquiry_count=arr[i].order_inquiry_count;
            }
          }
        }
      this.setData({
          current_inquiry_config: {
          inquiry_type: order_type,
          inquiry_mode:inquiry_mode,
          inquiry_price:inquiry_price,
          recieveStatus:recieveStatus
        }
      })
    },
    formatInquiryStatus(arr){
      var  a='3';
      if(arr){
        for (var i = 0; i < arr.length; ++i) {
           if(arr[i].is_enable==1 && arr[i].inquiry_type==1){
              a='2'
          };
          if(arr[i].is_enable==1 && arr[i].inquiry_type==3){
            return '1'
          };
        }
     
      }
      return a
    },
    getDoctorDetail(id) {
      doctorDetail(id).then(data => {
        let obj = this.data.doctorDetail;
        for (const key in obj) {
          let item = `doctorDetail.${key}`
          this.setData({
            [item]: data[key]
          })
        };
        let doctor_inquiry_config = data.doctor_inquiry_config;
        let inquiryType=this.formatInquiryStatus(doctor_inquiry_config);
        if(inquiryType==1){
         this.loopArr(doctor_inquiry_config,3);
        }else if(inquiryType==2){
         this.loopArr(doctor_inquiry_config,1);
        }else{
         this.setData({
               current_inquiry_config:null
             })
        }
      //  if(data.is_img_expert_reception==1 && data.is_img_welfare_reception==1){
      //   this.loopArr(doctor_inquiry_config,3);
      //  // 1:专家问诊 2:快速问诊 3:公益问诊 4:问诊购药
      //   this.setData({
      //     isHide:true
      //   })
      // }else if(data.is_img_expert_reception==1 && data.is_img_welfare_reception==0){
      //   this.loopArr(doctor_inquiry_config,1);
            
      // }else if(data.is_img_welfare_reception== 1 && data.is_img_expert_reception==0){
      //    this.loopArr(doctor_inquiry_config,3);
      // }else{
      //   this.setData({
      //     current_inquiry_config:null
      //   })
      // }
      })
    },
    goOrderDetail:throttle(function(){
      let {
        order_inquiry_id
      } = this.data;
      // wx.redirectTo({
      //   url: '/pages/orderDetail/orderDetail?order_inquiry_id='+order_inquiry_id
      // })
      console.log("订单详情");
      app.method.navigateTo({
        url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+order_inquiry_id
      })
    }),
    getMessageRounds(event) {
      console.log('detail======')
      console.log(event)
      this.setData({
        msgData: event.detail
      })
      console.log(this.data.doctorChatData.times_number)
      if(this.data.doctorChatData.times_number>=0){
        let rest_rounds=this.data.doctorChatData.times_number-event.detail.msg_round;
        console.log("rest_rounds:"+rest_rounds)
        this.setData({
          rest_rounds:rest_rounds>=0?rest_rounds:0
        })
    
      }
    },
    onChangeTime(e) {
      this.setData({
        'doctorChatData.timeData': e.detail,
      });
    },
    toggleFllow() {
      if (this.data.doctorChatData.follow) {
        this.handenotfllowDoctor()
      } else {
        this.handelfllowDoctor()
      }
    },
    handleServiceChatMsg(id){
        serviceChatMsg(id).then(res=> {
            console.log(res)
             this.setData({
                 serviceInfo:res
             })
        })
    },
    handleChatMsg(id) {
      chatMsg(id).then(data => {
        this.handleServiceChatMsg(id);
      //   console.log("接口请求收到时间66666"+dayjs().format("YYYY-MM-DD HH:mm:ss:SSS"));
      // console.log(data);
      let promise=wx.$TUIKit.getUserProfile({
        userIDList: [data.doctor_user_id] 
      });
      promise.then(function(imResponse) {
        wx.setStorageSync('doctor_avatar',imResponse.data[0].avatar);
      });
        let obj = this.data.doctorChatData;
        for (const key in obj) {
          let item = `doctorChatData.${key}`
          this.setData({
            [item]: data[key]
          })
        };
        this.getDoctorDetail(data.doctor_id);
        let patient_family_data = {
          patient_name: data.patient_family_name,
          patient_sex: data.patient_family_sex,
          patient_age: data.patient_family_age
        };
        this.setData({
          patient_family_data: patient_family_data,
          inquiry_mode:data.inquiry_mode
        })
        let duration=''
        if( data.duration == 0){
          duration='不限时长';
        }else if((data.duration / 60)>0 && (data.duration / 60)<=1){
          duration=data.duration+"分钟内";
        }else{
          duration=(data.duration / 60) + "小时内";
        };
        console.log(duration);
        let number = data.times_number == 0 ? '不限次' : data.times_number + "回合";
        let message='';
       if(data.inquiry_type==4 || data.inquiry_type==2){
         message=`医生接诊后${duration}${number}沟通。超过5分钟未接诊，平台会在1个工作日内全额退还费用，如使用优惠劵，一并退回。`
       }else if((data.inquiry_type==1 && data.inquiry_mode!=2) || data.inquiry_type==3){
        message=`医生接诊后${duration}${number}沟通。医生超过24小时未接诊，平台会在1个工作日内全额退还费用，如使用优惠劵，一并退回`
       }else if(data.inquiry_type==1 && data.inquiry_mode==2){
        message=` 医生会在24小时内接诊，接诊后24小时内，可以和医生按沟通时间进行视频问诊，同时可进行图文、语音沟通且无回合限制。医生超过24小时未接诊，平台会在24小时后全额退还费用，如使用优惠劵，一并退回。`
       };
        this.setData({
          message:message
        })
        if (data.inquiry_status == 3) {
          this.setData({
            "doctorChatData.rest_time": -1 //待接诊 可以沟通
          });
          if (data.times_number == 0) {
            this.setData({
              "doctorChatData.times_number": -1
            })
          } else {
            this.setData({
              message_rounds: data.times_number
            })

          }

        } else if (data.inquiry_status == 4) {
          if (data.times_number == 0) {
            this.setData({
              "doctorChatData.times_number": -1
            })
          } else {
            this.setData({
              message_rounds: data.times_number
            })

          }
          if (data.duration != 0) {
            if (data.reception_time) {
              let endtime = dayjs(data.reception_time).add(data.duration, 'minute').format('YYYY-MM-DD HH:mm:ss');
              let nowtime = dayjs().format('YYYY-MM-DD HH:mm:ss');
              let countdown = dayjs(endtime).diff(nowtime, "millisecond");
              let countdownTime = countdown > 0 ? countdown : 0;
              console.log("countdownTime--------");
              console.log(countdownTime);
              this.setData({
                "doctorChatData.rest_time": countdownTime
              })
            } else {
              this.setData({
                "doctorChatData.rest_time": 0
              })
            }
          } else {
            this.setData({
              "doctorChatData.rest_time": -2 //接诊不限时间
            })
          }
        }
        // console.log("times_number:----"+data.times_number,this.data.msgData.msg_round)
        if(data.times_number>=0){
          let rest_rounds=data.times_number-this.data.msgData.msg_round;
          console.log("rest_rounds----:"+rest_rounds)
          this.setData({
            rest_rounds:rest_rounds>=0?rest_rounds:0
          })
      
        }
        if(this.data.isFlag){
          this.scrollBottom();
          this.setData({
            isFlag:false
          })
        }
        if(data.inquiry_status == 4 && data.duration!==0){
          if(this.data.doctorChatData.rest_time==0){
            //console.log("结束了");
            this.selectComponent('#MessageInput').handlefinishConsult()
          }
          
        }
      })
    },
    handelfllowDoctor() {
      let id = this.data.doctorChatData.doctor_id;
      fllowDoctor(id).then(data => {
        this.setData({
          "doctorChatData.follow": true
        })
        wx.showToast({
          title: '关注成功',
          icon: "none"
        })
      })
    },
    handenotfllowDoctor() {
      let id = this.data.doctorChatData.doctor_id;
      notfllowDoctor(id).then(data => {
        this.setData({
          "doctorChatData.follow": false
        })
        wx.showToast({
          title: '已取消关注',
          icon: "none"
        })
      })
    },
    $handleCloseCards(event) {
      let commentDetail={
        avg_score:event.detail.score,
        is_evaluation:event.detail.score>0?true:false
      };
      this.setData({
        displayServiceEvaluation: false,
        commentDetail:commentDetail
      });
    },
    handleServiceEvaluation(e) {
        let commentDetail=e.detail;
      if( commentDetail && commentDetail.avg_score){
        commentDetail.is_evaluation=true
      }else{
        commentDetail.is_evaluation=false
      }
      this.setData({
        displayServiceEvaluation:true,
        commentDetail:commentDetail,
      });
    },
    init() {
      //this.handleGetRate(this.data.order_inquiry_id);
      wx.$TUIKit.setMessageRead({
        conversationID: this.data.conversationID
      }).then((data) => {
        logger.log('| TUI-chat | setMessageRead | ok');
      });
      wx.$TUIKit.getConversationProfile(this.data.conversationID).then((res) => {
        const {
          conversation
        } = res.data;
        app.globalData.chatNumber = app.globalData.chatNumber - conversation.unreadCount;
        this.setData({
          conversationName: this.getConversationName(conversation),
          conversation,
          isShow: conversation.type === wx.$TUIKitTIM.TYPES.CONV_GROUP,
        });
        if (conversation.type !== wx.$TUIKitTIM.TYPES.CONV_GROUP) return;
        if (!this.data.showTips) {
          this.setData({
            showGroupTips: true,
          });
        } else {
          this.setData({
            showAll: true,
          });
        }
      }).catch((err) => {
        console.log(err)
      });


    },
    getConversationName(conversation) {
      if (conversation.type === '@TIM#SYSTEM') {
        this.setData({
          showChat: false,
        });
        return '系统通知';
      }
      if (conversation.type === wx.$TUIKitTIM.TYPES.CONV_C2C) {
        return conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID;
      }
      if (conversation.type === wx.$TUIKitTIM.TYPES.CONV_GROUP) {
        return conversation.groupProfile.name || conversation.groupProfile.groupID;
      }
    },
    sendMessage(event) {
      // 将自己发送的消息写进消息列表里面
      this.selectComponent('#MessageList').updateMessageList(event.detail.message);
    },
    showMessageErrorImage(event) {
      this.selectComponent('#MessageList').sendMessageError(event);
    },
    triggerClose() {
      try {
        this.selectComponent('#MessageInput').handleClose();
      } catch (error) {

      }
    },
    handleCall(event) {
      if (event.detail.conversationType === wx.$TUIKitTIM.TYPES.CONV_GROUP) {
        this.selectComponent('#TUIGroup').callShowMoreMember(event);
      } else {
        this.triggerEvent('handleCall', event.detail);
      }
    },
    groupCall(event) {
      const {
        selectedUserIDList,
        type,
        groupID
      } = event.detail;
      const userIDList = selectedUserIDList;
      this.triggerEvent('handleCall', {
        userIDList,
        type,
        groupID
      });
    },
    goBack() {
      //this.triggerEvent('showConversationList');
      if (app.globalData.origion == 1) {
        wx.reLaunch({
          url: '/pages/index/index',
        })
      } else if (app.globalData.origion == 2) {
        wx.reLaunch({
          url: '/pages/index/index',
        })
      } else {
        wx.$TUIKit.setMessageRead({
          conversationID: this.data.conversationID,
        }).then(() => {
          if (this.data.fromType) {
            wx.reLaunch({
              url: "/pages/index/index"
            })
          } else {
            wx.navigateBack({
              delta: 1,
              fail:function(){
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
            })
          }

        });
      }

    },
    showConversationList() {
      this.triggerEvent('showConversationList');
    },
    freshChatStatus(event) {
      console.log("freshChatStatus");
      if (event.detail) {
        this.setData({
          order_inquiry_id:event.detail
        })
        this.handleChatMsg(event.detail);

      }
    },
    freshRate(event){
      console.log('comment_id:'+event.detail);
      if (event.detail) {
        this.setData({
          comment_id:event.detail
        });
        //this.handleGetRate(event.detail);

      }
    },
    changeMemberCount(event) {
      this.selectComponent('#TUIGroup').updateMemberCount(event.detail.groupOptionsNumber);
    },
    resendMessage(event) {
      this.selectComponent('#MessageInput').onInputValueChange(event);
    },
    //触发滚动到底部
     scrollBottom(){
       console.log("触发");
      wx.nextTick(() => {
        let compoment=this.selectComponent(".mylist");
        compoment.handleJumpNewMessage();
       });
     },
    // 监听键盘，获取焦点时将输入框推到键盘上方
    pullKeysBoards(event) {
      setNewInputStyle(event.detail.event.detail.height);
      this.setData({
        'viewData.style': newInputStyle,
      });
      this.scrollBottom();
    },

    // 监听键盘，失去焦点时收起键盘
    downKeysBoards(event) {
      this.scrollBottom();
      this.setData({
        'viewData.style': inputStyle,
      });
    },
    typing(event) {
      const {
        STRING_TEXT,
        FEAT_NATIVE_CODE
      } = constant;
      if (this.data.conversation.type === wx.$TUIKitTIM.TYPES.CONV_C2C) {
        if (event.detail.typingMessage.typingStatus === FEAT_NATIVE_CODE.ISTYPING_STATUS && event.detail.typingMessage.actionParam === constant.TYPE_INPUT_STATUS_ING) {
          this.setData({
            conversationName: STRING_TEXT.TYPETYPING,
          });
          setTimeout(() => {
            this.setData({
              conversationName: this.getConversationName(this.data.conversation),
            });
          }, (1000 * 30));
        } else if (event.detail.typingMessage.typingStatus === FEAT_NATIVE_CODE.NOTTYPING_STATUS && event.detail.typingMessage.actionParam === constant.TYPE_INPUT_STATUS_END) {
          this.setData({
            conversationName: this.getConversationName(this.data.conversation),
          });
        }
      }
    },
    handleReport() {
      const url = '/pages/TUI-User-Center/webview/webview?url=https://cloud.tencent.com/apply/p/xc3oaubi98g';
      app.method.navigateTo({
        url,
      });
    },
  },

});