import { getAction, postAction, putAction } from '../../../api/base';
const dayjs = require('dayjs');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    upKeepObject: null as any, // 保养单数据
    selectProject: null as any, // 项目所选
    selectCar: null as any, // 车辆所选
    projectOptions: [], // 项目数据
    carOptions: [] as any, // 车辆数据
    filterCarOptions: [] as any, // 过滤后的车辆数据
    filterProjectOptions: [] as any, // 过滤后的项目数据
    lastMileage: '', // 上次保养里程
    predictMileage: '', // 预计保养里程
    content: '', // 保养内容
    uploadUrl: 'api/vehicles/repair/fileUpload', // 上传图片地址
    attachmentList: [] as any, //附件
    lastTimeShow: false, // 展示上次保养时间选择框
    predictTimeShow: false, // 展示预计保养时间选择框
    lastTime: '', // 上传保养时间
    predictTime: '', // 预计保养时间
    lastTimestamp: new Date().getTime(),
    predictTimestamp: new Date().getTime(),
    plateNumberShow: false, //展示车牌号选择框
    projectShow: false, //展示项目选择框
    plateNumberSearchVal: '', // 查找车牌号输入值
    projectSearchVal: '', // 查找项目输入值
    type: '', // 当前页面状态（新增/编辑）
    echoFile: null as any // 回显附件
  },
  // 输入保养里程
  getMileage(e: any) {
    let { fieldname } = e.currentTarget.dataset;
    let res = null as any;
    e.detail.value = Number(Number(e.detail.value).toFixed(2));
    if (e.detail.value > 99999999) {
      res = 99999999;
      wx.showToast({
        title: '保养里程不能大于99999999',
        icon: 'none'
      });
    } else if (e.detail.value < 0) {
      res = 0;
      wx.showToast({
        title: '保养里程不能小于0',
        icon: 'none'
      });
    } else res = e.detail.value;
    if (fieldname == 'lastMileage') {
      this.setData({
        lastMileage: res
      });
    } else if (fieldname == 'predictMileage') {
      this.setData({
        predictMileage: res
      });
    }
  },
  // 输入保养内容
  textareaInput(e: any) {
    this.setData({
      content: e.detail.value
    });
  },
  // 上传图片回显
  returnPic(e: any) {
    let list = [] as any;
    e.detail.photoList.forEach((item: any) => {
      list.push(item);
    });
    this.setData({
      attachmentList: list
    });
  },
  // 提交申请
  submit() {
    // 校验必填
    let checkProject, checkCar, checkTextarea;
    this.data.selectProject?.projectId
      ? (checkProject = true)
      : (checkProject = false);
    this.data.selectCar?.id ? (checkCar = true) : (checkCar = false);
    this.data.content ? (checkTextarea = true) : (checkTextarea = false);

    if (!checkProject) {
      wx.showToast({
        title: '请选择所属项目',
        icon: 'none'
      });
      return;
    }
    if (!checkCar) {
      wx.showToast({
        title: '请选择所属车辆',
        icon: 'none'
      });
      return;
    }
    if (!this.data.lastTime) {
      wx.showToast({
        title: '请选择上次保养时间',
        icon: 'none'
      });
      return;
    }
    if (this.data.lastMileage === '') {
      wx.showToast({
        title: '请输入上次保养里程',
        icon: 'none'
      });
      return;
    }
    if (!this.data.predictTime) {
      wx.showToast({
        title: '请选择预计保养时间',
        icon: 'none'
      });
      return;
    }
    if (this.data.predictMileage === '') {
      wx.showToast({
        title: '请输入预计保养里程',
        icon: 'none'
      });
      return;
    }
    if (!checkTextarea) {
      wx.showToast({
        title: '请填写保养内容',
        icon: 'none'
      });
      return;
    }
    let fileList = JSON.parse(JSON.stringify(this.data.attachmentList)) as any;
    // 如何有回显的附件且未删除
    if (this.data.echoFile) {
      this.data.echoFile.forEach((item: any) => {
        fileList.push(item);
      });
    }
    let params = {
      id: this.data.type == 'add' ? null : this.data.upKeepObject.id, //id
      projectId: this.data.selectProject?.projectId, //所属项目
      plateNumber: this.data.selectCar?.plateNumber, //车牌号
      deliveryTime: this.data.selectCar?.deliveryTime, //交车时间
      frameNumber: this.data.selectCar?.frameNumber, //车架号
      vehicleBrand: this.data.selectCar?.vehicleBrand, //车辆品牌
      vehicleModel: this.data.selectCar?.vehicleModel, //车辆型号
      vehicleType: this.data.selectCar?.vehicleType, //车辆种类
      vinCode: this.data.selectCar?.vinCode, //VIN码
      engineNumber: this.data.selectCar?.engineNumber, //发动机码
      lastMileage: this.data.lastMileage, //上次保养里程
      lastTime: this.data.lastTime, //上次保养时间
      predictMileage: this.data.predictMileage, //上次保养里程
      predictTime: this.data.predictTime, //上次保养时间
      content: this.data.content, //保养内容
      attachmentList: fileList ? fileList : [] // 附件
    };
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    // 新增
    if (this.data.type == 'add') {
      postAction('api/vehicles/upkeepPlan/add', params)
        .then((res: any) => {
          if (res.code == 200) {
            wx.hideLoading();
            wx.showToast({
              title: '提交成功',
              icon: 'none'
            });
            wx.setStorageSync('message', {
              projectName: this.data.selectProject?.projectName,
              plateNumber: this.data.selectCar?.plateNumber,
              date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              id: res.message,
              auditStatus: 1
            });
            wx.reLaunch({
              url: '../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'
          });
        });
    }
    // 编辑
    else if (this.data.type == 'edit') {
      putAction('api/vehicles/upkeepPlan/edit', params)
        .then((res: any) => {
          if (res.code == 200) {
            wx.hideLoading();
            wx.showToast({
              title: '编辑成功',
              icon: 'none'
            });
            wx.setStorageSync('message', {
              projectName: this.data.selectProject?.projectName,
              plateNumber: this.data.selectCar?.plateNumber,
              date: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              id: this.data.upKeepObject.id,
              auditStatus: 1
            });
            wx.reLaunch({
              url: '../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'
          });
        });
    }
  },
  // 获取项目数据
  getProjects() {
    getAction('api/vehicles/repair/queryProjects')
      .then((res: any) => {
        if (res.code == 200) {
          let data = [] as any;
          res.result.forEach((el: any) => {
            el.value = el.projectId;
            el.text = el.projectName;
          });
          data = res.result;
          // 编辑情况下回显项目
          let selectProject;
          if (this.data.upKeepObject && this.data.type == 'edit') {
            selectProject = data.find((item: any) => {
              return (
                item.projectId == this.data.upKeepObject.upkeepPlan.projectId
              );
            });
            this.getCarFn(selectProject.projectId);
          }
          this.setData({
            projectOptions: data,
            filterProjectOptions: data,
            selectProject: selectProject
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  // 展示选择框
  pickerChange(event: any) {
    //下拉框切换是否展示
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    data[fieldName] = true;
    this.setData(data);
  },
  // 隐藏展示框
  hidePicker() {
    this.setData({
      lastTimeShow: false,
      predictTimeShow: false,
      plateNumberShow: false,
      projectShow: false
    });
  },
  // 选择器点击确认
  pickerConfirm(event: any) {
    let { fieldname } = event.currentTarget.dataset;
    let detail = event.detail;
    // 选择保养时间
    if (fieldname == 'lastTime') {
      this.setData({
        lastTime: dayjs(detail).format('YYYY-MM-DD'),
        lastTimestamp: detail
      });
    } else if (fieldname == 'predictTime') {
      this.setData({
        predictTime: dayjs(detail).format('YYYY-MM-DD'),
        predictTimestamp: detail
      });
    }
    // 选择车牌号
    else if (fieldname == 'plateNumber') {
      this.setData({
        selectCar: event.detail.value
      });
    }
    // 选择项目
    else if (fieldname == 'project') {
      this.setData({
        selectProject: event.detail.value
      });
      if (event.detail.value.projectId) {
        this.getCarFn(event.detail.value.projectId);
      }
    }
    this.hidePicker();
  },
  // 获取车辆数据
  getCarFn(projectId: any) {
    getAction(
      `api/vehicles/repair/queryVehicleInfoByProjectId?projectId=${projectId}`
    )
      .then((res: any) => {
        if (res.code == 200) {
          // 清空当前所选的车辆数据
          this.setData({
            selectCar: null
          });
          let data = [] as any;
          res.result.forEach((el: any) => {
            el.value = el.plateNumber;
            el.text = el.plateNumber;
          });
          data = res.result;
          // 编辑回显
          let selectCar;
          if (data && this.data.type == 'edit') {
            selectCar = data.find((item: any) => {
              return (
                item.plateNumber ==
                this.data.upKeepObject.upkeepPlan.plateNumber
              );
            });
          }
          this.setData({
            carOptions: data,
            filterCarOptions: data,
            selectCar: selectCar
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  // 清空数据
  resetData(event: any) {
    let { fieldname } = event.currentTarget.dataset;
    if (fieldname == 'lastMileage') {
      this.setData({
        lastMileage: ''
      });
    } else if (fieldname == 'predictMileage') {
      this.setData({
        predictMileage: ''
      });
    }
  },
  // 过滤车牌号
  filterPlateNumber(event: any) {
    let list = [] as any;
    this.data.carOptions.forEach((item: any) => {
      if (
        item.plateNumber.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0
      ) {
        list.push(item);
      }
    });
    this.setData({
      filterCarOptions: list,
      plateNumberSearchVal: event.detail
    });
  },
  // 过滤项目
  filterProject(event: any) {
    let list = [] as any;
    this.data.projectOptions.forEach((item: any) => {
      if (
        item.projectName.toLowerCase().indexOf(event.detail.toLowerCase()) >= 0
      ) {
        list.push(item);
      }
    });
    this.setData({
      filterProjectOptions: list,
      projectSearchVal: event.detail
    });
  },
  getInf() {
    let data = wx.getStorageSync('type');
    wx.removeStorage({ key: 'type' });
    if (!this.data.type) {
      this.setData({
        type: data.type
      });
    }
    // 编辑时先获取保养计划数据再获取项目数据和车辆数据
    if (data.info) this.getRepairObject(data.info.id);
    // 新增时获取项目数据
    if (data.type == 'add') this.getProjects();
    let title = data.type == 'add' ? '新增保养' : '保养计划编辑';
    wx.setNavigationBarTitle({
      title: title
    });
  },
  // 获取保养计划单数据
  getRepairObject(id: string) {
    if (id) {
      getAction(`api/vehicles/upkeepPlan/getUpkeepPlanObjectById?id=${id}`)
        .then((res: any) => {
          if (res.code == 200) {
            let data = res.result;
            this.setData({
              lastTime: data.upkeepPlan.lastTime,
              lastMileage: data.upkeepPlan.lastMileage,
              predictTime: data.upkeepPlan.predictTime,
              predictMileage: data.upkeepPlan.predictMileage,
              content: data.upkeepPlan.content,
              echoFile: data.upkeepPlan.attachmentList, // 回显附件
              upKeepObject: data
            });
            this.getProjects();
          } else {
            wx.showToast({
              title: res.message,
              icon: 'none'
            });
          }
        })
        .catch((err: any) => {
          wx.showToast({
            title: err.message,
            icon: 'none'
          });
        });
    }
  },
  // 删除回显图片
  delImg(e: any) {
    let that = this;
    let { index } = e.currentTarget.dataset;
    let { echoFile } = this.data;
    wx.showModal({
      title: '提示',
      content: '是否删除当前照片',
      success(res) {
        if (res.confirm) {
          echoFile.splice(index, 1);
          that.setData({
            echoFile: echoFile
          });
        }
      }
    });
  },
  // 图片预览
  showImage(event: any) {
    let { index, image } = event.currentTarget.dataset;
    let list = [] as any;
    if (image == 'echoFile') {
      this.data.echoFile.forEach((item: any) => {
        list.push(item.fileUrl);
      });
    }
    wx.previewImage({
      current: list[index | 0], // 当前显示图片的http链接  默认urls[0]
      urls: list // 需要预览的图片http链接列表
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 不放onReady 是因为有可能切出去然后状态改了得跳转到别的页面
    this.getInf();
    // 默认保养人为当前用户
    // let userInfo = wx.getStorageSync('userInfo');
  },

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

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

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

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

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