const apiArr = require("~/api/water_filter");
const util = require("~/utils/util");

// packages/WaterPurifier/pages/newUpKeep/newUpKeep.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:"",
    time:"",
    desc:"",
    fileList:[],
    deviceList: [], // 设备型号
    equipmentShow: false,
    selectEquipment: {},
    show:false,
    page_num:1,
    page_size:10,
    flag:false,

    minDate:new Date().getTime(),
    formatter(type, value) {
        if (type === 'year') {
          return `${value}年`;
        }
        if (type === 'month') {
          return `${value}月`;
        }
        if (type === 'day') {
            return `${value}日`;
          }
        return value;
    },
  },
  afterRead(e){
    const { file } = e.detail;
    // 验证文件类型
    if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image') {
      wx.showToast({ title: '只能上传 JPG/PNG 格式的图片', icon: 'none' });
      return false;
    }
    // 验证文件大小
    if (file.size > 5 * 1024 * 1024) {
      wx.showToast({ title: '图片大小不能超过 5MB', icon: 'none' });
      return false;
    }
    return true;
  },
  beforeRead(e){
    console.log(e);
    let that = this
    util.uploadFileUrl(e.detail.file.url,(res)=>{
        let datas = JSON.parse(res)
        console.log(datas.data);
        let url = util.img_url + datas.data.path
        let fileList = that.data.fileList
        let obj = {
            url:url,
            name:'avatar'
        }
        fileList.push(obj)
        that.setData({
            fileList
        })
    })
  },
  headerInputChange(e) {
    console.log('1231313', e);
    const { name } = e.currentTarget.dataset;
    if (name === 'desc') {
      this.setData({
        desc: e.detail
      })
      return;
    }
    this.setData({
      [name]: e.detail.value
    })
  },
  submits(){
    let that = this
    if(!that.data.selectEquipment.product_name) {
      wx.showToast({
        title: '请填写设备型号',
        icon: 'none',
      })
      return;
    }
    if(!that.data.phone){
        wx.showToast({
            title: '请填写联系电话',
            icon: 'none',
          })
          return;
    }
    if(!util.isPhone(that.data.phone)){
        wx.showToast({
            title: '请填写正确电话',
            icon: 'none',
          })
          return;
    }
    if(!that.data.time){
        wx.showToast({
            title: '请选择上门时间',
            icon: 'none',
          })
          return;
    }
    if(!that.data.desc){
        wx.showToast({
            title: '请填写报修内容',
            icon: 'none',
          })
          return;
    }
    
    util.postUrl(apiArr.addOrderItem,{
      appointment_time: that.data.time,
      customer_phone: that.data.phone,
      dealer_id: Number(wx.getStorageSync('dealer_id')),
      device_code: that.data.selectEquipment.device_code,
      fault_desc: that.data.desc,
      fault_imgs: that.data.fileList[0]?.url
    },res=>{
        if (res.error) {
          wx.showToast({
            title: '添加维修工单失败',
            icon: 'none',
          })
          return;
        }
        wx.showToast({
          title: res.msg,
          icon: 'none',
          success() {
            setTimeout(() => {
              wx.navigateBack({
                delta:1
              })
            }, 2000)
          }
        })
    })
  },
// 删除图片   
  deleteImg(e){
    console.log(e);
    let that = this
    let fileList = that.data.fileList
    fileList.splice(e.detail.index,1)
    that.setData({
        fileList
    })
  },
  //选择日期
  onInput(event){
    let that =this
    const date = new Date(event.detail); // 获取选中的 Date 对象
    const year = date.getFullYear(); // 获取年份
    const month = date.getMonth() + 1; // 获取月份（注意月份从 0 开始，需要 +1）
    const day = date.getDate(); // 获取日期
    const hours =date.getHours()
    const minutes = date.getMinutes(); 
    const time = `${year}-${month}-${day} ${hours}:${minutes}`;
    console.log(time);
    that.setData({
        time,
        show:false
    })
  },
  
  // 拉起设备型号选择弹窗
  headerEquipmentPopupClick() {
    this.setData({
      equipmentShow: true
    })
  },

  // 取消所选设备信息
  headerCancelClick(){
    this.setData({
      selectEquipment: {}, // 所选设备信息
      equipmentShow: false
    })
  },

  onClosePopup() {
    this.setData({
      equipmentShow: false
    })
  },

  headerSelectClick(e) {
    console.log('e',e);
    this.setData({
      selectEquipment: e.currentTarget.dataset.item,
      phone:e.currentTarget.dataset.item.customer_phone,
      equipmentShow: false
    })
  },

  changeShow(){
    let that = this
    that.setData({
        show:true
    })
  },
  onClose(){
    let that = this
    that.setData({
        show:false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init();
  },

  init() {
    let that = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    util.postUrl(apiArr.getUserList,{
      page_size:50,
      page_num:1,
      user_id: Number(wx.getStorageSync('userId'))
    },res=>{
      wx.hideLoading();
      if (res.rows.length === 0) {
        wx.showToast({
          title: '暂无可选择设备型号',
          success() {
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              })
            }, 2000)
          }
        })
        return;
      }

      res.rows.forEach(item=>{
          item.product_icon = util.img_url + item.product_icon
      })

      that.setData({
        deviceList:res.rows || [],
      })
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})