import formateTime from '../../../../../utils/formate-time';
import constant from '../../../../../utils/constant';
import {
  getCurrentPageUrl,
  getCurrentPageParam
} from "../../../../../../../utils/getUrl"
import {
  getRate
} from "../../../../../../../api/consultOrder"
const app = getApp()
// eslint-disable-next-line no-undef
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    message: {
      type: Object,
      value: {},
      observer(newVal) {
        this.setData({
          message: newVal,
          renderDom: this.parseCustom(newVal),
        });
      },
    },
    patient_data:{
      type: Object,
      value: {},
      observer(newVal) {
        this.setData({
          patient_data: newVal,
        });
      }
    },
    isMine: {
      type: Boolean,
      value: true,
    },
  },
  pageLifetimes:{
    show: function() {
      this.setData({
        img_host:app.hostConfig().imghost
      });
     
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    displayServiceEvaluation: false,
    score: 0,
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    commentDetail: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //  async getDom(id,renderDom){
    //   let result = await this.handleGetRate(id,renderDom);
    //   return result
    //  },
    handleGetRate(id) {
      getRate(id).then(data => {
        let commentDetail = null;
        if (data) {
          commentDetail = data
        } else {
          commentDetail = {
            avg_score: 0,
            content: "",
            evaluation_id: "",
            is_evaluation: false,
            order_inquiry_id:id,
            reply_progress: 0,
            reply_quality: 0,
            service_attitude: 0

          }
        }
        this.triggerEvent("popComment",commentDetail);
      })
    },
    async handleAllRate(id, renderDom) {
      let result = null;
      await getRate(id).then(data => {
        if (data) {
          renderDom[0].is_evaluation = true;
          renderDom[0].score = data.avg_score;
        }
      })

      this.setData({
        renderDom: renderDom
      })
    },
    showPop(event) {
      let id = event.currentTarget.dataset.id;
      console.log(id);
      this.handleGetRate(id);
    },

    // 解析音视频通话消息
    extractCallingInfoFromMessage(message) {
      const callingmessage = JSON.parse(message.payload.data);
      if (callingmessage.businessID !== 1) {
        return '';
      }
      const objectData = JSON.parse(callingmessage.data);
      switch (callingmessage.actionType) {
        case 1: {
          if (objectData.call_end >= 0) {
            return `通话时长：${formateTime(objectData.call_end)}`;
          }
          if (objectData.data && objectData.data.cmd === 'switchToAudio') {
            return '切换语音通话';
          }
          if (objectData.data && objectData.data.cmd === 'switchToVideo') {
            return '切换视频通话';
          }
          return '发起通话';
        }
        case 2:
          return '取消通话';
        case 3:
          if (objectData.data && objectData.data.cmd === 'switchToAudio') {
            return '切换语音通话';
          }
          if (objectData.data && objectData.data.cmd === 'switchToVideo') {
            return '切换视频通话';
          }
          return '已接听';
        case 4:
          return '拒绝通话';
        case 5:
          if (objectData.data && objectData.data.cmd === 'switchToAudio') {
            return '切换语音通话';
          }
          if (objectData.data && objectData.data.cmd === 'switchToVideo') {
            return '切换视频通话';
          }
          return '无应答';
        default:
          return '';
      }
    },
    parseCustom(message) {
      const {
        BUSINESS_ID_TEXT
      } = constant;
      // 群消息解析
      if (message.payload.data === BUSINESS_ID_TEXT.CREATE_GROUP) {
        const renderDom = [{
          type: 'group_create',
          text: message.payload.extension,
        }];
        return renderDom;
      }
      try {
        const customMessage = JSON.parse(message.payload.data);
        let avastar = '';
        if (message.flow == "in") {
          avastar = message.avatar;
        }
        // 约定自定义消息的 data 字段作为区分，不解析的不进行展示
        if (customMessage.businessID === BUSINESS_ID_TEXT.ORDER) {
          const renderDom = [{
            type: 'order',
            name: 'custom',
            title: customMessage.title || '',
            imageUrl: customMessage.imageUrl || '',
            price: customMessage.price || 0,
            description: customMessage.description,
          }];
          return renderDom;
        }
        // 服务评价
        if (customMessage.businessID === BUSINESS_ID_TEXT.EVALUATION) {
          const renderDom = [{
            type: 'evaluation',
            title: message.payload.description,
            score: customMessage.score,
            description: customMessage.comment,
          }];
          return renderDom;
        }
        // native 自定义消息解析
        if (customMessage.businessID === BUSINESS_ID_TEXT.LINK) {
          const renderDom = [{
            type: 'text_link',
            text: customMessage.text,
          }];
          return renderDom;
        }
        // 自定义消息类型（1:消息内页横条 2:订单结束评价弹出 3:医生端系统通知  4:医生端服务通知 5:患者端系统消息 6:处方开具成功（医生端） 7:处方审核通过（患者端））",
        if (customMessage.message_type == 1) {
          const renderDom = [{
            type: 'msg_tip',
            text: customMessage.title,
            desc: customMessage.desc
          }];
          return renderDom;
        }

        if (customMessage.message_type == 2) {
          let renderDom = [{
            type: 'msg_comment',
            text: customMessage.title,
            order_inquiry_id: customMessage.data.order_inquiry_id,
            is_evaluation: false,
            score: 0,
            desc: customMessage.desc,
            avatar: avastar
          }];

          this.handleAllRate(customMessage.data.order_inquiry_id, renderDom);

          return renderDom;
        };
        if (customMessage.message_type == 7) {
          let data = customMessage.data;
          const renderDom = [{
            type: 'msg_prescribe',
            product_name: data.product_name,
            order_inquiry_id: data.order_inquiry_id,
            order_prescription_id: data.order_prescription_id,
            pharmacist_verify_time: data.pharmacist_verify_time.substring(0, 10),
          }];
          return renderDom;
        };
        if (customMessage.message_type == 10) {
          let data = customMessage.data;
          const renderDom = [{
            type: 'msg_checksugar',
            title:customMessage.title,
            order_no:data.order_no,
            message_path:data.message_path,
            disease_class_names: data.disease_class_names
          }];
          return renderDom;
        }
        if (customMessage.message_type == 12) {
          let data = customMessage.data;
          const renderDom = [{
            type: 'wenzhen_form',
            order_inquiry_id:data.order_inquiry_id,
            message_path:data.message_path,
            //case_patient_message_path:data.case_patient_message_path,
            case_filled_fields:data.case_filled_fields,
            case_not_fill_fields:data.case_not_fill_fields
          }];
          return renderDom;
        }
        if (customMessage.message_type === 16){
          
            let data = customMessage.data;
            const renderDom = [{
              type: 'video_time_16',
              title: customMessage.title,
               desc: customMessage.desc,
             
            }];
            return renderDom;
        }
         //13 赠送对话customMessage.message_type ===14 || 
         if (customMessage.message_type ===13){
            let data = customMessage.data;
            const renderDom = [{
              type: 'send_talk',
              title: customMessage.title,
               desc: customMessage.desc,
             
            }];
            return renderDom;
        }
         //17 预约时间
         if (customMessage.message_type === 17){
          
            let data = customMessage.data;
            const renderDom = [{
              type: 'video_time',
              title: customMessage.title,
               desc: customMessage.desc.replace(/text/g,'span'),
             
            }];
            return renderDom;
        }

      } catch (error) {}
      // 客服咨询
      try {
        const extension = JSON.parse(message.payload.extension);
        if (message.payload.data === BUSINESS_ID_TEXT.CONSULTION) {
          const renderDom = [{
            type: 'consultion',
            title: extension.title || '',
            item: extension.item || 0,
            description: extension.description,
          }];
          return renderDom;
        }
        
      } catch (error) {}
      // 音视频通话消息解析
      try {
        const callingmessage = JSON.parse(message.payload.data);
        if (callingmessage.businessID === 1) {
          if (message.conversationType === wx.$TUIKitTIM.TYPES.CONV_GROUP) {
            if (message.payload.data.actionType === 5) {
              message.nick = message.payload.data.inviteeList ? message.payload.data.inviteeList.join(',') : message.from;
            }
            const _text = this.extractCallingInfoFromMessage(message);
            const groupText = `${_text}`;
            const renderDom = [{
              type: 'groupCalling',
              text: groupText,
              userIDList: [],
            }];
            return renderDom;
          }
          if (message.conversationType === wx.$TUIKitTIM.TYPES.CONV_C2C) {
            const c2cText = this.extractCallingInfoFromMessage(message);
            const renderDom = [{
              type: 'c2cCalling',
              text: c2cText,
            }];
            return renderDom;
          }
        }
        return [{
          type: 'notSupport',
          text: '[自定义消息]',
        }];
      } catch (error) {}
    },
    openLink(e) {
      if (e.currentTarget.dataset.value.key === '立即前往') {
        app.method.navigateTo({
          url: '/pages/TUI-User-Center/webview/webview?url=https://cloud.tencent.com/act/pro/imnew?from=16975&wechatMobile',
        });
      } else if (e.currentTarget.dataset.value.key === '立即体验') {
        app.method.navigateTo({
          url: '/pages/TUI-User-Center/webview/webview?url=https://cloud.tencent.com/document/product/269/68091',
        });
      }
    },
    goReport(event){
      let {url,id} = event.currentTarget.dataset;
      app.method.navigateTo({
        url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id='+id
      })
    },
    goPrescriptDetail(event) {
      let url = event.currentTarget.dataset.url;
      let redirectUrl = getCurrentPageUrl();
      let options = getCurrentPageParam();
      let params = ""
      for (const key in options) {
        if (params) {
          params = params + '&' + key + '=' + options[key];
        } else {
          params = params + key + '=' + options[key];
        }
      };
    //   console.log(url + "&fromType=" +  encodeURIComponent(redirectUrl + "?" + params))
      app.method.navigateTo({
        url: url + "&fromType=" + encodeURIComponent(redirectUrl + "?" + params)
      })
    },
    goList(event){
      console.log(event);
      const {ismine,params,id}=event.currentTarget.dataset;
      console.log(params);
      if(!ismine){//未填写
        app.method.navigateTo({
          url:'/patient/pages/inquiryForm/inquiryForm?params='+params+"&order_inquiry_id="+id
        })
      }else{//已填写
        app.method.navigateTo({
          url:'/patient/pages/inquiryForm/inquiryForm?case_filled_fields='+params+"&order_inquiry_id="+id
        })
      }
     // app.go(url);
    }
  },
});