// Pages/yishi/index/index.js
import { API } from './../../../utils/network/api'
import { pxTorpx } from './../../../utils/util'
import { requestSubscribeMessage } from './../../../utils/requestSubscribeUtil';

const api = new API()
const app = getApp()
Page({
  data: {
    title: "肝胆相照互联网医院",
    navHeight: 0,
    stateHeight: 0,
    doctor_inquiry_config:null,
    info:{
      user_name: "医师姓名",
      not_accepted_inquiry_num: 0,
      accepting_inquiry_num: 0,
      info_shiming_status_txt: "未认证",
      info_shiming_status: "info_shiming_status_no",
      show_info_note: false,
      praise_rate: "100%",
      avg_response_time: 0,
      number_of_fans: 0,
      avatar: api.getStaticHost()+"/applet/doctor/static/images/default_photo.png",
      reject_prescription_number: false,//处方管理小红点
    },
    static_host: api.getStaticHost(),
    iden_auth_status_txt: "未认证",
    multi_point_status_txt: "未认证",
    shiming_status_url: "",
    iden_auth_status_url: "/Pages/yishi/identity/index",
    multi_point_status_url: "/Pages/yishi/zhiye_identity/index",
    duration: 500,
    interval: 5000,
    swiperList: [],
    banner: [],
    default_dialog_show: false,//只弹框一次
    dialog_visible: false,
    dialog_content: "请您先完成实名认证",
    dialog_url: "",
    /*
      case_module取值
      新问诊 0
      接诊中 1
      多点执业认证 2
      简介管理 3
      在线问诊管理 4
      快速问诊管理 5
      义诊管理 6
      处方管理 7
      联系客服 8
    */
    /*
      case_status 取值
      未实名认证和医师身份认证 0
      已实名认证，未医师身份认证 1
      已实名认证和医师身份认证，未绑定结算银行卡 2
      已实名认证和医生身份认证，已绑定结算银行卡 3
      已实名认证和医师身份认证且绑定结算银行卡，开通了在线问诊，未开通多点执业认证 4
    */
    mycase: [
      {
        case_status: 0,
        case_module: [0,1,2,3,4,5,6,7,8],
        case_text: "请您先完成实名认证",
        case_url: "/Pages/yishi/identity/index"
      },
      {
        case_status: 1,
        case_module: [0,1,2,3,4,5,6,7,8],
        case_text: "请您先医师身份认证",
        case_url: "/Pages/yishi/identity/index?selected_tab=1"
      },
      {
        case_status: 2,
        case_module: [0,1,2,3,4,5,6,7,8],
        case_text: "请您先绑定结算银行卡",
        case_url: "/Pages/yishi/bankcard/index"
      },
      {
        case_status: 3,
        case_module: [7],
        case_text: "请您先进行多点执业认证",
        case_url: "/Pages/yishi/zhiye_identity/index"
      },
      {
        case_status: 4,
        case_module: [7],
        case_text: "请您先进行多点执业认证",
        case_url: "/Pages/yishi/zhiye_identity/index"
      },
      {
        case_status: 5,
        case_module: [],
        case_text: "已全部通过"
      },
    ],
    contactKeFu: false,
    sub_visible: false,
    jiesuan_dialog_show: false,
    jiesuan_dialog_visible: false,
    funbox_height: 100,
    skeleton_loading: true,
    confirmBtn: {
      "openType": "contact",
      "content": "确认",
    },
    overlay_show: false
  },
  //  获取状态栏信息
  getMenuButtonBound() {
    
    let stateHeight = 0; //  接收状态栏高度
    const navHeight = wx.getMenuButtonBoundingClientRect().height; //  获取胶囊高度
    let top = 0;

    top = wx.getMenuButtonBoundingClientRect().top - stateHeight; //  获取top值
    // console.log('navHeight', navHeight);
    // console.log('top', top);
 
    this.setData({
      // navHeight: navHeight + top * 2, //  导航栏高度
      navHeight, //  导航栏高度
      stateHeight: stateHeight + top, //  状态栏高度
    });
  },
  getFunboxHeight(){
    // console.log("109: ", rpxTopx(109))
    // console.log("113: ", rpxTopx(113))
    const { statusBarHeight } = wx.getSystemInfoSync();
    // console.log("statusBarHeight: ", rpxTopx(statusBarHeight));
    let funbox_height = wx.getSystemInfoSync().windowHeight - (this.data.stateHeight + this.data.navHeight + 10) - 55;//减去底部空白
    funbox_height = pxTorpx(funbox_height);
    // 147 userinfo的高度
    // 80  info_note
    // 155 认证部分的高度
    // 168 广告部分的高度
    // 40 自定义适配
    funbox_height = funbox_height - 147 - 20 - 30 - 20 - 155 - 30 - 168 - 20 - 30 - 30 - 30 - 30 - 40;
    // 50  info_note
    if(this.data.info.show_info_note){
      funbox_height = funbox_height - 50;
    }
    funbox_height = funbox_height / 3;
    if(funbox_height > 150) funbox_height = 150
    this.setData({
      funbox_height: funbox_height
    })
  },
  confirmJieSuanDialog(){
    this.setData({
      jiesuan_dialog_visible: false,
    })
    const overlay_show = wx.getStorageSync('overlay_show')
    if(!overlay_show){
      this.setData({
        overlay_show: true
      })
      wx.setStorageSync('overlay_show', "1")
    }

    app.go("/Pages/yishi/manual_detail/index?manual_id=1")
  },
  cancelJieSuanDialog(){
    this.setData({
      jiesuan_dialog_visible: false,
    })
    const overlay_show = wx.getStorageSync('overlay_show')
    if(!overlay_show){
      this.setData({
        overlay_show: true
      })
      wx.setStorageSync('overlay_show', "1")
    }
  },
  confirmContactDialog(){
    this.setData({
      contactKeFu: false
    })
  },
  cancelContactDialog(){
    // console.log("cancelContactDialogcancelContactDialogcancelContactDialog");
    this.setData({
      contactKeFu: false
    })
  },
  onPullDownRefresh(){
    // console.log("用户下拉动作")
    this.onShow();
  },
  onLoad(){
    
  },
  onUnload(){
    // console.log("index onUnload() onUnload() ");
    this.setData({
      swiperList: []
    })
  },
  onHide(){
    // console.log("index onHide() onHide() ");

    // wx.offCopyUrl(this.Copylistener) // 需传入与监听时同一个的函数对象

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().stopInterval()
    }

    this.setData({
      contactKeFu: false
    })
  },
  Copylistener(res){
    setTimeout(()=>{
      wx.setClipboardData({
        data: '暂不支持分享',
        success (res) {

        },
        complete(){
          wx.hideToast()
        }
      })
    },1000)
    return
  },
  onShow: function () {

    //初始化默认值
    this.setData({
      skeleton_loading: true,
    });

    // wx.onCopyUrl(this.Copylistener);
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 0,  //数字是当前页面在tabbar的索引,如我的查询页索引是2，因此这边为2，同理首页就为0，审批页面为1
      })
      this.getTabBar().startInterval()
    }
    this.getMenuButtonBound();
    
    api.yiShiIndex().then(response => {
      // console.log(response);
      let avatar = response.data.info.avatar;
      this.setData({
        "info.user_name": response.data.info.user_name,
        "info.not_accepted_inquiry_num": response.data.info.not_accepted_inquiry_num,
        "info.accepting_inquiry_num": response.data.info.accepting_inquiry_num,
        "info.praise_rate": response.data.info.praise_rate,
        "info.avg_response_time": response.data.info.avg_response_time,
        "info.number_of_fans": response.data.info.number_of_fans,
        doctor_inquiry_config:response.data.doctor_inquiry_config
      })
      if(avatar){
        this.setData({
          "info.avatar": avatar
        })
      }

      //实名认证
      let idcard_status = response.data.info.idcard_status;
      //医师身份认证
      let iden_auth_status = response.data.info.iden_auth_status;
      //多点执业认证
      let multi_point_status = response.data.info.multi_point_status;
      //绑定结算银行卡
      let is_bind_bank = response.data.info.is_bind_bank;
      // //是否参加专家图文接诊（0:否 1:是）
      // let is_img_expert_reception = response.data.info.is_img_expert_reception;
      // //是否参加专家快速接诊（0:否 1:是）
      // let is_img_quick_reception = response.data.info.is_img_quick_reception;
      // //是否参加专家公益接诊（0:否 1:是）
      // let is_img_welfare_reception = response.data.info.is_img_welfare_reception;

      this.setData({
        "info.idcard_status": idcard_status,
        "info.iden_auth_status": iden_auth_status,
        "info.multi_point_status": multi_point_status,
        "info.is_bind_bank": is_bind_bank,
        // "info.is_img_expert_reception": is_img_expert_reception,
        // "info.is_img_quick_reception": is_img_quick_reception,
        // "info.is_img_welfare_reception": is_img_welfare_reception,
      });

      //iden_auth_status 0:未认证 1:认证通过 2:审核中 3:认证失败
      if(iden_auth_status == 0) this.setData({iden_auth_status_txt: "未认证"});
      if(iden_auth_status == 1) this.setData({iden_auth_status_txt: "已认证", iden_auth_status_url: "/Pages/yishi/attestation/index"});
      if(iden_auth_status == 2) this.setData({iden_auth_status_txt: "审核中"});
      if(iden_auth_status == 3) this.setData({iden_auth_status_txt: "认证失败"});

      //multi_point_status 0:未认证 1:认证通过 2:审核中 3:认证失败
      if(multi_point_status == 0) this.setData({multi_point_status_txt: "未认证"});
      if(multi_point_status == 1) this.setData({multi_point_status_txt: "已认证", multi_point_status_url: "/Pages/yishi/practicing/index"});
      if(multi_point_status == 2) this.setData({multi_point_status_txt: "审核中"});
      if(multi_point_status == 3) this.setData({multi_point_status_txt: "认证失败"});

      //平均响应时间 
      var avg_response_time = response.data.info.avg_response_time;
      if(avg_response_time != "0"){
        this.setData({"info.show_info_note": true});
      }
      //处方管理小红点
      var reject_prescription_number = response.data.info.reject_prescription_number;
      if(reject_prescription_number){
        this.setData({"info.reject_prescription_number": reject_prescription_number});
      }
      //格式化广告轮播
      this.formatAD(response.data.banner);
      this.checkStatus();
      
      this.setData({
        skeleton_loading: false
      })
    }).then(res => {
      wx.stopPullDownRefresh()
    }).then(res =>{
      this.getFunboxHeight();
    }).catch(errors => {
      console.error(errors);
    })
  },
  formatAD(banner){
    let swiperList = [];
    banner.forEach(item => {
      swiperList.push(item.banner_path);
    })
    this.setData({
      banner: banner,
      swiperList: swiperList
    })
  },
  onTapAD(e) {
    let item = e.currentTarget.dataset.item;
    // console.log(item);
    let open_with = item.open_with;
    let banner_link = item.banner_link;
    if(open_with == 1){//小程序页面
      app.go(banner_link);
    }else if(open_with == 2){//webview 页面
      app.go("/Pages/webpage/index?src="+banner_link);
    }
  },
  onChangeAD(e) {
    // const { current, source } = e.detail;
    // console.log(current, source);
  },
  go(e){
    let checkDialog = this.checkDialog(e);
    // console.log("checkDialog: ", checkDialog);
    if(checkDialog){
      let url = e.currentTarget.dataset.url;
      // console.log(url);
      if(url.indexOf("wenzhen") > -1){
        wx.switchTab({
          url: url,
        })
      }
      app.go(e.currentTarget.dataset.url)
    }
  },
  gozhiye(e){
    let idcard_status = this.data.info.idcard_status;
    let iden_auth_status = this.data.info.iden_auth_status;
    let is_bind_bank = this.data.info.is_bind_bank;
    if(idcard_status != 1){
      this.setData({
        dialog_content: "请您先完成实名认证",
        shiming_status_url: "/Pages/yishi/identity/index",
        dialog_visible: true,
      });
      return;
    }
    if(iden_auth_status != 1){
      this.setData({
        dialog_content: "请您先医师身份认证",
        shiming_status_url: "/Pages/yishi/identity/index?selected_tab=1",
        dialog_visible: true,
      });
      return;
    }
    if(is_bind_bank != 1){
      this.setData({
        dialog_content: "请您先绑定结算银行卡",
        shiming_status_url: "/Pages/yishi/bankcard/index",
        dialog_visible: true,
      });
      return;
    }
    app.go(e.currentTarget.dataset.url);
  },
  confirmDialog(e){
    // console.log(e)
    let url = e.currentTarget.dataset.url;
    // console.log("confirmDialog: ", url)
    this.setData({
      dialog_visible: false
    })
    app.go(url);
  },
  cancelDialog(){
    this.setData({
      dialog_visible: false
    })
  },
  checkStatus(){
     //实名认证
     let idcard_status = this.data.info.idcard_status;
     //医师身份认证
     let iden_auth_status = this.data.info.iden_auth_status;
     //多点执业认证
     let multi_point_status = this.data.info.multi_point_status;
      //绑定结算银行卡
     var is_bind_bank = this.data.info.is_bind_bank;
        //是否参加专家图文接诊（0:否 1:是）

    // let is_img_expert_reception = this.data.info.is_img_expert_reception;
    // //是否参加专家快速接诊（0:否 1:是）
    // let is_img_quick_reception = this.data.info.is_img_quick_reception;
    // //是否参加专家公益接诊（0:否 1:是）
    // let is_img_welfare_reception = this.data.info.is_img_welfare_reception;

     let usertype =  wx.getStorageSync('usertype');
     let userID = wx.getStorageSync('user_id_'+usertype);
     wx.setStorageSync(userID+'_idcard_status', idcard_status);
     wx.setStorageSync(userID+'_iden_auth_status', iden_auth_status);
     wx.setStorageSync(userID+'_multi_point_status', multi_point_status);
     wx.setStorageSync(userID+'_is_bind_bank', is_bind_bank);

    if(idcard_status == 0){
      if(!this.data.default_dialog_show){
        this.setData({
          dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "未认证",
        "info.info_shiming_status": "info_shiming_status_no",
        dialog_content: "请您先完成实名认证",
        shiming_status_url: "/Pages/yishi/identity/index",
        dialog_url: "/Pages/yishi/identity/index",
        default_dialog_show: true
      });
      return false;
    }

    if(idcard_status == 2){
      if(!this.data.default_dialog_show){
        this.setData({
          dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "认证失败",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/identity/index",
        dialog_url: "/Pages/yishi/identity/index",
        dialog_content: "实名认证失败",
        default_dialog_show: true
      });
      return false;;
    }
    
    if(iden_auth_status == 0){
      if(!this.data.default_dialog_show){
        this.setData({
          dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "前往医师身份认证",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/identity/index?selected_tab=1",
        dialog_url: "/Pages/yishi/identity/index?selected_tab=1",
        dialog_content: "请您先医师身份认证",
        default_dialog_show: true
      });
      return false;
    }
    if(iden_auth_status == 2){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "审核中",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/identity/index?selected_tab=1",
        dialog_url: "/Pages/yishi/identity/index?selected_tab=1",
        // dialog_content: "您的医师身份认证正在审核中",
        // default_dialog_show: true
      });
      return false;
    }
    if(iden_auth_status == 3){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "认证失败",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/identity/index?selected_tab=1",
        dialog_url: "/Pages/yishi/identity/index?selected_tab=1",
        dialog_content: "您的医师身份认证失败",
        // default_dialog_show: true
      });
      return false;
    }

   
    if(is_bind_bank == 0){
      if(!this.data.default_dialog_show){
        this.setData({
          dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "绑定结算银行卡",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/bankcard/index",
        dialog_url: "/Pages/yishi/bankcard/index",
        dialog_content: "请您先绑定结算银行卡",
        default_dialog_show: true
      });
      return false;
    }
    
    //多点执业认证
    if(multi_point_status == 0){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "前往多点执业认证",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/zhiye_identity/index",
        dialog_content: "请您先进行多点执业认证",
        // default_dialog_show: true
      });
      // return false;
    }
    
    if(multi_point_status == 2){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
        });
      }
      this.setData({
        "info.info_shiming_status_txt": "审核中",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/zhiye_identity/index",
        dialog_content: "您的多点执业认证正在审核中",
        // default_dialog_show: true
      });
      // return false;
    }
    
    if(multi_point_status == 3){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
      });
      }
      this.setData({
        "info.info_shiming_status_txt": "认证失败",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/zhiye_identity/index",
        dialog_content: "您的多点执业认证失败",
        // default_dialog_show: true
      });
      // return false;
    }

    const jiesuan_dialog_show = wx.getStorageSync('jiesuan_dialog_show');
    if(!jiesuan_dialog_show){
      this.setData({
        jiesuan_dialog_visible: true,
      });
      wx.setStorageSync('jiesuan_dialog_show', true);
    }
    // (is_img_expert_reception + is_img_quick_reception + is_img_welfare_reception) == 0
    let flag=false;
    if(this.data.doctor_inquiry_config){
      flag=this.data.doctor_inquiry_config.every((item)=>{
        return item.is_enable==0
      })
    };
    if(!this.data.doctor_inquiry_config || flag){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
      });
      }
      this.setData({
        "info.info_shiming_status_txt": "开启在线问诊",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/onlinesetup/index",
        // default_dialog_show: true
      });
      return false;
    }
    //(is_img_expert_reception + is_img_quick_reception + is_img_welfare_reception) > 0
    if(this.data.doctor_inquiry_config && !flag){
      if(!this.data.default_dialog_show){
        this.setData({
          // dialog_visible: true,
      });
      }
      this.setData({
        "info.info_shiming_status_txt": "去接诊",
        "info.info_shiming_status": "info_shiming_status_yes",
        shiming_status_url: "/Pages/yishi/wenzhen_v2/wenzhen",
        // default_dialog_show: true
      });
      return false;
    }

    
    
    //开启在线问诊
    // var is_img_expert_reception = this.data.info.is_img_expert_reception;
    // if(is_img_expert_reception == 0 ){
    //   if(!this.data.default_dialog_show){
    //       this.setData({
    //         // dialog_visible: true,
    //     });
    //   }
    //   this.setData({
    //     "info.info_shiming_status_txt": "开启在线问诊",
    //     "info.info_shiming_status": "info_shiming_status_yes",
    //     shiming_status_url: "/Pages/yishi/onlinesetup/index",
    //     dialog_content: "请您先前往在线问诊管理中，开通在线问诊",
    //     default_dialog_show: true
    //   })
    //   return false;
    // }

   

    this.setData({
      "info.info_shiming_status_txt": "去接诊",
      shiming_status_url: "/Pages/yishi/wenzhen_v2/wenzhen",
    });
    this.setData({"info.info_shiming_status": "info_shiming_status_yes"});
    return true;
  },
  contactKeFu(e){
    let _this = this;

    let checkDialog = this.checkDialog(e);
    if(checkDialog){
      
      let tmplIds = ['JMPmlYGh1HcUSuEfJCVQUIsZv4H5ar3QvXZfrNYNFuc']
      let sub_promise = requestSubscribeMessage(tmplIds)
      sub_promise.then(res => {
        console.log("订阅成功")
        this.setData({
          contactKeFu: true
        })
      }).catch(err => {
        console.log(err)
        let errCode = err.errCode
        if(errCode == 20004){
          this.setData({
            sub_visible: true,
          })
        }
      })
    }
  },
  subcancelDialog(){
    this.setData({
      sub_visible: false,
      contactKeFu: true
    })
  },
  subconfirmDialog(){
    this.setData({
      sub_visible: false
    })
    wx.openSetting({
      success (res) {
        console.log(res.authSetting)
      }
    })
  },
  checkDialog(e){
    //实名认证
    let idcard_status = this.data.info.idcard_status;
    //医师身份认证
    let iden_auth_status = this.data.info.iden_auth_status;
    //多点执业认证
    let multi_point_status = this.data.info.multi_point_status;
    //绑定结算银行卡
    let is_bind_bank = this.data.info.is_bind_bank;
    //是否参加专家图文接诊（0:否 1:是）
    let is_img_expert_reception = this.data.info.is_img_expert_reception;
    //是否参加专家快速接诊（0:否 1:是）
    let is_img_quick_reception = this.data.info.is_img_quick_reception;
    //是否参加专家公益接诊（0:否 1:是）
    let is_img_welfare_reception = this.data.info.is_img_welfare_reception;
    let statusArr = [];
    
    // 未实名认证和医师身份认证 0
    // 已实名认证，未医师身份认证 1
    // 已实名认证和医师身份认证，未绑定结算银行卡 2
    // 已实名认证和医生身份认证，已绑定结算银行卡 未开通多点执业认证3
    // 已实名认证和医师身份认证且绑定结算银行卡，开通了在线问诊，未开通多点执业认证 4
    // 已实名认证和医师身份认证且绑定结算银行卡，开通了在线问诊，已开通多点执业认证 5
    if(idcard_status == 0 && iden_auth_status == 0){
      statusArr.push(0);
    }
    if(idcard_status == 1 && iden_auth_status != 1){
      statusArr.push(1);
    }
    if(idcard_status == 1 && iden_auth_status == 1 && is_bind_bank != 1){
      statusArr.push(2);
    }
    if(idcard_status == 1 && iden_auth_status == 1 && is_bind_bank == 1 && multi_point_status != 1 && 
      (is_img_expert_reception + is_img_quick_reception + is_img_welfare_reception) == 0){
      statusArr.push(3);
    }
    if(idcard_status == 1 && iden_auth_status == 1 && is_bind_bank == 1 && multi_point_status != 1 &&
      (is_img_expert_reception + is_img_quick_reception + is_img_welfare_reception) > 0){
      statusArr.push(4);
    }
    if(idcard_status == 1 && iden_auth_status == 1 && is_bind_bank  == 1 && multi_point_status == 1){
      statusArr.push(5);
    }

    let retult = true;
    statusArr.forEach(status => {
      let now_case = this.data.mycase.find(item => {
        return item.case_status == status;
      });
      // console.log("now_case: ", now_case);
      //所属模块
      let moudle = e.currentTarget.dataset.moudle;
      // console.log("moudle: ", moudle);
      if(now_case){
        let now_moudle = now_case.case_module.find(item => {
          return item == moudle;
        })
        // console.log("now_moudle: ", now_moudle);
        if(now_moudle != undefined){
          this.setData({
            dialog_content: now_case.case_text,
            dialog_visible: true,
            dialog_url: now_case.case_url
          });
          retult = false;
          return;
        }
      }
    })

    return retult;
  },
  onClickHideOverlay(){
    this.setData({
      overlay_show: false
    })
  }
})