// pages/writeSick/writeSick.js
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import dayjs from '../../../utils/dayjs.min.js'
import {
  createOrder
} from "../../../api/consult"
import {
  getSign
} from "../../../api/common"
import {
  lastSick
} from "../../../api/consultExpert"
import {
  throttle
} from "../../../utils/util"
import {client_type} from "../../../utils/isPc"
import {isExist,pathographyDetail} from "../../../api/sickRecord"
let urlHost=app.hostConfig().agreehost;
console.log(client_type);
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prevData: null,
    order_no:'',
    pathography_id:'',
    showdialog: false,
    showAgreeDialog: false,
    message: '',
    order_inquiry_id:'',
    doctor_id: '',
    family_id: '',
    chat_id: '',
    inquiry_type: 1,
    inquiry_mode: 1,
    messageTitle: '',
    disease_class_name: '',
    disease_class_id:null,
    show: false,
    startIndex: 0,
    cancelBtn: false,
    showSick: false,
    hideSick: false,
    hideGuomin: false,
    hidePregnant:false,
    disease_desc: '',
    hideFamilysick: false,
    showBack: false,
    is_exist:false,
    columns: [],
    fileList: [],
    lockBtn: false,
    checkSign: false,
    is_allergy_history:null,
    is_family_history:null,
    is_pregnant:null,
    pregnant: '',
    checkAgree: false,
    is_taboo:null,
    diagnosis_date:null,
    product: [],
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    allergy_history: '',
    family_history: '',
    currentDate: new Date().getTime(),
    minDate: new Date('1900/01/01 00:00:00').getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    }

  },
  setInfo(obj){
    let Info =obj;
    for (const key in Info) {
      if (key != "product") {
        if (Info[key]) {
          this.setData({
            [key]: Info[key]
          })
        }
      }

    };
    if (Info.disease_desc) {
      this.setData({
        hideSick: true
      })
    };
    if (Info.pregnant) {
      this.setData({
        hidePregnant: true
      })
    };
    
    if (Info.allergy_history) {
      this.setData({
        hideGuomin: true
      })
    };
    if (Info.family_history) {
      this.setData({
        hideFamilysick: true
      })
    };

    if (Info.fileList) {
      
      this.setData({
        fileList:Info.fileList,
        checkSign: false
      })
    } else {
      this.setData({
        checkSign: true
      })
    }
  },
  getlocalInfo(id){
    let sickInfo = wx.getStorageSync('sickInfo');
    if (sickInfo) {
      var InfoObj = JSON.parse(sickInfo);
      if (InfoObj instanceof Array) {
        let obj=null;
       let  isHas= InfoObj.some((item)=>{
         if(item.family_id==id){
          obj=item;
         }
         return item.family_id==id;
       })
       if(isHas){
        this.setInfo(obj)
       }else{
         this.handleOnlineSick(this.data.family_id);
       }
        // for (let i = 0; i < InfoObj.length; i++) {
        //   if (InfoObj[i].family_id == id) {
        //     Dialog.confirm({
        //       title: '温馨提示',
        //       message: '是否加载之前保存的病情信息？',
        //     }).then(() => {
        //       this.setInfo(InfoObj[i])
        //     }).catch(() => {
         
        //     });
            
        //     break;
        //   };
        // }
      }

    }else{
      this.handleOnlineSick(this.data.family_id);
    }
  },
  handleSetValue(data){
    if(data){
      let obj = {
        disease_class_name: '',
        disease_class_id: '',
        diagnosis_date: '',
        disease_desc: '',
        is_allergy_history:null,
        product: [],
        is_taboo:null,
        is_pregnant:null,
        pregnant: '',
        is_family_history:null,
        allergy_history: '',
        family_history: '',
      }
      for (const key in obj) {
        if (key != "product") {
          if(key=="is_taboo" && !data[key]){
            this.setData({
              [key]: null
            })
          }else{
            this.setData({
              [key]: data[key]
            })
          }
         
        }

      };
      if (data.disease_desc) {
        this.setData({
          hideSick: true
        })
      };
      if (data.pregnant) {
        this.setData({
          hidePregnant: true
        })
      };
      
      if (data.allergy_history) {
        this.setData({
          hideGuomin: true
        })
      };
      if (data.family_history) {
        this.setData({
          hideFamilysick: true
        })
      };
      if (data.diagnose_images) {
        this.setData({
          fileList: data.diagnose_images,
          checkSign: false
        })
      } else {
        this.setData({
          checkSign: false
        })
      }
    }
  },
  handleOnlineSick(id){
    lastSick(id).then(data => {
      this.handleSetValue(data);
    })
  },
  // handleLastSick(id) {
  //   lastSick(id).then(data => {
  //     if (!data){
  //       this.getlocalInfo(id);
  //     } else {
      

  //     }
  //   })
  // },

  onConfirm(event) {
    const {
      value
    } = event.detail;
    this.setData({
      disease_class_name: `${value.disease_class_name}`,
      disease_class_id: `${value.disease_class_id}`,
      showSick: false
    })
  },
  showSick() {
    app.method.navigateTo({
      url: '/patient/pages/commonSick/commonSick'
    })
  },
  delImg(event) {
    let id = event.currentTarget.dataset.id;
    this.data.fileList.splice(id, 1);
    this.setData({
      fileList: this.data.fileList
    })
  },
  previewImage(event) {
    let id = event.currentTarget.dataset.id;
    let urls = this.data.fileList;
    wx.previewImage({
      current: urls[id], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  uploadFile(File) {
    wx.showLoading({
      title: '图片上传中...',
      mask: true
    })
    let THIS = this;
    getSign({
      user_type: 1,
      scene: 2
    }).then((resdata) => {
      let {
        accessid,
        dir,
        policy,
        signature,
        host
      } = resdata;
      let index = File.lastIndexOf(".");
      let houzhui=File.substring(index, File.length);
      let filename = this.data.family_id+new Date().getTime().toString()+(this.data.fileList.length).toString()+houzhui;//File.substring(index + 1, File.length);
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: host, // 仅为示例，非真实的接口地址
          filePath: File,
          name: 'file',
          formData: {
            OSSAccessKeyId: accessid,
            policy,
            key: dir + filename,
            signature
          },
          success(res) {
            if (res.statusCode === 204) {
              let url = host + '/' + dir + filename;
              THIS.setData({
                fileList: THIS.data.fileList.concat([url])
              })
            }
          },
          fail: err => {
            console.log(err);
          }
        });
      })
    })
  },

  upload() {
    if(this.data.fileList.length>=9){
     wx.showToast({
       title: '复诊凭证最多上传9张',
       icon:"none"
     })
     return false
    };
    let THIS = this;
    wx.chooseMedia({
      count: 9-this.data.fileList.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        var imgList = res.tempFiles;
        var promiseFun = [];
        for (let i = 0; i < imgList.length; i++) {
          var file = imgList[i].tempFilePath;
          promiseFun.push(
            THIS.uploadFile(file)
          )
        };
        Promise.all(promiseFun).then((res) => {
          wx.showToast({
            title: '图片上传成功',
            icon: "none"
          })
          THIS.setData({
            checkSign: false
          })
          wx.hideLoading();

        });

      }
    })
  },
  onCancel() {
    this.setData({
      showSick: false
    })
  },
  goRecord:throttle(function(){
   app.method.navigateTo({
     url:'/patient/pages/sickRecord/sickRecord?family_id='+this.data.family_id
   })
  }),
  handleThrottle: throttle(function () {
    this.create_Order()
  }),
  create_Order() {
    let {
      inquiry_type,
      inquiry_mode,
      doctor_id,
      family_id,
      disease_class_id,
      diagnosis_date,
      disease_desc,
      fileList,
      is_allergy_history,
      product,
      is_taboo,
      checkSign,
      is_pregnant,
      pregnant,
      is_family_history,
      allergy_history,
      family_history,
      checkAgree,
      sex
    } = this.data;
    
    if (!disease_class_id) {
      wx.showToast({
        title: '请选择所患疾病',
        icon: "none"
      })
      return false;
    };
    if (!diagnosis_date) {
      wx.showToast({
        title: '请选择确诊日期',
        icon: "none"
      })
      return false;
    };
    if (!disease_desc) {
      wx.showToast({
        title: '请填写病情主诉',
        icon: "none"
      })
      return false;
    };
    if(disease_desc.length<10){
      wx.showToast({
        title: '病情主诉不少于10个字',
        icon: "none"
      })
      return false;
    };
 
    if (fileList.length == 0 && !checkSign) {
      wx.showToast({
        title: '请上传复诊凭证或者勾选凭证遗失或不在身边',
        icon: "none"
      })
      return false;
    }
    if(is_taboo==null && inquiry_type == 4){
      wx.showToast({
        title: '请选择是否服用过您想购买的药品且无相关禁忌',
        icon: "none"
      })
      return false;
    }
    if (is_taboo == 0 && inquiry_type == 4) {
      this.setData({
        showdialog: true,
        messageTitle: "您的情况不适合线上问诊开方，建议线下就诊"
      })
      return false
    };

    if (inquiry_type == 4 && allergy_history) {
      for (let i = 0; i < product.length; i++) {
        if (allergy_history.indexOf(product[i].product_name) != -1) {
          this.setData({
            showdialog: true,
            messageTitle: "您的情况不适合线上问诊开方，建议线下就诊"
          })
          return false
        }

      }
    };
    if(is_allergy_history==null){
      wx.showToast({
        title: '请选择您是否有过敏史',
        icon: "none"
      })
      return false;
    };
    if(is_allergy_history==1){
      if(!allergy_history){
        wx.showToast({
          title: '过敏史内容不能为空',
          icon: "none"
        })
        return false;
      }
    };
    if(is_family_history==null){
      wx.showToast({
        title: '请选择您是否有家族病史',
        icon: "none"
      })
      return false;
    };
    if(is_family_history==1){
      if(!family_history){
        wx.showToast({
          title: '家族病史内容不能为空',
          icon: "none"
        })
        return false;
      }
    };
    if(is_pregnant==null && sex==2){
      wx.showToast({
        title: '请选择您是否处于备孕、妊娠、哺乳期',
        icon: "none"
      })
      return false;
    };
    if (is_pregnant == 1) {
      wx.showToast({
        title: '您的情况不适合线上问诊开方，建议线下就诊',
        icon: "none"
      })
      return false;
    }
    if (!checkAgree) {
      this.setData({
        showAgreeDialog: true
      })
      return false;
    };
    this.setData({
      lockBtn: true
    });
    createOrder({
      patient_id: wx.getStorageSync('CLIENT_USER_ID'),
      doctor_id: doctor_id,
      family_id: family_id,
      disease_class_id: disease_class_id,
      diagnosis_date: diagnosis_date,
      disease_desc: disease_desc,
      is_allergy_history:is_allergy_history,
      is_taboo: is_taboo,
      allergy_history: allergy_history,
      family_history: family_history,
      is_family_history: is_family_history,
      is_pregnant: is_pregnant,
      pregnant: pregnant,
      product: product,
      inquiry_type: inquiry_type,
      inquiry_mode: inquiry_mode,
      diagnose_images: fileList,
      client_type:client_type ,
    }).then((data) => {
      let {
        inquiry_no,
        order_inquiry_id,
        order_no,
      } = data.data;
      let {
        chat_id,
        inquiry_type,
        inquiry_mode
      } = this.data;
      this.setData({
        lockBtn: false
      });
      if(data.status==1){
        app.method.navigateTo({
          url: '/patient/pages/payOrder/payOrder?doctor_id=' + doctor_id + '&inquiry_no=' + inquiry_no + "&chat_id=" + chat_id + "&inquiry_type=" + inquiry_type + "&inquiry_mode=" + inquiry_mode + "&order_inquiry_id=" + order_inquiry_id + "&fromType=chat"
        })
      }else if(data.status==2){
        this.setData({
          showdialog:true,
          messageTitle:"当前患者存在进行中问诊订单",
          order_inquiry_id: order_inquiry_id,
          cancelBtn:true
        })
      }else if(data.status==3){
        this.setData({
            showdialog:true,
            messageTitle:"当前患者存在服务包订单",
            order_no:order_no,
            cancelBtn:true
          })
      }
     

    }).catch((error)=>{
       this.setData({
         showdialog:true,
         messageTitle:error.message,
         cancelBtn:true
       })
    })
  },
  inputChange(e) {
    this.setData({
      [e.target.dataset.id]: e.detail.value
    })
  },
  openPop() {
    this.setData({
      show: true
    })
  },
  handleClose() {
    this.setData({
      show: false
    })
  },
  handleConfirm(event) {
    this.setData({
      show: false
    });
    this.setData({
      diagnosis_date: dayjs(event.detail).format('YYYY-MM-DD')
    });
  },
  handlepathographyDetail(id){
    pathographyDetail(id).then(data=>{
      this.handleSetValue(data);
    })
  },
  handleIsExist(){
    let {family_id}=this.data;
    isExist({
      family_id
    }).then(data=>{
      this.setData({
        is_exist:data.is_exist==0?false:true
      })
    })
  },
  handelFocus(e) {
    let key = e.target.dataset.id;
    let value = e.target.dataset.value;
    if (!e.detail.value) {
      this.setData({
        [key]: false,
        [value]: e.detail.value
      })
    } else {
      this.setData({
        [key]: true,
        [value]: e.detail.value
      })
    }
  },
  handelTextFocus(e) {
    let key = e.target.dataset.id;
    let value = e.target.dataset.value;
    if (!e.detail) {
      this.setData({
        [key]: false,
        [value]: e.detail
      })
    } else {
      this.setData({
        [key]: true,
        [value]: e.detail
      })
    }
  },
  goBack() {

    if (app.globalData.origion == 1) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    } else if (app.globalData.origion == 2) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    } else {
      let {
        disease_class_name,
        diagnosis_date,
        fileList,
        is_allergy_history,
        is_pregnant,
        checkSign,
        checkAgree,
        is_family_history,
        disease_desc
      } = this.data;
      //封装组件后退有bug,通过引用，回退正常
      if (disease_class_name || is_allergy_history  || is_pregnant || is_family_history || fileList.length > 0 || diagnosis_date || disease_desc || checkSign || checkAgree) {
        Dialog.confirm({
            title: '温馨提示',
            message: '是否保存填写的病情信息？',
          }).then(() => {
            this.onSave()
          })
          .catch(() => {
            //wx.setStorageSync('sickInfo','');
            wx.navigateBack({
              delta: 1,
              fail: function () {
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
            })
          });
      } else {

        wx.navigateBack({
          delta: 1
        })
      }
    }
  },
  agreeConfirm(){
   this.setData({
     checkAgree:true
   })
  },
  confirm(event) {
    
    if (event.detail) {
      this.setData({
        showdialog: false
      })
    }
    if(this.data.messageTitle=="当前患者存在进行中问诊订单"){
      let {order_inquiry_id}=this.data;
      app.method.navigateTo({
        url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+ order_inquiry_id,
      })
    }else if(this.data.messageTitle=="当前患者存在服务包订单"){
        let {order_no}=this.data;
        app.method.navigateTo({
            url:  '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id='+order_no,
          })
    }
  },
  cancelAlert(){
    this.setData({
      showdialog: false
    })
  },
  onChangeSign() {
    this.setData({
      checkSign: !this.data.checkSign
    })
    if (this.data.checkSign) {
      this.setData({
        fileList: []
      })
    }
  },
  onChange(event) {
   
    let key = event.target.dataset.id;
    this.setData({
      [key]: event.detail
    });
    if (event.detail == 0) {
      if (key == "is_allergy_history") {
        this.setData({
          allergy_history: ''
        })
      };

      if (key == "is_family_history") {
        this.setData({
          family_history: ''
        })
      };

      if (key == "is_pregnant") {
        this.setData({
          pregnant: ''
        })
      }
    }
  },
  onSave() {
    let {
      family_id,
      allergy_history,
      family_history,
      disease_desc,
      disease_class_name,
      disease_class_id,
      diagnosis_date,
      fileList,
      checkSign,
      checkAgree,
      is_allergy_history,
      is_pregnant,
      pregnant,
      is_family_history,
      is_taboo,
      product
    } = this.data;
    let sickInfo = {
      family_id,
      disease_class_name,
      diagnosis_date,
      fileList,
      disease_class_id,
      disease_desc,
      allergy_history,
      family_history,
      is_allergy_history,
      is_pregnant,
      pregnant,
      checkSign,
      is_taboo,
      product,
      checkAgree,
      is_family_history
    };
    let sickInfo_stroage = wx.getStorageSync("sickInfo");
    if (sickInfo_stroage) {
      let sickInfoObj = JSON.parse(sickInfo_stroage);
      if (sickInfoObj instanceof Array) {
        for (let i = 0; i < sickInfoObj.length; i++) {
          if (sickInfoObj[i].family_id == family_id) {
            sickInfoObj.splice(i, 1);
          }
        }
        sickInfoObj.push(sickInfo);
        wx.setStorageSync('sickInfo', JSON.stringify(sickInfoObj));
      } else {
        sickInfoObj.family_id = family_id;
        wx.setStorageSync('sickInfo', JSON.stringify([sickInfoObj]));
      }
    } else {
      wx.setStorageSync('sickInfo', JSON.stringify([sickInfo]));
    }

    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 订单类型（1:专家问诊 2:快速问诊 3:公益问诊 4:问诊购药）
    console.log(options.inquiry_mode)
    if (options.inquiry_type == 1 || options.inquiry_type == 3) {
      this.setData({
        doctor_id: options.doctor_id,
        family_id: options.family_id,
        chat_id: options.chat_id,
        inquiry_type: options.inquiry_type,
        inquiry_mode: options.inquiry_mode,
        sex: options.sex
      })
    } else {
      if (options.inquiry_type == 4) {
        this.setData({
          startIndex: 1
        })
      }

      this.setData({
        product: options.product ? JSON.parse(options.product) : [],
        family_id: options.family_id,
        inquiry_type: options.inquiry_type,
        sex: options.sex,
        inquiry_mode: 1
      })
    }
    //this.getSick();
   
    this.handleIsExist();
    this.getlocalInfo(options.family_id);
  },
  goAgreement:throttle(function(){
    app.method.navigateTo({
      url:"/patient/pages/linkPage/linkPage?url="+encodeURIComponent(urlHost+'/basic/file/agreement.htm?id=1')
    })
  }),
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      img_host:app.hostConfig().imghost
    });
    let {
      prevData,
      pathography_id,
      family_id
    } = this.data;
    if (prevData) {
      this.setData({
        disease_class_name: prevData.disease_class_name,
        disease_class_id: prevData.disease_class_id,
      })
    }
    console.log(pathography_id)
    if(pathography_id){
      this.handlepathographyDetail(pathography_id)
    }
    // else{
     
    //   //this.handleLastSick(options.family_id);
    // }

   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  
})