import { getAction, postAction } from '../../../api/base';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabActive: 0,
    currentflowStatus: 0,
    options: [] as any, // 维修厂数据
    filterOptions: [] as any, // 维修厂过滤后数据
    selectOption: null as any, // 选择的维修厂数据
    contact: '', // 联系人
    contactPhone: '', // 联系人电话
    upkeepObject: {} as any, // 保养单数据
    isCollapsed: false, // 默认为非折叠状态
    userInfo: {} as any, // 用户信息
    repairShopShow: false, // 控制维修厂选择弹窗
    repairShopSearchVal: '', // 维修厂查询过滤输入值
    userInf: ''
  },
  // 变更tab
  changeTab(e: any) {
    console.log(e.currentTarget.dataset.tab);
    this.setData({
      tabActive: e.currentTarget.dataset.tab
    });
  },
  // 收起保养明细
  collapse() {
    this.setData({
      isCollapsed: !this.data.isCollapsed
    });
  },
  getInf() {
    // 获取信息
    let info = wx.getStorageSync('selectMaintain');
    wx.removeStorage({ key: 'selectMaintain' });
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      currentflowStatus: info.flowStatus,
      userInfo: userInfo
    });
    this.getUpkeepObject(info.id);
  },
  // 获取保养单数据
  getUpkeepObject(id: string) {
    if (id) {
      getAction(`api/vehicles/upkeepBill/getUpkeepObjectById?id=${id}`)
        .then((res: any) => {
          if (res.code == 200) {
            let data = res.result;
            if (data.upkeepOffer?.beforeUpkeepImgUrl)
              data.upkeepOffer.beforeUpkeepImgUrl =
                data.upkeepOffer.beforeUpkeepImgUrl.split(',');
            this.setData({
              upkeepObject: data
            });
          } else {
            wx.showToast({
              title: res.message,
              icon: 'none'
            });
          }
        })
        .catch((err: any) => {
          wx.showToast({
            title: err.message,
            icon: 'none'
          });
        });
    }
  },
  getContactPerson(e: any) {
    this.setData({
      contact: e.detail.value
    });
  },
  getTel(e: any) {
    this.setData({
      contactPhone: e.detail.value
    });
  },
  // 手机号校验方法
  checkMobilephone() {
    const regex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (this.data.contactPhone == '') {
      return true;
    } else {
      if (!regex.test(this.data.contactPhone)) {
        return false;
      } else {
        return true;
      }
    }
  },
  checkPhone() {
    let res = this.checkMobilephone();
    if (!res) {
      wx.showToast({
        title: '联系电话格式不正确',
        icon: 'none'
      });
      return false;
    } else return true;
  },
  // 获取维修厂信息
  getRepairShop() {
    getAction('api/vehicles/repair/getRepairShop')
      .then((res: any) => {
        if (res.code == 200) {
          let data = [] as any;
          res.result.forEach((el: any) => {
            el.value = el.repairShop;
            el.text = el.repairShop_dictText;
          });
          data = res.result;
          this.setData({
            options: data,
            filterOptions: data
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  bindCancel() {
    // 作废
    wx.setStorageSync('upkeepObject', this.data.upkeepObject);
    wx.navigateTo({
      url: '../operation/cancel/cancel',
      fail: e => {
        console.log(e);
      }
    });
  },
  // 返回
  goBack() {
    let pageList = getCurrentPages();
    if (pageList && pageList.length != 1) wx.navigateBack();
    else {
      if (this.data.userInfo.type == '1') {
        wx.reLaunch({
          url: '/pages/index/index'
        });
      } else if (this.data.userInfo.type == '2') {
        wx.reLaunch({
          url: '/pages/manufacturerIndex/manufacturerIndex'
        });
      } else if (this.data.userInfo.type == '3') {
        wx.reLaunch({
          url: '/pages/projectIndex/projectIndex'
        });
      } else if (this.data.userInfo.type == '4') {
        wx.reLaunch({
          url: '/pages/maintenanceIndex/maintenanceIndex'
        });
      } else {
        wx.reLaunch({
          url: '/pages/login/login'
        });
      }
    }
  },
  bindSend() {
    // 派单
    if (!this.data.selectOption) {
      wx.showToast({
        title: '请选择维修厂',
        icon: 'none'
      });
      return;
    }
    let res = this.checkPhone();
    if (!res) return;

    let params = {
      id: this.data.upkeepObject.id, //id
      flowStatus: 2, //当前流程状态
      checkFlag: 1, //审核状态   1-》通过， 2-》不通过
      upkeepBill: {},
      upkeepAssign: {
        repairShop: this.data.selectOption.repairShop, //维修厂id
        contact: this.data.contact, //联系人
        contactPhone: this.data.contactPhone //联系电话
      },
      upkeepOffer: {},
      currentUpkeepCheck: {}
    };
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    postAction('api/vehicles/upkeepBill/submitUpkeepObject', params)
      .then((res: any) => {
        if (res.code == 200) {
          wx.hideLoading();
          wx.showToast({
            title: '派单成功',
            icon: 'none'
          });
          wx.setStorageSync('message', {
            repairShop: this.data.selectOption.repairShop_dictText,
            contact: this.data.contact,
            phone: this.data.contactPhone,
            id: this.data.upkeepObject.id,
            flowStatus: 2
          });
          wx.redirectTo({
            url: '../operation/message/message',
            fail: e => {
              console.log(e);
            }
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        wx.hideLoading();
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  // 去报价
  setOffer() {
    wx.setStorageSync('upkeepObject', this.data.upkeepObject);
    wx.navigateTo({
      url: '../operation/offer/offer',
      fail: e => {
        console.log(e);
      }
    });
  },
  // 展示选择框
  pickerChange(event: any) {
    //下拉框切换是否展示
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    data[fieldName] = true;
    this.setData(data);
  },
  // 隐藏展示框
  hidePicker() {
    this.setData({
      repairShopShow: false
    });
  },
  // 选择器点击确认
  pickerConfirm(event: any) {
    let { fieldname } = event.currentTarget.dataset;
    let detail = event.detail;
    // 选择维修厂
    if (fieldname == 'repairShop') {
      this.setData({
        selectOption: detail.value,
        contact: detail.value.contact,
        contactPhone: detail.value.contactPhone
      });
    }
    this.hidePicker();
  },
  // 过滤维修厂
  filterRepairShop(event: any) {
    let list = [] as any;
    this.data.options.forEach((item: any) => {
      if (
        item.repairShop_dictText
          .toLowerCase()
          .indexOf(event.detail.toLowerCase()) >= 0
      ) {
        list.push(item);
      }
    });
    this.setData({
      filterOptions: list,
      repairShopSearchVal: event.detail
    });
  },
  // 清空数据
  resetData(event: any) {
    let { fieldname } = event.currentTarget.dataset;
    if (fieldname == 'contact') {
      this.setData({
        contact: ''
      });
    } else if (fieldname == 'contactPhone') {
      this.setData({
        contactPhone: ''
      });
    }
  },
  // 图片预览
  showImage(event: any) {
    let { index, image } = event.currentTarget.dataset;
    let list = [] as any;
    if (image == 'attachmentList') {
      this.data.upkeepObject.upkeepBill.attachmentList.forEach((item: any) => {
        list.push(item.fileUrl);
      });
    } else if (image == 'beforeUpkeepImgUrl') {
      list = this.data.upkeepObject.upkeepOffer.beforeUpkeepImgUrl;
    } else if (image == 'attachmentUpkeepList') {
      this.data.upkeepObject.upkeepOffer.attachmentUpkeepList.forEach(
        (item: any) => {
          list.push(item.fileUrl);
        }
      );
    }
    wx.previewImage({
      current: list[index | 0], // 当前显示图片的http链接  默认urls[0]
      urls: list // 需要预览的图片http链接列表
    });
  },
  getUserInf() {
    this.setData({
      userInf: wx.getStorageSync('userInfo')
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel && !getApp().EventChannel)
      getApp().EventChannel = eventChannel;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getRepairShop();
    this.getUserInf();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 不放onReady 是因为有可能切出去然后状态改了得跳转到别的页面
    this.getInf();
  },

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

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    let pages = getCurrentPages();
    let idx = null,
      num = 0;
    pages.forEach((item: any, index: number) => {
      if (
        item.route == 'pages/UpkeepBill/UpkeepBillRecord/UpkeepBillRecord' ||
        item.route == 'pages/backlog/backlogList/backlogList'
      )
        idx = index;
    });
    if (idx != null) num = pages.length - 2 - idx;
    console.log(idx, num);
    if (idx != null && num != 0) {
      wx.navigateBack({
        // delta: num,
        delta: 1,
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          if (getApp().EventChannel.emit) getApp().EventChannel.emit('refresh');
        },
        fail: e => {
          console.log(e);
        }
      });
    } else if (idx == null) {
      // if (this.data.userInfo.type == '1') {
      //   wx.reLaunch({
      //     url: '/pages/index/index'
      //   });
      // } else if (this.data.userInfo.type == '2') {
      //   wx.reLaunch({
      //     url: '/pages/manufacturerIndex/manufacturerIndex'
      //   });
      // } else if (this.data.userInfo.type == '3') {
      //   wx.reLaunch({
      //     url: '/pages/projectIndex/projectIndex'
      //   });
      // } else if (this.data.userInfo.type == '4') {
      //   wx.reLaunch({
      //     url: '/pages/maintenanceIndex/maintenanceIndex'
      //   });
      // } else {
      //   wx.reLaunch({
      //     url: '/pages/login/login'
      //   });
      // }
    }
  },

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

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

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