// pages/medinceList/medinceList.js
const app = getApp()
import {
  family,
  addfamily
} from "../../../api/familyDoc";
import {
  cart,
  editCart
} from "../../../api/goodsCar"
import {throttle} from "../../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    show: false,
    isLock: false,
    showAdd: false,
    sex: null,
    delId:'',
    height:970,
    delIndex:-1,
    showDialog:false,
    currentFamilyId: '',
    showPicker: false,
    realName: '',
    idCard: '', //'',
    phoneNumber: '',
    relation: "",

    relationId:"",
    family: [],
    list: [],
    translist:[],
    pageData:[],
    columns: [{
        text: "本人",
        value: 1
      },
      {
        text: "父母",
        value: 2
      },
      {
        text: "爱人",
        value: 3
      },
      {
        text: "子女",
        value: 4
      },
      {
        text: "亲戚",
        value: 5
      },
      {
        text: "其他 ",
        value: 6
      }
    ]
  },
  getCart() {
    cart().then(data => {
     
      this.setData({
        list: data
      })
    })
  },
  confirm(event){
    let {delId,delIndex}=this.data;
   if(event.detail){
     this.handleEditCart(delId,0,delIndex, 'minus');
   }
  },
  onCloseDel(event){
    let index = event.currentTarget.dataset.id;
    //let shopping_cart_num = this.data.list[index].shopping_cart_num;
    let product_id = this.data.list[index].product_id;
    this.setData({
      showDialog:true,
      delId:product_id,
      delIndex:index
    })
  },
  goBack(){
    wx.navigateBack({
      delta: 1,
    })
  },
  minusGoods(event) {
    if (!this.data.isLock) {
      this.setData({
        isLock: true
      })
      let index = event.currentTarget.dataset.id;
      let shopping_cart_num = this.data.list[index].shopping_cart_num;
      let product_id = this.data.list[index].product_id;
      if (shopping_cart_num == 1) {
        this.setData({
          isLock:false,
          showDialog:true,
          delId:product_id,
          delIndex:index
        })
        return false
      }
      --shopping_cart_num;
      this.handleEditCart(product_id, shopping_cart_num, index, 'minus');
    }

  },
  addGoods(event) {
    if (!this.data.isLock) {
      this.setData({
        isLock: true
      })
      let index = event.currentTarget.dataset.id;
      let shopping_cart_num = this.data.list[index].shopping_cart_num;
      let stock = this.data.list[index].stock;
      let product_id = this.data.list[index].product_id;
      if(shopping_cart_num>=5){
        wx.showToast({
          title: '每个药品购买数量不超过5个',
          icon: "none"
        })
        this.setData({
          isLock:false
        })
        return false
      }
      if (shopping_cart_num == stock) {
        this.setData({
          isLock:false
        })
        wx.showToast({
          title: '该商品库存已不足',
          icon: "none"
        })
        return false
      }
      ++shopping_cart_num;
      this.handleEditCart(product_id, shopping_cart_num, index, 'add');
    }

  },
  handleEditCart(product_id, shopping_cart_num, index, type) {
    let item = `list[${index}].shopping_cart_num`;
    editCart({
      product_id: product_id,
      shopping_cart_num: shopping_cart_num
    }).then(data => {
      let number = this.data.totalNumber;
      if (type == "add") {
        ++number
      } else {
        --number
      };
      this.setData({
        [item]: shopping_cart_num,
        totalNumber: number,
        isLock: false
      });
      if(shopping_cart_num==0){
        this.getCart();
      }
    })
  },
  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  goPatientList() {
    if(this.data.list.length==0){
      wx.showToast({
        title: '请先选择药品',
        icon: "none"
      })
      return false
    }
    if (this.data.list.length > 5) {
      wx.showToast({
        title: '最多选择5种药',
        icon: "none"
      })
      return false
    }
    this.setData({
      show: true
    })
  },
  onCloseAdd() {
    this.setData({
      showAdd: false
    });
  },
  onConfirmPicker(event) {
    const {value} = event.detail;
    this.setData({
      relationId: `${value.value}`,
      relation: `${value.text}`,
      showPicker: false
    });
  },

  openPicker() {
    this.setData({
      showPicker: true
    })
  },
  closePicker() {
    this.setData({
      showPicker: false
    })
  },
  inputChange(e) {
    this.setData({
      [e.target.dataset.id]: e.detail.value
    })
  },
  addFamily() {
    let {
      realName,
      idCard,
      phoneNumber,
      relationId,
      sex
    } = this.data;
    addfamily({
      card_name: realName,
      type: 1,
      id_number: idCard,
      mobile: phoneNumber,
      is_default: 0,
      relation: relationId
    }).then((data) => {
      this.getFamily();
      this.setData({
        currentFamilyId:data.family_id,
        realName:'',
        idCard:'',
        phoneNumber:'',
        relationId:'',
        relation:'',
        showAdd:false
      })
     
    })
  },
  addPatient() {
    this.setData({
      showAdd: true,
      currentFamilyId: '',
      sex: ''
    })
  },
  selectPatient(e) {
    let currentFamilyId=e.currentTarget.dataset.familyid;
    let sex=e.currentTarget.dataset.sex;
    let name=e.currentTarget.dataset.name;
    let age=e.currentTarget.dataset.age;
     this.setData({
       currentFamilyId:currentFamilyId,
       sex:sex
     })
  },
  getFamily() {
    family().then((data) => {
      this.setData({
        family: this.transforpage(data)
      })
    })
  },
  transforpage(arr) {
    const pages = []
    let newArr = arr.concat([{
      type: "add"
    }])
    newArr.forEach((item, index) => {
      const page = Math.floor(index / 2)
      if (!pages[page]) {
        pages[page] = []
      }
      pages[page].push(item)
    });
    return pages
  },
  confirmNext() {
    if (!/^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$/.test(this.data.realName)) {
      wx.showToast({
        title: `姓名要求在2-10个字符`,
        icon: 'none',
      });
      return false;
    };
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.data.idCard)) {
      wx.showToast({
        title: `请输入有效的身份证号`,
        icon: 'none',
      });
      return false;
    };

    if (!/^1[3456789]\d{9}$/.test(this.data.phoneNumber)) {
      wx.showToast({
        title: `请输入有效的手机号码！`,
        icon: 'none',
      });
      return false;
    }
  },
  goNext:throttle(function() {
    let {list}=this.data;
    let arr=[];
    for (let i = 0; i < list.length; i++) {
        arr[i]={};
        arr[i].product_id=list[i].product_id;
        arr[i].product_num=list[i].shopping_cart_num;
        arr[i].product_name=list[i].product_name;
        arr[i].product_spec=list[i].product_spec;
    };
    this.setData({
      translist:arr,
      show:false
    })
    let {
      currentFamilyId,
      sex,
      translist
    } = this.data;
    app.method.navigateTo({
      url: '/patient/pages/writeSick/writeSick?family_id='+currentFamilyId+"&inquiry_type=4&product="+JSON.stringify(translist)+"&sex="+sex
    })
  }),
  goSick:throttle(function() {
    if (!/^([\u4e00-\u9fa5\·]{2,10})$/.test(this.data.realName)) {
      wx.showToast({
        title: `姓名要求在2-10个汉字`,
        icon: 'none',
      });
      return false;
    };
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.data.idCard)) {
      wx.showToast({
        title: `请输入有效的身份证号`,
        icon: 'none',
      });
      return false;
    };
    if (this.data.phoneNumber) {
      if (!/^1[3456789]\d{9}$/.test(this.data.phoneNumber)) {
        wx.showToast({
          title: `请输入有效的手机号码！`,
          icon: 'none',
        });
        return false;
      }
    };
    
    let idInfo = this.getIdInfo(this.data.idCard);
    if (idInfo.age < 6) {
      wx.showToast({
        title: `六岁以下儿童不支持线上问诊`,
        icon: 'none',
      });
      return false;
    }
    this.setData({
      sex:idInfo.sex
    })
    this.addFamily()

  }),
  //获取身份证号信息
  getIdInfo(IdCard) {
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (reg.test(IdCard)) {
      let sex
      if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
        sex = '1'
      } else {
        sex = '2'
      }
      var ageDate = new Date()
      var month = ageDate.getMonth() + 1
      var day = ageDate.getDate()
      var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1
      if (IdCard.substring(10, 12) < month || (IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day)) {
        age++
      }
      if (age <= 0) {
        age = 1
      }
      return {
        sex,
        age
      }
    } else {
      return false;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let medinceInfo = options.product;
    if (medinceInfo){
      var info = JSON.parse(medinceInfo);
      info.forEach((item)=>{
        item.shopping_cart_num=item.amount;
      });
      this.setData({
        list: info,
        pageData:info
      })
    }else{
      this.getCart();
    }
    this.getFamily();
 
  },
  onfocus(event){
    this.setData({
      height:970+event.height+120
    })
  },
  onblur(event){
    this.setData({
      height:970
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      img_host:app.hostConfig().imghost
    });
  },

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

  },

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

  },

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

  },

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

  },

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