// TUIKit-WChat/Chat/index.js
import logger from '../../utils/logger';
import constant from '../../utils/constant';
import { API } from './../../../utils/network/api'
import { rpxTopx } from './../../../utils/util'
const dayjs = require("../../utils/dayjs.js");
const api = new API()
// eslint-disable-next-line no-undef
const app = getApp();

const inputStyle = `
  --padding: 0px;
`;

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

const setNewInputStyle = (number) => {
  const height = number;
  newInputStyle = `--padding: ${height}px`;
};

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    currentConversationID: {
      type: String,
      value: '',
      observer(currentConversationID) {
        this.setData({
          conversationID: currentConversationID,
        });
      },
    },
    order_inquiry_id: {
      type: String,
      value: ''
    },
    from:{
      type: String,
      value: '',
      observer(from) {
        this.setData({
          from: from,
        });
      },
    },
    inquiry_type: {
      type: String,
      value: ''
    },
    unreadCount: {
      type: Number,
      value: '',
      observer(unreadCount) {
        this.setData({
          unreadCount,
        });
      },
    },
    hasCallKit: {
      type: Boolean,
      value: false,
      observer(hasCallKit) {
        this.setData({
          hasCallKit,
        });
      },
    },
    baseInfo: {
      type: Object,
      value: {},
      observer(baseInfo) {
        this.dealBasic(baseInfo);
        this.setData({
          "navbarData.title": baseInfo.patient_family_name
        });
      },
    }
  },

  lifetimes: {
    attached() {
      if (app?.globalData?.reportType === constant.OPERATING_ENVIRONMENT) {
        this.setData({
          showTips: true,
          message_rounds: 0
        });
      }
      //console.log("000")
      this.getNavbarHeight()

      // let _this = this
      // wx.onKeyboardHeightChange(res => {
      //   let kb_height = res.height
      //   console.log("键盘高度：", kb_height)
      //   _this.setData({
      //     kb_height: kb_height
      //   })
      //   console.log("111")
      //   _this.getNavbarHeight();
      // })
    },
    
    ready() {
      //修改为组件传值
      // this.getInquiryMessageBasic()
      // console.log("app.globalData.scene from TUIchat ready: ", app.globalData.scene);
      let pages = getCurrentPages();
      // console.log("pages:", pages)
      // console.log("pages.length:", pages.length)
      // console.log("pages:", pages[0])
      if(pages.length == 1){
        // console.log("navbarData.showCapsule");
        this.setData({
          "navbarData.showCapsule": 3
        })
      }
      this.setData({
        finsh_btn: false
      })

      wx.onNetworkStatusChange((res) => {
        let msg = ''
        if (!res.isConnected) {
          msg = '当前网络不可用，请检查你的网络设置'
        } else if (res.networkType === 'none') {
          msg = '网络开小差了,请在网络良好后重试'
        }
        if (msg) {
          wx.showToast({
            title: msg,
            icon: 'none',
          })
        }
      })

    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    rest_time:0,
    total_rounds:0,
    timeData:{},
    conversationName: '',
    conversation: {},
    messageList: [],
    isShow: false,
    showImage: false,
    showChat: true,
    conversationID: '',
    config: {
      sdkAppID: '',
      userID: '',
      userSig: '',
      type: 1,
      tim: null,
    },
    unreadCount: 0,
    hasCallKit: false,
    viewData: {
      style: inputStyle,
    },
    input_area_style:"",
    KeyboardHeight: 0,
    showTips: false,
    showGroupTips: false,
    showAll: false,
    navbarData: {
      showCapsule: 2, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
    },
    navbar_height: 120,
    dialog_visible: false,
    finsh_btn: false,
    KeysBoardsStatus: "down",
    message_rounds: 0,
    keysboards_height: 0,
    kb_height: 0,
    change_kb: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    refreshMessageRounds(e){
      // console.log("TUIchat refreshMessageRounds", e)
      let message_rounds = e.detail.message_rounds
      // console.log("TUIchat refreshMessageRounds message_rounds：", message_rounds)
      this.setData({
        message_rounds: message_rounds
      })
      //let total_rounds=this.data.total_rounds;
      // if(total_rounds>=0){
      //   if(total_rounds-message_rounds<=0 && this.data.baseInfo.inquiry_status==4){
      //     wx.showToast({
      //       title: '沟通已达到限制的'+total_rounds+'个回合',
      //       icon:"none"
      //     })
      //     this.finishConsult();
      //   }
      // }
      
    },
    onChangeTime(e) {
      this.setData({
        'timeData': e.detail,
      });
    },
    getNavbarHeight(addHeight){

      try {
        //console.log("getNavbarHeight: ", new Date().getTime())
      let rect = null;
      if (wx.getMenuButtonBoundingClientRect) {
          rect = wx.getMenuButtonBoundingClientRect();
      }
      // console.log("rect: ", rect)
      wx.getSystemInfo({
        success: (res) => {
            // const { statusBarHeight } = wx.getSystemInfoSync();
            // console.log("statusBarHeight: ", statusBarHeight);
            // console.log("${rect.height}px: ", `${rect.height}`);
            let height = Number.parseInt(res.statusBarHeight) + Number.parseInt(`${rect.height}`);

            let KeysBoardsStatus = this.data.KeysBoardsStatus
            if(KeysBoardsStatus == 'pull'){
              height = height + rpxTopx(35)
            }else{
              height = height + rpxTopx(70)
            }
            if(addHeight > 0){
              height = height + addHeight
            }
            let kb_height =  Number.parseInt(this.data.kb_height)
            let textarea_height =  Number.parseInt(this.data.textarea_height)
            //console.log("getNavbarHeight 键盘高度：", kb_height)
            if(kb_height > 0){
              //console.log("height 1: ", height)
              height = height + kb_height
              //console.log("height 2: ", height)
            }
            if(textarea_height > 0){
              //console.log("height 1: ", height)
              height = height + textarea_height
              //console.log("height 2: ", height)
            }

            this.setData({
              navbar_height: height
            })
            //console.log(444)
        },
        fail: (err) => {
            console.error('navbar 获取系统信息失败', err);
        },
      });
      } catch (error) {
        console.error(error)
      }
      

    },
    //结束问诊
    putDoctorInquiryFinish() {
      this.setData({
        dialog_visible: true
      })
      wx.hideKeyboard()
    },
    cancelDialog(){
      this.setData({
        dialog_visible: false
      })
    },
    finishConsult(){
      this.setData({
        finsh_btn: true
      })
      api.putDoctorInquiryFinish({order_inquiry_id: this.data.order_inquiry_id}).then(response => {
        // console.log(response);
        // this.getInquiryMessageBasic();
        //调用子组件中的跳到最新消息
        this.getNavbarHeight()
        this.selectComponent('#MessageList').handleJumpNewMessage();
      }).catch(errors => {
        console.error(errors);
        this.setData({
          message_rounds:this.data.total_rounds,
          finsh_btn: false
        })
      })
    },
    confirmDialog(){
      let finsh_btn = this.data.finsh_btn
      if(finsh_btn){
        return
      }
      this.finishConsult();
      this.setData({
        dialog_visible: false
      })
    },
    dealBasic(obj){
      let data=obj;
      console.log(data.duration)
      if(data.inquiry_status==4){
        if(data.times_number==0){
          this.setData({
            total_rounds:-1,//无线沟通
          })
        }else{
          this.setData({
            total_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({
              "rest_time": countdownTime
            });
            //if(countdownTime==0){
              // wx.showToast({
              //   title: '沟通时长已超过限制时间',
              //   icon:"none"
              // })
             // this.finishConsult();
           // }
          } else {

            this.setData({
              "rest_time": 0
            })
          }
        } else {
          console.log("wwww")
          this.setData({
            "rest_time": -1 //接诊不限时间
          })
        }
      }

    },
    //获取问诊订单消息内页基础数据
    getInquiryMessageBasic() {
      // console.log("order_inquiry_id: ", this.data.order_inquiry_id);
      api.getInquiryMessageBasic({order_inquiry_id: this.data.order_inquiry_id}).then(response => {
        console.log("11111111111111111111111111111111111111")
        // console.log(response);
        this.setData({
          baseInfo: response.data,
        })
        if(response.data.inquiry_status > 4){
          wx.hideKeyboard()
          this.getNavbarHeight()
        }
      }).catch(errors => {console.error(errors);})
    },
    init() {
      console.warn("TUIChat js: init", this.data.conversationID)
      wx.$TUIKit.setMessageRead({ conversationID: this.data.conversationID }).then(() => {
        logger.log('| TUI-chat | setMessageRead | ok');
      });
      wx.$TUIKit.getConversationProfile(this.data.conversationID).then((res) => {
        const { conversation } = res.data;
        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,
          });
        }
      });
    },
    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);
      this.getNavbarHeight();
    },
    refreshMessageStatus(message) {
      //console.log("TUIchat refreshMessageStatus", message)
      this.selectComponent('#MessageList').refreshMessageStatus(message);
    },
    showMessageErrorImage(event) {
      this.selectComponent('#MessageList').sendMessageError(event);
    },
    triggerClose() {
      //console.log("message-list triggerClose")
      if(this.data.baseInfo.inquiry_status == 4){
        this.selectComponent('#MessageInput').handleClose();
      }
      wx.hideKeyboard()
      this.getNavbarHeight()
    },
    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');
      wx.$TUIKit.setMessageRead({
        conversationID: this.data.conversationID,
      }).then(() => {
        wx.navigateBack();
      });
    },
    showConversationList() {
      this.triggerEvent('showConversationList');
    },
    changeMemberCount(event) {
      this.selectComponent('#TUIGroup').updateMemberCount(event.detail.groupOptionsNumber);
    },
    resendMessage(event) {
      this.selectComponent('#MessageInput').onInputValueChange(event);
    },
    myhandleExtensions(e){
      //console.log("myhandleExtensionsmyhandleExtensions: ", e);
      wx.hideKeyboard()
      let displayFlag = e.detail.displayFlag;
      // setTimeout(() => {
        if(displayFlag){
          this.setData({
            input_area_style: "position: absolute;  bottom: 20px;"
          })
          this.getNavbarHeight(100);
          this.selectComponent('#MessageList').handleJumpNewMessage();
        }else{
          this.setData({
            input_area_style: "",
          })
          this.getNavbarHeight();
        }
      // }, 100);
    },
    // 监听键盘，获取焦点时将输入框推到键盘上方
    pullKeysBoards(event) {
      //console.log("pullKeysBoardspullKeysBoards")
      let value = event.detail.event.detail.value;
      let height = event.detail.event.detail.height;
      
      //console.log("pullKeysBoards value: ", height)
      setNewInputStyle(height);
      if(height){
        this.setData({
          kb_height: height
        })
      }
      //console.log("333")
      this.setData({
        'viewData.style': newInputStyle,
        // input_area_style: "position: absolute;  bottom: 52rpx;",
        KeysBoardsStatus: "pull"
      });
      this.getNavbarHeight();
      this.selectComponent('#MessageList').handleJumpNewMessage();
      
    },
    // 监听键盘，失去焦点时收起键盘
    downKeysBoards(event) {
      //console.log("downKeysBoardsdownKeysBoards")
      // //console.log(event)
      let value = event.detail.event.detail.value;
      //console.log("downKeysBoards value: ", value)
      if(value){
        this.setData({
          'viewData.style': inputStyle,
          KeysBoardsStatus: "down",
          kb_height: 0
        });
      }else{
        this.setData({
          'viewData.style': inputStyle,
          input_area_style: "",
          KeysBoardsStatus: "down",
          kb_height: 0
        });
      }
      //console.log("444")
      this.getNavbarHeight();
    },
    inputBindLinechange(event){
      console.log(event)
      let lineCount = event.detail.event.detail.lineCount;
      let height = event.detail.event.detail.height;
      if(height > 100){
        return
      }
      let lineHeight = height / lineCount;
      this.setData({
        textarea_height: lineHeight * (lineCount - 1)
      })
      this.getNavbarHeight();
    },
    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';
      wx.navigateTo({
        url,
      });
    },
  },

});
