import request from '~/api/request';
Page({

  /**
   * 页面的初始数据
   */

  // 凝血酶原时间(s)/国际标准化比/活化的部分凝血酶时间（s）
  data: {
    style: 'border: 2rpx solid #efefef;border-radius: 12rpx;',

    form: {
      follow_name: '',
      liver_function_image:[],
      b_mode_image: [],
      blood_routine_image: [],
      coagulation_function_image: [],
      mdt_image: [],
      nutritional_indicator_image: []
    },
    isName: true,
    isTime: true,
    isDoctor: true,
    isHeight: true,
    isWeight: true,



    personInfo: {
      name: '',
      gender: 0,
      birth: '',
      address: [],
      introduction: '',
      yearType: 0,

      // photos: [],
    },
    mode: '',
    dateVisible: false,
    date: new Date('2021-12-23').getTime(), // 支持时间戳传入
    dateText: '',
    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,
    },
    imageVisible: false,
    imageList: [],
    imageIndex: 1,

  },
  onInput(e) {
    const { key, tips } = e.currentTarget.dataset;

    if(e.detail.value){
      this.setData({
        [tips]: true,
        [`form.${key}`]: e.detail.value
      });
    } else {
      this.setData({
        [tips]: false,
        [`form.${key}`]: e.detail.value
      })
    }
   
    
  },
  onInputTime(e){
    const { tips } = e.currentTarget.dataset;
    if(e.detail.value){
      this.setData({
        [tips]: true,
      });
    } else {
      this.setData({
        [tips]: false,
      })
    }
  },
  showPicker(e) {
    const { mode } = e.currentTarget.dataset;
    this.setData({
      [`${mode}Visible`]: true,
    });



  },
  onPickerChange(e) {
    if(e.detail.value){
      this.setData({
        isTime: true,
        ['form.follow_date']: e.detail.value
      })
    } else {
      this.setData({
        isTime: false,
        ['form.follow_date']: e.detail.value
      })
    }
    
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },

  planId:'',
  async toQuestionnaire() {
    let valid = true;
    // 必填项校验
    if(!this.data.form.follow_name){
      this.setData({ isName: false });
      valid = false;
    }
    if(!this.data.form.follow_date){
      this.setData({ isTime: false });
      valid = false;
    }
    if(!this.data.form.follow_hospital){
      this.setData({ isDoctor: false });
      valid = false;
    }
    if(!this.data.form.height){
      this.setData({ isHeight: false });
      valid = false;
    }
    if(!this.data.form.weight){
      this.setData({ isWeight: false });
      valid = false;
    }
    if(!valid) return
    const data = this.data.form
    data.liver_function_image = data.liver_function_image.length > 0 ? data.liver_function_image.join(',') : ''
    data.b_mode_image = data.b_mode_image.length > 0 ? data.b_mode_image.join(',') : '',
    data.blood_routine_image = data.blood_routine_image.length > 0 ? data.blood_routine_image.join(',') : '',
    data.coagulation_function_image = data.coagulation_function_image.length > 0 ? data.coagulation_function_image.join(',') : '',
    data.mdt_image = data.mdt_image.length > 0 ? data.mdt_image.join(',') : '',
    data.nutritional_indicator_image = data.nutritional_indicator_image.length > 0 ? data.nutritional_indicator_image.join(',') : ''
    data.is_have_cyst = data.is_have_cyst ? Number(data.is_have_cyst) : 0
    data.is_have_ascites = data.is_have_ascites ? Number(data.is_have_ascites) : 0
    await request('patient/follow_questionnaire', 'post',{plan_id: Number(this.planId), ...data})
    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 2000, 
      complete: () => {
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  handleChangeGroup(e) {
    const { mode } = e.currentTarget.dataset
    this.setData({
      [`form.${mode}`]: e.detail.value
    })
  },
  //上传文件方法 
  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) {
    const { mode } = e.currentTarget.dataset;
    if(this.data.form[mode].length >= 9){
      wx.showToast({ title: '最多上传9张图片!', icon: 'none' });
      return
    }
    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' });
              const { mode } = e.currentTarget.dataset;
              let arr = this.data.form[mode]
              arr.unshift(data)
              this.setData({
                [`form.${mode}`]: arr
              })

              console.log('上传成功:', data); // 输出上传成功后的数据
            }
          });
        } else {
          wx.showToast({ title: '未选择文件!', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '选择文件失败!', icon: 'none' });
        console.error('选择文件失败:', err); // 输出选择文件的错误信息
      }
    });
  },

  imageKey:'',
  handleImagePreview(e){
    const { mode, index } = e.currentTarget.dataset;
    this.imageKey = mode
    console.log(this.data.form[mode])
    this.setData({
      imageList: this.data.form[mode],
      imageIndex: index,
      imageVisible: true
    })
  },
  onClose(){
    this.setData({
      imageVisible: false
    }) 
  },
  handleDelete(e){
    const { mode, index } = e.currentTarget.dataset;
    let arr = this.data.form[mode]
    arr.splice(index, 1)
    this.setData({
      [`form.${mode}`]: arr
    })
  },

  onDelete(e){
    console.log(e)
    let arr = this.data.form[this.imageKey]
    arr.splice(e.detail.index, 1)
    // let imageList = this.data.imageList
    // imageList.splice(this.data.imageIndex, 1)
    let imageIndex = e.detail.index
    this.setData({
      // imageIndex: imageIndex - 1,
      [`form.${this.imageKey}`]: arr,
      imageList: arr,
      imageVisible: arr.length != 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.planId = options.planId
    this.setData({
      ['form.follow_name']: options.name,
      ['form.follow_date']: options.time
    })
    this.getDetail()
  },

  async getDetail(){
    const res = await request('patient/questionnaire_info', 'post',{patient_id : 0, questionnaire_id: Number(this.planId)})
    const data = res
    data.liver_function_image = data.liver_function_image ? data.liver_function_image.split(',') : []
    data.b_mode_image = data.b_mode_image ? data.b_mode_image.split(',') : []
    data.blood_routine_image = data.blood_routine_image ? data.blood_routine_image.split(',') : []
    data.coagulation_function_image = data.coagulation_function_image ? data.coagulation_function_image.split(',') : []
    data.mdt_image = data.mdt_image ? data.mdt_image.split(',') : []
    data.nutritional_indicator_image = data.nutritional_indicator_image ? data.nutritional_indicator_image.split(',') : []
    
    this.setData({
      form: data
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})