/*
 * @Descripttion: 签署管理页面
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: ZZB
 * @lastAuthor: chenminggui
 * @Date: 2022-02-28 15:45:51
 * @LastEditors: zhangzhuobin 1093998108@qq.com
 * @LastEditTime: 2022-06-29 10:32:19
 */
const { bus } = getApp();
// 引用dayjs,用于下方转换日期
const dayjs = require('../../src/js/dayjs/index')
import {
  fhPatientSignDetail,
  fhClientSignPay,
  fhPatientVerty,
  fhIsVerityPatientVerty,
  fhHospitalSet
} from '../../api/sign/index'
import {
  statusObj
} from '../sign/utils'
// import TIM from '../utils/tim-wx'
import {
  parseTime,
  minutesCha
} from '../../utils/parseTime'
import {
  fhGetRemoteVisitsDetail,
} from '../../api/remote/index'
let TIM
Page({
      data: {
        statusObj: statusObj,
        detailObj: {},
        isFirstOnShow: true, // 是否为首次执行onShow
        detail: null,
        tapTime: '', //防抖动参数
        payStatus: false,
        authedFlag:false,
        // 远程探视状态
        visitState: '',
        // 是否展示签署按钮状态
        isShowSign: true,
        // 是否展示<今天>这两个文字的状态
        isShowToday: false,
        // 是否允许进入远程探视房间
        isNotCanEnterRoom: true,
      },
      onLoad(e) {
        require('../../remote/utils/tim-wx', utils => {
          console.log(TIM, 'TIM');
          console.log(utils,'utils') // Wechat MiniProgram
           TIM = utils
          console.log(TIM, 'TIM');
        })
        this.setData({
          sigId: e.id,
          remoteVisitRecordId: e.remoteVisitRecordId
        })
        bus.on("refeshLogin", this.handlerLogin.bind(this));
      },
      onShow() {
          this.featureGetDetail()
          this.getRemoteVisitsDetail()
          if(wx.getStorageSync('memberId')){
            this.handleAuthedIdent();
          }
        },
        handlerLogin({flag}){
          if(flag === true){
            // 获取用户是否登录状态
        const ifAuth = wx.getStorageSync('anflag')
        console.log(ifAuth, 'ifAuth')
        // 若用户未登录,通过短链进入网签详情时则跳转登录页面进行登录操作
        if (ifAuth) {
          wx.$routerTo('/pages/authorization/authorization')
          return
        }
          }
        },
      /**
       * 获取远程探视详情
       */
       async getRemoteVisitsDetail() {
        try {
          const remoteVisitRecordId = this.data.remoteVisitRecordId
          const { results } = await fhGetRemoteVisitsDetail(remoteVisitRecordId)
          console.log("我是远程探视详情",results.visitState)
          this.setData({
            visitState: results.visitState
          })
        } catch (e) {
          console.log(e)
        } finally {
          this.getHospitalSet()
        }
      },
      /***
       * 获取当前医院的网签设置
       */
       async getHospitalSet() {
        try {
          const { hospitalId } = wx.getStorageSync('hospital-info')
          const { results } = await fhHospitalSet(hospitalId)
          // if (['TO_BE_START', 'DOING'].includes(this.data.visitState)) {
            const toBeStartTimes =
              dayjs(this.data.detailObj.businessLicense).valueOf() - dayjs().valueOf()
            console.log('toBeStartTimes', toBeStartTimes)
            console.log('可提前进入时长', results.advanceTime)
            console.log('获取探视状态', this.data.visitState)
            this.setData({
              isNotCanEnterRoom: !(toBeStartTimes < results.advanceTime * 60 * 1000)
            })
            console.log('isNotCanEnterRoom', this.data.isNotCanEnterRoom)
          // }
        } catch (e) {
          console.log(e)
        }
      },
      /***
       * 患者是否认证过
       */
      async handleAuthedIdent() {
        wx.showLoading({title:"正在加载中",mask:true})
          try {
            const params = {
              patientId: getApp().globalData.baseInfo.memberId
            }
            const {
              results
            } = await fhIsVerityPatientVerty(params);
            wx.setStorageSync('authedFlag',results.flag)
            console.log(results, '认证返回的信息')
            this.setData({
              authedFlag:results.flag
            })
            // if (!results) {
            //   wx.showModal({
            //     title: "提示",
            //     content: '您当前未实名验证,是否确认前往实名验证',
            //     success: (res) => {
            //       if (res.confirm) {
            //         this.handleToFaDaDaMini();
            //       }
            //     }
            //   })
            // }
          } catch (e) {
            console.log(e)
          } finally {
            wx.hideLoading()
          }
      },

      /**
       * 获取跳转实名认证的路径
       */
      async getVertyPatient() {
        const params = {
          accounType: 1,
          patientId: getApp().globalData.baseInfo.memberId,
          url: `pages/sign-detail/index?id=${this.data.sigId}`
        }
        const {
          results
        } = await fhPatientVerty(params);
        return Promise.resolve(results)
      },

      /**
       * 跳转法大大小程序逻辑
       */
      handleToFaDaDaMini() {
        console.log('准备获取地址')
        wx.showLoading({
          title: "加载中",
          mask: true
        })
        this.getVertyPatient().then(res => {
          console.log('获取地址成功', res)

          // 法大大小程序AppId :
          // 测试环境：wx855361a721050c6b
          // 正式环境：wxa1439f77c6d06a15
          // 获取小程序账号信息
          const accountInfo = wx.getAccountInfoSync().miniProgram
          console.log('当前小程序版本环境', accountInfo.envVersion)
          // 根据小程序环境信息适配跳转法大大的APPid
          const appId = accountInfo.envVersion === 'release' ? 'wxa1439f77c6d06a15' : 'wx855361a721050c6b'
          wx.navigateToMiniProgram({
            appId: appId,
            path: 'pages/result-loading/result-loading?verifyUrl=' + encodeURIComponent(res),
            envVersion: 'release'
          })
          wx.hideLoading();
        })
      },

      /**
       * 测试网签文件编辑
       */
       tapEnter() {
        console.log("点击进入文件编辑")
        const fileUrl = "http://test.api.fabigbig.com:8888/api/fill_page.api?app_id=406000&v=2.0&timestamp=20220322153236&contract_template_id=tianxieduogedocx&contract_id=tianxieduogedocx123123123&doc_title=%E9%A2%84%E8%A7%88%E5%A1%AB%E5%85%85%E9%A1%B5%E9%9D%A2&return_url=%E5%90%8C%E6%AD%A5%E8%B0%83%E5%87%86%E9%80%9A%E7%9F%A5%E5%9C%B0%E5%9D%80&msg_digest=M0FGQjQyMDFCMEM2M0JBMjI1NjRCQkRCQTYyOEExQkIzMUI5NTIyQg=="
        wx.navigateTo({
          url:`/pages/sign-file/index?url=${encodeURIComponent(fileUrl)}`
        })
       },

      /**
       * 立即支付流程
       */
      async handlePayWechat() {
        if(wx.getStorageSync('anflag')){
          wx.$routerTo('/pages/authorization/authorization')
          return
        }
        this.handleLoading()
        try {
          const params = {
            memberId: getApp().globalData.baseInfo.memberId
          }
          const bodyParams = {
            needSmsCode: '',
            payType: 1
          }
          const res = await fhClientSignPay(this.data.sigId, params, bodyParams)
          const results = res.results
          if (res.success) {
            wx.requestPayment({
              timeStamp: results.timeStamp,
              nonceStr: results.nonceStr,
              signType: results.signType,
              paySign: results.paySign,
              package: results.prepayId,
              success: (res) => {
                this.handleLoading();
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                })
                this.featureGetDetail();
              },
              fail: (error) => {
                wx.hideLoading()
                console.log(error)
              }
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: 'none',
            })
          }
        } catch (e) {
          console.log('error', e)
        }
      },

      /**获取网签管理详情 */
      async featureGetDetail() {
        try {
          this.handleLoading()
          const params = {
            documentId: this.data.sigId
          }
          const {
            results
          } = await fhPatientSignDetail(params)
          results.exactaddress = wx.getStorageSync('exactaddress'),

            console.log("打印网签管理详情",results)
            this.setData({
              detailObj: results
            })
          
            //  引用dayjs,用于下方转换日期
            const dayjs = require('../../src/js/dayjs/index')
            //  若今天日期等于签署截止日期,改变isShowToday的状态
            if (dayjs(new Date()).format('YYYY-MM-DD') === dayjs(results.deadline).format('YYYY-MM-DD')) {
              this.setData({
                isShowToday:true
              })
            }
          
            if (results.taskStatus==='overdue' || results.taskStatus==='undo') {
              this.setData({
                isShowSign: false
              })
            }
          this.handleCloseLoad();
          wx.stopPullDownRefresh()
        } catch (e) {
          console.log('error', e)
          this.handleCloseLoad();
          wx.stopPullDownRefresh()
        } finally {
            if (wx.getStorageSync('memberId')) { 
              this.handleAuthedIdent()
            }
        }
      },

      /***
       * 判断是否可以进入房间探视
       * @returns boleam
       */
      canGoRoom() {
        // 医院设置的讲解进入时间
        const advanceTime = getApp().globalData.advanceTime || 0;
        const nowDate = new Date();
        const businessLicense = this.data.detailObj.businessLicense
        console.log(parseTime(nowDate) > businessLicense)
        //判断现在时间是否大于开始沟通时间
        if (parseTime(nowDate) < businessLicense) {
          console.log('1111')
            const minutes = minutesCha(parseTime(nowDate), businessLicense)
            if (minutes > advanceTime) {
              wx.showModal({
                title: "提示",
                content: '还未到约定沟通时间',
                showCancel: false
              })
              return false;
            } else {
              return true;
            }
          }else{
          console.log('222')
            const minCha = minutesCha(businessLicense, parseTime(nowDate))
            if(minCha > 20){
              wx.showModal({
                title: "提示",
                content: '本次沟通已经结束',
                showCancel: false
              })
              return false
            }else{
              return true
            }
          }
        },

        /**
         * 进入远程房间
         */
        handleGoRoom() {
              if (this.data.isNotCanEnterRoom) {
                return
              }
            // const emtraceFlag = this.canGoRoom()
            // if (emtraceFlag) {
              wx.TUIKit = TIM.create({
                SDKAppID: +wx.$unienv.VUE_APP_TRTC_SDKAPPID
              })
              wx.TUIKitEvent = TIM.EVENT
              // 监听系统级事件
              // wx.TUIKit.on(wx.TUIKitEvent.SDK_READY, this.onSDKReady)
              const nowTime = new Date()
              if (nowTime - this.tapTime < 1000) {
                return
              }
              this.tapTime = nowTime
              this.checkDeviceAuthorize()
                .then(result => {
                  console.log('授权成功', result)
                  wx.navigateTo({
                    url: `/remote/room/room?roomID=${this.data.detailObj.remoteVisitRecordId}&template=sign&memberType=PATIENT&userID=${getApp().globalData.baseInfo.memberId}&signId=${this.data.sigId}&payStatus=${this.data.detailObj.payStatus}&payAmount=${this.data.detailObj.payAmount}`
                  })
                })
                .catch(error => {
                  console.log('没有授权', error)
                })
            // }
          },

          // 检测是否开启摄像头权限
          checkDeviceAuthorize: function () {
            this.hasOpenDeviceAuthorizeModal = false
            return new Promise((resolve, reject) => {
              if (!wx.getSetting || !wx.getSetting()) {
                // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
                resolve()
              }
              wx.getSetting().then(result => {
                console.log('getSetting', result)
                this.authorizeMic = result.authSetting['scope.record']
                this.authorizeCamera = result.authSetting['scope.camera']
                if (
                  result.authSetting['scope.camera'] &&
                  result.authSetting['scope.record']
                ) {
                  // 授权成功
                  resolve()
                } else {
                  // 没有授权，弹出授权窗口
                  // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
                  console.log('getSetting 没有授权，弹出授权窗口', result)
                  wx.authorize({
                      scope: 'scope.record'
                    })
                    .then(res => {
                      console.log('authorize mic', res)
                      this.authorizeMic = true
                      if (this.authorizeCamera) {
                        resolve()
                      }
                    })
                    .catch(error => {
                      console.log('authorize mic error', error)
                      this.authorizeMic = false
                    })
                  wx.authorize({
                      scope: 'scope.camera'
                    })
                    .then(res => {
                      console.log('authorize camera', res)
                      this.authorizeCamera = true
                      if (this.authorizeMic) {
                        resolve()
                      } else {
                        this.openConfirm()
                        reject(new Error('authorize fail'))
                      }
                    })
                    .catch(error => {
                      console.log('authorize camera error', error)
                      this.authorizeCamera = false
                      this.openConfirm()
                      reject(new Error('authorize fail'))
                    })
                }

              })
            })
          },
          /**
           * Loading
           */
          handleLoading() {
            wx.showLoading({
              title: "加载中..."
            });
          },

          handleCloseLoad() {
            wx.hideLoading();
          },

          onPullDownRefresh() {
            this.featureGetDetail();
            this.getHospitalSet()
          }

      })