import request from '~/api/request';

let modeType = '';
let mode2 = '';
let modeText = ''
let modeIndex = 0
let id = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: [{
      "name": "",
      "dose": "",
      "frequency": "",
      "time": "饭前"
    }],
    start_date: '',
    end_date: '',
    reminder: {
        "morning": "08:00",
        "noon": "12:00",
        "evening": "18:00"
    },
    // 下拉
    selectList: [],
    selectValue: '',
    selectVisible: false,
    
    timeData: '',
    id: '',
    style: 'border: 0;',
    frequencyList:[{
      label: '每日1次',
      value: '1'
    },{
      label: '每日2次',
      value: '2'
    },{
      label: '每日3次',
      value: '3'
    }],
    minute: '',
    startMinute: '2025-04-29 00:00:00',
    dateVisible: false,
    minuteVisible: false,
    date: new Date('2021-12-23').getTime(), // 支持时间戳传入
    dateText: '',
    birthStart:  new Date().getTime(),
    filter(type, options) {
      if (type === 'year') {
        return options.sort((a, b) => b.value - a.value);
      }
      return options;
    },
    popupProps: {
      usingCustomNavbar: true,
    },

    formatter(item, index) {
      if (index === 1) {
        const label = item.label.slice(0, -1);
        return {
          value: item.value,
          label: calendarMonth[Number(label) - 1],
        };
      }
      if (index === 2) {
        const [dateValue, weekValue] = item.label.split(' ');
        const dateSuffixes = {
          1: 'st',
          2: 'nd',
          3: 'rd',
        };
        const weekMap = {
          周一: 'Mon.',
          周二: 'Tues.',
          周三: 'Wed.',
          周四: 'Thurs.',
          周五: 'Fri.',
          周六: 'Sat.',
          周日: 'Sun.',
        };
        const label = dateValue.slice(0, -1);

        return {
          value: item.value,
          label: `${label}${dateSuffixes[label] || 'th'} ${weekMap[weekValue]}`,
        };
      }

      return {
        value: item.value,
        label: item.label.slice(0, -1),
      };
    },

    originFiles: [
      {
        url: 'https://tdesign.gtimg.com/mobile/demos/example4.png',
        name: 'uploaded1.png',
        type: 'image',
        removeBtn: true,
      },
      {
        url: 'https://tdesign.gtimg.com/mobile/demos/example6.png',
        name: 'uploaded2.png',
        type: 'image',
        removeBtn: true,
      },
      {
        url: 'https://tdesign.gtimg.com/mobile/demos/example5.png',
        name: 'uploaded3.png',
        type: 'image',
        removeBtn: true,
      },
    ],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },


  },
  showSelect(e){
    const { mode, index } = e.currentTarget.dataset;
    modeText = mode
    modeIndex = index
    this.setData({
      selectValue: [this.data.detail[index].frequency],
      selectVisible: true,
      
    })
  },
  onSelectChange(e){
    this.setData({
      [`detail[${modeIndex}].frequency`]: e.detail.value[0]
    })
  },
  showPicker(e) {
    const { mode } = e.currentTarget.dataset;
    modeType = mode;
    this.setData({
      birthVisible: true,
      timeData: this.data[mode],
    });
   
  },
  onPickerChange(e){
    this.setData({
      [modeType]: e.detail.value,
    });
  },
  showPickertime(e){
    const { mode } = e.currentTarget.dataset;
    mode2 = mode;
    this.setData({
      minuteVisible: true,
      timeData2: this.data.reminder[mode],
      minute: this.data.reminder[mode]
    });
  },
  onConfirm(e){
    this.setData({
      minuteVisible: false,
      [`reminder.${mode2}`]: e.detail.value,
    });
  },
  hidePickerMinute(){
    this.setData({
      minuteVisible: false,
    });
  },
  onRadioChange(e){
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`detail[${index}].time`]: e.detail.value
    })
  },
  handleSuccess(e) {
    console.log(e.detail)
    const { files } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    console.log(e.detail.file);
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },

  deleteItem(e){
    const { index } = e.currentTarget.dataset;
    this.setData({
      detail: this.data.detail.filter((item, i) => i !== index)
    })
  },
  onPickerCancel(){
    this.setData({
      selectVisible: false,
    });
  },
  async addData(){
    const res = await request('/api/v1/patient/add_therapeutic_regimen','post',{
      detail: JSON.stringify(this.data.detail),
      reminder: JSON.stringify(this.data.reminder),
      start_date: this.data.start_date,
      end_date: this.data.end_date
      
    })
  },

  addItem(){
    this.setData({
      detail: [...this.data.detail, {
          "name": "",
          "dose": "",
          "frequency": "",
          "time": ""
      }]
    })
  },
  onInput(e){
    const { mode, index } = e.currentTarget.dataset;

    this.setData({
      [`detail[${index}].${mode}`]: e.detail.value,
    })
  },
  async saveData(){
    if(this.data.id){
      const res = await request(`patient/medicine_scheme/${this.data.id}`,'put',{
        detail: JSON.stringify(this.data.detail),
        reminder: JSON.stringify(this.data.reminder),
        start_date: this.data.start_date,
        end_date: this.data.end_date
      })
      wx.navigateBack()
    }else{
      const res = await request('patient/medicine_scheme','post',{
        detail: JSON.stringify(this.data.detail),
        reminder: JSON.stringify(this.data.reminder),
        start_date: this.data.start_date,
        end_date: this.data.end_date
      })
      wx.navigateBack()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    if(options.id){
      this.setData({
        id: options.id
      })
      this.getData(options.id)
    }
  },

  async getData(){
   const obj = JSON.parse(await wx.getStorageSync('therapeuticRegimen'));
   this.setData({
    detail: obj.detail,
    start_date: obj.start_date,
    end_date: obj.end_date,
    reminder: JSON.parse(obj.reminder),
   })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})