import Toast from '@vant/weapp/toast/toast';
import { API } from './../../../utils/network/api'
import Dialog from '@vant/weapp/dialog/dialog';

const api = new API()
const app = getApp()
Page({
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '在线开方', //导航栏 中间的标题
    },
    autoHeight:{ minHeight: 100},
    add_disease_desc:'',//医生填写的病情主诉
    height: app.globalData.height,   
    zhenduan_popshow: false,
    drugs_popshow: false,
    note_popshow: false,
    disease_class_name: "",
    zhenduan_search_list: [],
    zhenduan_list: [],
    note_columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
    drugs_box_item_list:[],
    drug_content_show: false,
    search_drug_list_empty: true,
    search_drug_list: [],
    product_name: "",
    select_drug_id: "",
    save_durg_product_id: "",
    save_durg_prescription_product_num: "",
    save_durg_single_unit: "",
    save_durg_single_use: "",
    save_durg_packaging_unit: "",
    save_durg_frequency_use: "",
    save_durg_available_days: "",
    order_inquiry_id: "",
    order_prescription_id: "",
    doctor_advice: "",
    doctors_advice_focus: false,
    case_detail: {},
    sub_disabled: false,
    from: "",
    now_filed_focus: 'save_durg_prescription_product_num',
    page_meta_show: true,
    static_host: api.getStaticHost()
  },
  changeFocus(e){
    let next_filed_focus = e.currentTarget.dataset.next_filed_focus;
    this.setData({
      now_filed_focus: next_filed_focus
    })
  },
  onDoctorsAdviceFocus(){
    this.setData({
      doctors_advice_focus: true
    })
  },
  onLoad(options){
    let from = options.from;
    let order_inquiry_id = options.order_inquiry_id;
    let order_prescription_id	 = options.order_prescription_id	;
    //获取患者问诊病例
    api.getDoctorInquiryCase({order_inquiry_id: order_inquiry_id}).then(response => {
      console.log(response);
      this.setData({
        case_detail: response.data
      })
    }).then(res => {
      //有处方id，才去请求详情
      if(order_prescription_id){
        this.getDoctorPrescriptionInfo(order_inquiry_id, order_prescription_id);
      }
    }).catch(errors => {console.error(errors);})
    this.setData({
      order_inquiry_id: order_inquiry_id,
      order_prescription_id: order_prescription_id,
      from: from
    })
    if(from == 'chat'){
      this.setData({
        "navbarData.title": '处方详情'
      })
    }
  },
  select_drug(e){
    this.setData({
      drug_content_show: true,
      product_name: e.currentTarget.dataset.product_name,
      select_drug_id: e.currentTarget.dataset.product_id,
      save_durg_product_id: e.currentTarget.dataset.product_id,
      save_durg_single_use: e.currentTarget.dataset.single_use,
      save_durg_frequency_use: e.currentTarget.dataset.frequency_use,
      save_durg_single_unit: e.currentTarget.dataset.single_unit,
      save_durg_available_days: e.currentTarget.dataset.available_days,
      save_durg_packaging_unit: e.currentTarget.dataset.packaging_unit,
    });
  },
  showPopup() {
    this.setData({ drugs_popshow: true });
  },

  onClose() {
    var _this = this;
    this.setData({ 
      drugs_popshow: false,
    });

    setTimeout(function(){
      _this.setData({ 
        drug_content_show: false,
        search_value: ""
      });
    },1000)
  },

  showNotePopup() {
    this.setData({ note_popshow: true });
  },

  onCloseNote() {
    this.setData({ note_popshow: false });
  },

  onConfirmNote(event) {
    const { picker, value, index } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
    this.setData({ note_popshow: false });
  },

  onCancelNote(event) {
    const { picker, value, index } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
    this.setData({ note_popshow: false });
  },

  onChangeNote(event) {
    const { picker, value, index } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
  },

  saveDrugs(){
    console.log("saveDrugs");

    let product_id = this.data.save_durg_product_id;
    this.delDrugBox(product_id);
    let save_durg_prescription_product_num = this.data.save_durg_prescription_product_num;

    if(!save_durg_prescription_product_num || save_durg_prescription_product_num <0){
      Dialog.alert({
        message: '请输入药品数量',
      }).then(() => {
        this.setData({
          save_durg_prescription_product_num: ""
        })
      });
      return
    }

    let save_durg = {};
    save_durg.product_name = this.data.product_name;
    save_durg.product_id = this.data.save_durg_product_id;
    save_durg.prescription_product_num = this.data.save_durg_prescription_product_num;
    
    save_durg.single_unit = this.data.save_durg_single_unit;
    save_durg.single_use = this.data.save_durg_single_use;
    save_durg.packaging_unit = this.data.save_durg_packaging_unit;
    save_durg.frequency_use = this.data.save_durg_frequency_use;
    save_durg.available_days = this.data.save_durg_available_days;
    let list = this.data.drugs_box_item_list;
    list.push(save_durg);
    this.setData({
      drugs_box_item_list: list,
      drugs_popshow: false,
      product_name: "",
      drug_content_show: false,
      search_drug_list: [],
      save_durg_product_id: "",
      save_durg_prescription_product_num: "",
      save_durg_single_unit: "",
      save_durg_single_use: "",
      save_durg_packaging_unit: "",
      save_durg_frequency_use: "",
      save_durg_available_days: ""
    })
    
  },
  showZhenDuan(){
    this.setData({
      zhenduan_popshow: true
    })
  },
  onZhenDuanChange(e){
    console.log(e)
    let name = e.detail;
    this.setData({
      zhenduan_search_list: []
    })
    if(name){
      this.search();
    }
  },
  search(){
    //搜索诊断
    let params = {};
    params.icd_keyword = this.data.disease_class_name;
    api.getBasicIcdSearch(params).then(response => {
      console.log(response);
      this.setData({
        zhenduan_search_list: response.data
      })
    }).catch(errors => {
      console.error(errors);
    })
  },
  searchDrug(){
    //搜索药品
    let params = {};
    params.product_keyword = this.data.product_name;
    api.getBasicProductSearch(params).then(response => {
      console.log(response);
      this.setData({
        drug_content_show: false
      })
      if(response.data.length > 0){
        this.setData({
          search_drug_list_empty: false,
          search_drug_list: response.data,
        })
      }
    }).catch(errors => {
      console.error(errors);
    })
  },
  onDrugChange(e){
    console.log(e.detail);
    let name = e.detail;
    this.setData({
      search_drug_list_empty: true,
      search_drug_list: []
    })
    if(name){
      this.searchDrug();
    }
  },
  onZhenduanClose(){
    this.setData({
      zhenduan_popshow: false
    })
  },
  addZhenDuan(e){
    let icd_name = e.currentTarget.dataset.icd_name;
    let icd_id = e.currentTarget.dataset.icd_id;
    console.log("icd_name: ", icd_name);
    console.log("icd_id: ", icd_id);

    let disease_obj = {};
    disease_obj.icd_name = icd_name;
    disease_obj.icd_id = icd_id;
    let list = this.data.zhenduan_list;
    let find_index = list.findIndex(item => {
      return item.icd_id == icd_id
    });
    if(find_index == -1){
      list.push(disease_obj);
    }
    this.setData({
      zhenduan_list: list,
      zhenduan_popshow: false
    })
  },
  delZhenDuan(e){
    let disease_class_id = e.currentTarget.dataset.disease_class_id;
    console.log("disease_class_id: ", disease_class_id);
    let list = this.data.zhenduan_list;
    let find_index = list.findIndex(item => {
      return item.icd_id == disease_class_id
    });
    console.log("find_idex： ", find_index)
    list.splice(find_index, 1);
    this.setData({
      zhenduan_list: list
    })
  },
  go(e){
    let url = e.currentTarget.dataset.url;
    console.log(url);
    app.go(url);
  },
  editDrug(e){
    let product_id = e.currentTarget.dataset.product_id;
    console.log(product_id);
    let list = this.data.drugs_box_item_list;
    let drug = list.find(item => {
      return item.product_id == product_id;
    })
    console.log(drug);
    this.setData({
      drugs_popshow: true,
      product_name: drug.product_name,
      drug_content_show: true,
      save_durg_product_id: drug.product_id,
      save_durg_prescription_product_num: drug.prescription_product_num,
      save_durg_single_unit: drug.single_unit,
      save_durg_single_use: drug.single_use,
      save_durg_packaging_unit: drug.packaging_unit,
      save_durg_frequency_use: drug.frequency_use,
      save_durg_available_days: drug.available_days
    })
  },
  delDrug(e){
    let product_id = e.currentTarget.dataset.product_id;
    console.log(product_id);
    this.delDrugBox(product_id);
  },
  delDrugBox(product_id){
    let list = this.data.drugs_box_item_list;
    let drug_index = list.findIndex(item => {
      return item.product_id == product_id;
    })
    console.log(drug_index);
    if(drug_index > -1){
      list.splice(drug_index, 1);
      this.setData({
        drugs_box_item_list: list
      })
    }
  },
  onChangeTextAraa(event){
    this.setData({
      add_disease_desc:event.detail
    })
  },
  getAdvice(e){
    console.log(e.detail.value)
    this.setData({
      doctor_advice: e.detail.value
    })
  },
  postDoctorPrescription(e){//新增处方
    
    let sub_disabled = this.data.sub_disabled;
    if(sub_disabled) return

    console.log("postDoctorPrescription postDoctorPrescription");
    //先置灰，避免重复提交
    this.setData({
      sub_disabled: true
    })

    let params = {};
    params.order_inquiry_id = this.data.order_inquiry_id;
    params.doctor_advice = this.data.doctor_advice;
    let prescription_icd = [];
    this.data.zhenduan_list.forEach(item => {
      prescription_icd.push(item.icd_id);
    })
    params.prescription_icd = prescription_icd;
    params.prescription_product = this.data.drugs_box_item_list;

    console.log(params);
    //糖组检测需要填病情主诉；
    let disease_desc=this.data.case_detail.disease_desc;
    params.disease_desc=disease_desc?disease_desc:this.data.add_disease_desc;
    if(!params.disease_desc){
      wx.showToast({
        title: '请填写病情主诉',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(prescription_icd.length == 0){
      wx.showToast({
        title: '请选择诊断',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(params.prescription_product.length == 0){
      wx.showToast({
        title: '请选择药品',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(this.data.doctor_advice == ""){
      wx.showToast({
        title: '请填写医嘱',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(this.data.doctor_advice.length < 5 || this.data.doctor_advice.length > 200){
      wx.showToast({
        title: '医嘱字数5-20',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }


    api.postDoctorPrescription(params).then(response => {
      console.log(response);
      wx.showToast({
        title: '提交成功',
        icon: "success"
      })
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    }).catch(errors => {
      console.error(errors);
      this.setData({
        sub_disabled: false
      })
    })
  },
  get_save_durg_prescription_product_num(e){
    console.log("get_save_durg_prescription_product_num")
    let save_durg_prescription_product_num = e.detail
    console.log(typeof save_durg_prescription_product_num)
    save_durg_prescription_product_num = Number.parseInt(save_durg_prescription_product_num)
    console.log(save_durg_prescription_product_num)
    if(isNaN(save_durg_prescription_product_num)){
      Dialog.alert({
        message: '请输入正确数字',
      }).then(() => {
        this.setData({
          save_durg_prescription_product_num: ""
        })
      });
      return
    }

    if(save_durg_prescription_product_num > 5){
      Dialog.alert({
        message: '每个药品数量不允许添加超过5个',
      }).then(() => {
        this.setData({
          save_durg_prescription_product_num: ""
        })
      });
      return
    }
    this.setData({
      save_durg_prescription_product_num: save_durg_prescription_product_num
    })
  },
  putDoctorPrescription(){//修改处方
    let sub_disabled = this.data.sub_disabled;
    if(sub_disabled) return

    console.log("putDoctorPrescription putDoctorPrescription");
    //先置灰，避免重复提交
    this.setData({
      sub_disabled: true
    })

    let params = {};
    params.order_prescription_id = this.data.order_prescription_id;
    params.doctor_advice = this.data.doctor_advice;
    let prescription_icd = [];
    this.data.zhenduan_list.forEach(item => {
      prescription_icd.push(item.icd_id);
    })
    params.prescription_icd = prescription_icd;
    params.prescription_product = this.data.drugs_box_item_list;

    console.log(params);

    if(prescription_icd.length == 0){
      wx.showToast({
        title: '请选择诊断',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(params.prescription_product.length == 0){
      wx.showToast({
        title: '请选择药品',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(this.data.doctor_advice == ""){
      wx.showToast({
        title: '请填写医嘱',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }
    if(this.data.doctor_advice.length < 5 || this.data.doctor_advice.length > 200){
      wx.showToast({
        title: '医嘱字数5-20',
        icon: "error"
      })
      this.setData({
        sub_disabled: false
      })
      return;
    }

    api.putDoctorPrescription(params).then(response => {
      console.log(response);
      wx.showToast({
        title: '提交成功',
        icon: "success"
      })
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    }).catch(errors => {
      console.error(errors);
      this.setData({
        sub_disabled: false
      })
    })
  },
  getDoctorPrescriptionInfo(order_inquiry_id, order_prescription_id){//获取处方详情
    let params = {};
    params.order_inquiry_id = order_inquiry_id;
    params.order_prescription_id = order_prescription_id;
    api.getDoctorPrescriptionInfo(params).then(response => {
      console.log(response);
      this.setData({
        doctor_advice: response.data.prescription.doctor_advice,
        pharmacist_audit_status: response.data.prescription.pharmacist_audit_status,
        zhenduan_list: response.data.prescription_icd,
        drugs_box_item_list: response.data.prescription_product
      })
    }).catch(errors => {console.error(errors);})
  }
})