// pages/vehicleMaintenance/maintainSend/maintainSend.ts
import { getAction, postAction } from '../../../../api/base';
const dayjs = require('dayjs');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectProject: null as any, // 项目所选
    selectCar: null as any, // 项目所选
    projectOptions: [], // 项目数据
    carOptions: [] as any,
    filterCarOptions: [] as any, // 过滤后的车辆数据
    filterProjectOptions: [] as any, // 过滤后的项目数据
    repairPeople: '', // 报修人
    phone: '', // 联系电话
    classifyOptions: [] as any, // 报修分类数据
    selectedClassify: [] as any, // 选择的报修分类
    repairContent: '', // 报修内容
    uploadUrl: 'api/vehicles/repair/fileUpload', // 上传图片地址
    repairImgUrl: '' as any, //报修副屏
    repairTimeShow: false, // 展示报修时间选择框
    repairTime: '', // 报修时间
    repairTimestamp: new Date().getTime(),
    plateNumberShow: false, //展示车牌号选择框
    projectShow: false, //展示项目选择框
    plateNumberSearchVal: '', // 查找车牌号输入值
    projectSearchVal: '' // 查找项目输入值
  },
  // 选着报修分类
  selectClassify(e: any) {
    let index = null;
    this.data.selectedClassify.forEach((item: any, idx: number) => {
      if (item == e.currentTarget.dataset.inf.value) index = idx;
    });
    // 如果已经选择，清除
    if (index != null) {
      this.data.selectedClassify.splice(index, 1);
      let data = this.data.classifyOptions;
      data[e.currentTarget.dataset.index].selected = false;
      this.setData({
        classifyOptions: data
      });
    }
    // 如果没有选择，则添加
    else {
      this.data.selectedClassify.push(e.currentTarget.dataset.inf.value);
      let data = this.data.classifyOptions;
      data[e.currentTarget.dataset.index].selected = true;
      this.setData({
        classifyOptions: data
      });
    }
  },
  // 输入报修人
  getRepairPeople(e: any) {
    this.setData({
      repairPeople: e.detail.value
    });
  },
  // 输入联系电话
  getPhone(e: any) {
    this.setData({
      phone: e.detail.value
    });
  },
  checkPhone() {
    let res = this.checkMobilephone();
    if (!res) {
      wx.showToast({
        title: '联系电话格式不正确',
        icon: 'none'
      });
      return false;
    } else return true;
  },
  // 手机号校验方法
  checkMobilephone() {
    const regex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (this.data.phone == '') {
      return true;
    } else {
      if (!regex.test(this.data.phone)) {
        return false;
      } else {
        return true;
      }
    }
  },
  // 输入报修内容
  textareaInput(e: any) {
    this.setData({
      repairContent: e.detail.value
    });
  },
  // 上传图片回显
  returnPic(e: any) {
    let list = [] as any;
    e.detail.photoList.forEach((item: any) => {
      list.push(item.fileUrl);
    });
    this.setData({
      repairImgUrl: list
    });
  },
  // 提交申请
  submit() {
    // 联系电话格式校验
    let checkPhone = this.checkPhone();
    // 校验必填
    let checkProject, checkCar, checkClassify, checkTextarea;
    this.data.selectProject?.projectId
      ? (checkProject = true)
      : (checkProject = false);
    this.data.selectCar?.id ? (checkCar = true) : (checkCar = false);
    this.data.selectedClassify.length > 0
      ? (checkClassify = true)
      : (checkClassify = false);
    this.data.repairContent ? (checkTextarea = true) : (checkTextarea = false);

    if (!checkProject) {
      wx.showToast({
        title: '请选择所属项目',
        icon: 'none'
      });
      return;
    }
    if (!checkCar) {
      wx.showToast({
        title: '请选择所属车辆',
        icon: 'none'
      });
      return;
    }
    if (!this.data.repairTime) {
      wx.showToast({
        title: '请选择报修时间',
        icon: 'none'
      });
      return;
    }
    if (!checkClassify) {
      wx.showToast({
        title: '请选择报修分类',
        icon: 'none'
      });
      return;
    }
    if (!checkTextarea) {
      wx.showToast({
        title: '请填写报修内容',
        icon: 'none'
      });
      return;
    }
    if (!checkPhone) {
      return;
    }
    let params = {
      id: null, //id《新建的仅保存及提交为null，编辑进来的带上数据id》
      flowStatus: 2, //流程状态《仅保存传值：1。提交传值：2》
      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, //发动机码
      repairPeople: this.data.repairPeople, //报修人
      phone: this.data.phone, //联系电话
      repairTime: this.data.repairTime, //报修时间
      repairClass: this.data.selectedClassify.join(','), //报修分类
      repairContent: this.data.repairContent, //报修内容
      repairImgUrl: this.data.repairImgUrl
        ? this.data.repairImgUrl.join(',')
        : '' //报修图片
    };
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    postAction('api/vehicles/repair/addOrEdit', 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,
            flowStatus: 1
          });
          wx.redirectTo({
            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;
          this.setData({
            projectOptions: data,
            filterProjectOptions: data
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  // 获取报修分类
  getRepairClass() {
    getAction('api/vehicles/repair/getRepairClass')
      .then((res: any) => {
        if (res.code == 200) {
          let data = res.result;
          data.forEach((item: any) => {
            item.selected = false;
          });
          this.setData({
            classifyOptions: data
          });
        } 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({
      repairTimeShow: false,
      plateNumberShow: false,
      projectShow: false
    });
  },
  // 选择器点击确认
  pickerConfirm(event: any) {
    let { fieldname } = event.currentTarget.dataset;
    let detail = event.detail;
    // 选择报修时间
    if (fieldname == 'repairTime') {
      this.setData({
        repairTime: dayjs(detail).format('YYYY-MM-DD'),
        repairTimestamp: 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) {
        // 获取车辆数据
        getAction(
          `api/vehicles/repair/queryVehicleInfoByProjectId?projectId=${event.detail.value.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;
              this.setData({
                carOptions: data,
                filterCarOptions: data
              });
            } else {
              wx.showToast({
                title: res.message,
                icon: 'none'
              });
            }
          })
          .catch((err: any) => {
            wx.showToast({
              title: err.message,
              icon: 'none'
            });
          });
      }
    }
    this.hidePicker();
  },
  // 清空数据
  resetData(event: any) {
    let { fieldname } = event.currentTarget.dataset;
    if (fieldname == 'repairPeople') {
      this.setData({
        repairPeople: ''
      });
    } else if (fieldname == 'phone') {
      this.setData({
        phone: ''
      });
    }
  },
  // 过滤车牌号
  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
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},

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

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

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

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

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

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

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