import request from '~/api/request';

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

  /**
   * 页面的初始数据
   */
  data: {
    imageFile: '',
    detail: [{
      "name": "",
      "dose": "",
      "frequency": "",
      "time": "饭前",
      
    }],
    reminder: {
      "morning": "08:00",
      "noon": "12:00",
      "evening": "18:00"
  },
    start_date: '',
    end_date: '',
    
    // 下拉
    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,
    },
    imageVisible: false,
    imageList: [],
    imageIndex: 1,
    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),
      };
    },

    
    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.start_date || !this.data.end_date){
      wx.showToast({
        title: '请选择用药周期',
        icon: 'none'
      })
      return
    }
    // 校验 detail 是否有空缺项
    const hasDetailEmpty = this.data.detail.some(item => {
      return !item.name || !item.dose || !item.frequency || !item.time;
    });
    if (hasDetailEmpty) {
      wx.showToast({
        title: '请完整填写所有用药信息',
        icon: 'none'
      });
      return;
    }
    // 校验 reminder 是否有空缺项
    const reminder = this.data.reminder;
    if (!reminder.morning || !reminder.noon || !reminder.evening) {
      wx.showToast({
        title: '请设置完整的提醒时间',
        icon: 'none'
      });
      return;
    }
    
    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),
   })
  },

  //上传文件方法 
  async uploadFileToOSS(file, callback) {
    

    const policyData = await request('admin/policy_token', 'post')
    const res = JSON.parse(policyData.token)
    const fileNameWithExt = file.path.split('/').pop(); // hello.png
    const fileName = fileNameWithExt.split('.').slice(0, -1).join('.'); // hello

    const formData = {
      key: 'upload_file/' + fileName,  //上传文件名称
      policy: res.policy,   //表单域
      'x-oss-signature-version': res.x_oss_signature_version,    //指定签名的版本和算法
      'x-oss-credential': res.x_oss_credential,   //指明派生密钥的参数集
      'x-oss-date': res.x_oss_date,   //请求的时间
      'x-oss-signature': res.signature,   //签名认证描述信息
      'x-oss-security-token': res.security_token,  //安全令牌
      success_action_status: "200"  //上传成功后响应状态码
    };
    // console.log(filePath)
    // return
    // 发送请求上传文件 
    wx.uploadFile({
      url: 'https://image-fudan.oss-cn-beijing.aliyuncs.com/', 
      method: 'put',
      filePath: file.path,
      name: 'file',   //固定值为file
      formData: formData,
      success(res) {
        console.log('上传响应:', res);
        if (res.statusCode === 200) {
          callback(null, 'https://image-fudan.oss-cn-beijing.aliyuncs.com/upload_file/'+ fileName); // 上传成功
        } else {
          console.error('上传失败，状态码:', res.statusCode);
          console.error('失败响应:', res);
          callback(res); // 上传失败，返回响应
        }
      },
      fail(err) {
        console.error('上传失败:', err); // 输出错误信息
        wx.showToast({ title: '上传失败，请重试!', icon: 'none' });
        callback(err); // 调用回调处理错误
      }
    });
    
  },
  handleUpload(e) {
    wx.chooseImage({
      count: 1, // 选择一个文件
      type: 'all', // 支持所有类型的文件
      success: (res) => {
        wx.showToast({ title: '文件上传中，请稍等!', icon: 'none' });
        console.log('选择的文件:', res.tempFiles); // 输出选择的文件信息
        if (res.tempFiles.length > 0) {
          const tempFilePath = res.tempFiles[0]; 
          console.log('选择的文件路径:', tempFilePath); // 输出文件路径
          this.uploadFileToOSS(tempFilePath, (error, data) => {
            if (error) {
              wx.showToast({ title: '上传失败!', icon: 'none' });
              console.error('上传失败:', error); // 输出具体的错误信息
            } else {
              wx.showToast({ title: '上传成功!', icon: 'success' });
             
              this.setData({
                imageFile: data
              })

              console.log('上传成功:', data); // 输出上传成功后的数据
            }
          });
        } else {
          wx.showToast({ title: '未选择文件!', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '选择文件失败!', icon: 'none' });
        console.error('选择文件失败:', err); // 输出选择文件的错误信息
      }
    });
  },
  handleDelete(e){
    this.setData({
      imageFile: ''
    });
  },
  handleImagePreview(e){
   
    this.setData({
      imageList: [this.data.imageFile],
      imageIndex: 1,
      imageVisible: true
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})