// packageA/pages/refuelingCharging/RefuelingChargingReporting/RefuelingChargingReporting.ts
import { postAction, getAction, upload } from '../../../../api/base';
const dayjs = require('dayjs');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    plateNumberListDefault: [] as any,
    plateNumberList: [] as any,
    plateNumberPickerIndex: -1,
    oilTypeList: [] as any,
    oilTypePickerIndex: -1,
    showSelect: {
      oilTypeSelectShow: false,
      recordDateSelectShow: false
    } as any,
    requireObj: {
      // id: '',
      plateNumber: '',
      oilType: '',
      oilCard: '', //油卡
      mileage: '', //加油充电时里程
      amount: '', //数量
      totalPrice: '', //金额
      recordDate: '' // 日期
    },
    // 非必填
    validateObj: {
      driver: '', // 司机
      oilStation: '', // 加油站
      oilCardBalance: '', // 油卡余额
      remark: '' // 备注
    },
    params: {
      id: '',
      sysOrgCode: '', //所属机构
      projectId: '', //所属项目
      vehicleId: '', //车辆id
      vehicleModel: '', //车辆型号
      plateNumber: '', //车牌号
      vehicleType: '', //车辆种类
      driver: '', //驾驶员
      oilStation: '', //加油站
      oilCardBalance: '', //油卡余额
      oilType: '', //油品规格
      oilCard: '', //油卡
      mileage: '', //加油充电时里程
      // "fuelType": "1", //燃料类型
      amount: '', //数量
      totalPrice: '', //金额
      remark: '', //备注
      attachmentUrl: '', //附件
      recordDate: '' // 日期
    } as any,
    loading: false,
    pvIndex: 0,
    searchVal: '',
    price: '—', // 单价
    fileList: [], // 附件:
    uploading: false, // 是否上传中
    recordDateTimeTamp: new Date().getTime() // 日期标签
  },
  selectplateNumber(e: any) {
    this.setData({
      pvIndex: e.detail.value
    });
  },
  //下拉框相关----------
  pickerChange(event: any) {
    //下拉框切换是否展示
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    data.showSelect[fieldName] = true;
    this.setData(data);
  },
  hidePicker() {
    let showSelect = this.data.showSelect;
    showSelect = {
      oilTypeSelectShow: false,
      recordDateSelectShow: false
    };
    this.setData({
      showSelect: showSelect
    });
  },
  pickerConfirm(event: any) {
    console.log(event);
    //下拉框点击确认
    let { fieldname, fieldindex } = event.currentTarget.dataset;
    let detail = event.detail;
    let data: any = { ...this.data };
    if (fieldname === 'plateNumber') {
      console.log(this.data.pvIndex);
      // data.params[fieldname] = this.data.pvIndex;
      // data.params[fieldname] = detail.value.value;
      // data[fieldindex] = detail.index;
      fieldindex = this.data.pvIndex;
      // data.params.fuelType = this.data.plateNumberList[fieldindex].fuelType; // 燃料类型
      if (this.data.plateNumberList[fieldindex].oilCard)
        data.params.oilCard = this.data.plateNumberList[fieldindex].oilCard; //油卡
      data.params.sysOrgCode = this.data.plateNumberList[fieldindex].sysOrgCode; //所属机构
      data.params.projectId = this.data.plateNumberList[fieldindex].projectId; //所属项目
      data.params.vehicleId = this.data.plateNumberList[fieldindex].id; //车辆id
      data.params.vehicleModel =
        this.data.plateNumberList[fieldindex].vehicleModel; //车辆型号
      data.params.plateNumber =
        this.data.plateNumberList[fieldindex].plateNumber; //车牌号
      data.params.vehicleType =
        this.data.plateNumberList[fieldindex].vehicleType; //车辆种类
    } else if (fieldname == 'recordDate') {
      data.params[fieldname] = dayjs(new Date(detail)).format('YYYY-MM-DD');
      data.recordDateTimeTamp = event.detail;
      // data.requireObj[fieldname] = '';
    } else {
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
    }

    if (data.params[fieldname]) {
      // delete data.requireObj[fieldname];
      data.requireObj[fieldname] = '';
    } else {
      data.requireObj[fieldname] = '此项为必填项';
    }
    this.setData(data);
    this.hidePicker();
  },
  // 下拉框相关----------end
  // 输入框相关---------------
  getInput(e: any) {
    console.log(e);
    let { fieldname, fieldindex, fieldkey } = e.currentTarget.dataset;
    let detail = e.detail;
    let data: any = { ...this.data };
    if (
      fieldname == 'amount' ||
      fieldname == 'totalPrice' ||
      fieldname == 'mileage' ||
      fieldname == 'oilCardBalance'
    ) {
      detail.value = detail.value.replace(/[^\d.]/g, ''); // 只能输入数字和.
      detail.value = detail.value.replace(/^\./g, ''); //第一个字符不能是.
      detail.value = detail.value.replace(/\.{2,}/g, '.'); // 不能连续输入.
      detail.value = detail.value.replace(/(\.\d+)\./g, '$1'); // .后面不能再输入.
      detail.value = detail.value.replace(/^0+(\d)/, '$1');
      let reg: RegExp = /^\d+(\.\d{1,2})?$/; //小数部分不能大于2位
      if (!detail.value && fieldname != 'oilCardBalance') {
        data.requireObj[fieldname] = '此项为必填项';
      } else if (!detail.value && fieldname == 'oilCardBalance')
        data.requireObj[fieldname] = '';
      if (detail.value > 999999) {
        // data.params[fieldname] = 999999;
        if (fieldname == 'oilCardBalance')
          data.validateObj[fieldname] = '输入值上限为999999';
        else data.requireObj[fieldname] = '输入值上限为999999';
        data.params[fieldname] = detail.value;
      } else if (!reg.test(detail.value) && detail.value) {
        if (fieldname == 'oilCardBalance')
          data.validateObj[fieldname] = '输入值最多保留两位小数';
        else data.requireObj[fieldname] = '输入值最多保留两位小数';
        data.params[fieldname] = detail.value;
      } else {
        data.params[fieldname] = detail.value;
        if (fieldname == 'oilCardBalance') data.validateObj[fieldname] = '';
        else data.requireObj[fieldname] = '';
      }
      if (data.params.amount && data.params.totalPrice) {
        // 单价
        let price = data.params.totalPrice / data.params.amount;
        data.price = Math.floor(price * 100) / 100;
      } else {
        data.price = '—';
      }
    } else {
      data.params[fieldname] = detail.value;
      if (data.params[fieldname]) {
        // delete data.requireObj[fieldname];
        if (fieldname == 'oilCard')
          data.requireObj[fieldname] = this.checkStr(data.params[fieldname]);
        else {
          if (fieldname == 'remark')
            data.validateObj[fieldname] = this.checkStr(
              data.params[fieldname],
              1000
            );
          else
            data.validateObj[fieldname] = this.checkStr(
              data.params[fieldname],
              64
            );
        }
      } else {
        if (
          fieldname == 'driver' ||
          fieldname == 'oilStation' ||
          fieldname == 'oilCardBalance' ||
          fieldname == 'remark'
        ) {
          data.validateObj[fieldname] = '';
        } else {
          data.requireObj[fieldname] = '此项为必填项';
        }
      }
    }
    this.setData(data);
  },
  clearVal(e: any) {
    let { fieldname, fieldindex, fieldkey } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    if (fieldname == 'projectList') {
      data.params.projectList[fieldindex].remark = '';
    } else if (fieldname == 'vehicleList') {
      data.params[fieldname][fieldindex][fieldkey] = '';
    } else {
      data.params[fieldname] = '';
    }
    this.setData(data);
  },
  // 文件上传
  fileAfterRead(event: any) {
    const file = event.detail;
    let index: any = event.detail.index;
    let { list } = event.currentTarget.dataset;
    let data: any = this.data;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    data[list][index] = {
      status: 'uploading',
      message: '上传中'
    };
    data.uploading = true;
    this.setData(data);
    upload('api/insuranceRecord/upload', option)
      .then((res: any) => {
        let tempData = JSON.parse(res.data);
        if (!tempData.success) {
          wx.showToast({
            title: tempData.message,
            icon: 'none'
          });
          data[list][index] = {
            status: 'failed',
            message: '上传失败'
          };
          data.uploading = false;
          this.setData(data);
          return;
        }
        data[list][index] = {
          ...file,
          url: tempData.message,
          status: 'done',
          message: '上传完成'
        };
        console.log(data[list]);

        data.uploading = false;
        // 地址拼接
        let attachmentUrl = data.params.attachmentUrl
          ? data.params.attachmentUrl + ',' + tempData.message
          : tempData.message;
        data.params.attachmentUrl = attachmentUrl;
        this.setData(data);
      })
      .catch(err => {
        data.uploading = false;
      });
  },
  // 删除文件
  deleteFile(event: any) {
    let { list } = event.currentTarget.dataset;
    let data: any = this.data;
    let index = event.detail.index;
    data[list].splice(index, 1);
    data.params.attachmentUrl = data[list]
      .map((item: any) => {
        return item.url;
      })
      .join(',');
    this.setData(data);
  },
  // 输入框相关---------------end
  // 校验相关-----------------
  checkStr(str: any, lenght = 32) {
    let returnStr = '';
    let spaceRegex = /^\S*$/ as any;
    let regex = /[!@#$%^&*?><|\\\\]/ as any;
    let tooLong = str.length > lenght;
    if (!spaceRegex.test(str)) {
      returnStr = '不支持含有空格';
    } else if (regex.test(str)) {
      returnStr = '不支持特殊字符';
    } else if (tooLong) {
      returnStr = `输入长度不得超过${lenght}个字符`;
    } else {
      returnStr = '';
    }
    return returnStr;
  },
  // 校验文件
  checkFile() {
    let { fileList } = this.data;
    let result = true;
    if (
      fileList.some((item: any) => {
        return item.status == 'failed';
      })
    )
      result = false;
    return result;
  },
  isStepReady() {
    //校验基础信息
    let isAllReady = true;
    let temp: any = this.data.requireObj;
    let validate: any = this.data.validateObj;
    let params: any = this.data.params;
    for (let key in temp) {
      if (key == 'id') {
        continue;
      }
      if (key == 'checkTime') {
        let timeRegex =
          /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/ as any;
        if (!timeRegex.test(params[key])) {
          isAllReady = false;
          temp[key] = '请填写正确的时间';
        }
        // temp[key] = temp[key] ? temp[key] : '请填写正确的时间';
      } else if (key == 'amount' || key == 'totalPrice' || key == 'mileage') {
        // 判断是否是正整数
        let reg: RegExp = /^\d+(\.\d{1,2})?$/; //小数部分不能大于2位
        // console.log(!regPos.test(params[key]));
        // if (!regPos.test(params[key])) {
        //   isAllReady = false;
        //   temp[key] = '输入值为正数且最多保留两位小数';
        // }
        if (!params[key]) {
          isAllReady = false;
          temp[key] = '此项为必填项';
        } else temp[key] = '';
        if (params[key] > 999999) {
          isAllReady = false;
          temp[key] = '输入值上限为999999';
        }
        if (!reg.test(params[key]) && params[key]) {
          isAllReady = false;
          temp[key] = '输入值最多保留两位小数';
        }
      } else if (!params[key]) {
        isAllReady = false;
        temp[key] = temp[key] ? temp[key] : '此项为必填项';
      } else {
        temp[key] = this.checkStr(params[key]);
        if (temp[key]) {
          isAllReady = false;
        }
      }
    }
    // 非必填校验
    for (let key in validate) {
      if (key == 'oilCardBalance') {
        let reg: RegExp = /^\d+(\.\d{1,2})?$/; //小数部分不能大于2位
        if (params[key] > 999999) {
          isAllReady = false;
          validate[key] = '输入值上限为999999';
        }
        if (!reg.test(params[key]) && params[key]) {
          isAllReady = false;
          validate[key] = '输入值最多保留两位小数';
        }
      } else {
        if (key == 'remark') validate[key] = this.checkStr(params[key], 1000);
        else validate[key] = this.checkStr(params[key], 64);
        if (validate[key]) {
          isAllReady = false;
        }
      }
    }
    this.setData({
      requireObj: temp,
      validateObj: validate
    });
    return isAllReady;
  },
  // 校验相关-----------------end
  filterPlateNumberList(e: any) {
    let val = e.detail.value;
    let arr = [] as any;
    if (val) {
      if (this.data.plateNumberListDefault.length > 0) {
        arr = this.data.plateNumberListDefault.filter(
          (item: any) => item.plateNumber.indexOf(val) != -1
        );
      }
    } else {
      arr = this.data.plateNumberListDefault;
    }
    this.setData({
      searchVal: val,
      plateNumberList: arr
    });
  },
  restorePlateNumberList() {
    this.setData({
      searchVal: '',
      plateNumberList: this.data.plateNumberListDefault
    });
  },
  getplateNumberListByProjectId() {
    let userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo);
    let params = {
      projectId: '',
      plateNumber: ''
    };
    getAction('api/vehicle/getVehicleList', params).then((res: any) => {
      if (res.code == 200) {
        let tmp = [];

        this.setData({
          plateNumberListDefault: res.result ? res.result : [],
          plateNumberList: res.result ? res.result : [],
          plateNumberPickerIndex: -1
        });
        // if (this.data.params.plateNumber != '') {
        //   let i = res.result.findIndex(
        //     (x: any) => x.value == this.data.params.plateNumber
        //   );
        //   if (i == -1) {
        //     return;
        //   }
        //   this.setData({
        //     plateNumberPickerIndex: i
        //   });
        // }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 获取字典相关数据
  getDictOptions(dictCode: string) {
    getAction('api/sys/dict/getDictItems/' + dictCode).then((res: any) => {
      if (res.code == 200) {
        if (dictCode == 'oil_type') {
          this.setData({
            oilTypeList: res.result,
            oilTypePickerIndex: -1
          });
          // if (this.data.params.oilType != '') {
          //   let i = res.result.findIndex(
          //     (x: any) => x.value == this.data.params.oilType
          //   );
          //   if (i == -1) {
          //     return;
          //   }
          //   this.setData({
          //     oilTypePickerIndex: i
          //   });
          // }
        } else {
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  formSubmit() {
    if (this.data.loading) {
      wx.showToast({
        title: '信息保存中，请勿重复提交',
        icon: 'none'
      });
      return;
    }
    // 校验文件是否正在上传
    if (this.data.uploading) {
      wx.showToast({
        title: '文件上传中，请稍后',
        icon: 'none'
      });
      return;
    }
    if (!this.isStepReady()) {
      wx.showToast({
        title: '请按照要求填写对应信息',
        icon: 'none'
      });
      // 验证是否非空
      return;
    }
    // 验证非必填
    // if (this.data.params.remark) {
    //   let msg = this.checkStr(this.data.params.remark);
    //   if (msg) {
    //     if (msg == '输入长度不得超过32个字符') {
    //       msg =
    //         this.data.params.remark.length > 200
    //           ? '输入长度不得超过200个字符'
    //           : '';
    //     }
    //     wx.showToast({
    //       title: '备注：' + msg,
    //       icon: 'none'
    //     });
    //     return;
    //   }
    // }
    // 校验是否有错误文件
    if (!this.checkFile()) {
      wx.showToast({
        title: '请删除错误文件',
        icon: 'none'
      });
      return;
    }
    wx.showLoading({
      title: '保存中'
    });
    this.setData({
      loading: true
    });
    postAction('api/gis/refuelChargeRecord/add', this.data.params).then(
      (res: any) => {
        wx.hideLoading();
        this.setData({
          loading: false
        });
        if (res.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
          wx.navigateBack({
            delta: 1
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getDictOptions('oil_type');
    // 获取车辆下拉
    this.getplateNumberListByProjectId();
  },

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

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

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

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

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

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

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