// pages/backlog/annualInspectionFeedback/annualInspectionFeedback.ts
import { getAction, upload, putAction, postAction } from '../../../api/base';
const dayjs = require('dayjs');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showBox: {
      base: true,
      vehicle: true,
      cost: true,
      check: true
    },
    showSelect: {
      projectSelectShow: false,
      contractSelectShow: false,
      vehicleTypeSelectShow: false,
      templateSelectShow: false,
      yesOrNoSelectShow: false,
      timeSelectShow: false
    } as any,
    vehicleOptionsList: [],
    vehiclePickerIndex: -1,
    insuranceCompanyList: [],
    insuranceCompanyPickerIndex: -1,
    handleStatusOptions: [],
    handleStatusIndex: -1,
    yesOrNoOptions: [
      {
        text: '已处理',
        value: 1
      },
      {
        text: '未处理',
        value: 0
      }
    ],
    requireObj: {
      processedPerson: '',
      validityPeriod: '',
      testingFee: '',
      serviceFee: '',
      miscellaneousFee: ''
    },
    params: {
      drivingLicense: '',
      drivingLicenseList: [],
      detailsTable: '',
      detailsTableList: [],
      vehicleQualificationMark: '',
      vehicleQualificationMarkList: [],
      other: '',
      otherList: []
    } as any,
    changeProjectIndex: -1,
    validityPeriodDateTamp: new Date().getTime(),
    handlingDateTamp: new Date().getTime()
  },
  showBoxInf(e: any) {
    console.log(e);
    let data: any = { ...this.data };
    let { fieldname } = e.currentTarget.dataset;
    // let detail = e.detail;
    data.showBox[fieldname] = !data.showBox[fieldname];
    this.setData(data);
  },
  pickerChange(event: any) {
    //下拉框切换是否展示
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    if (fieldName == 'yesOrNoSelectShow') {
      let { fieldindex } = event.currentTarget.dataset;
      data.changeProjectIndex = fieldindex;
    }
    data.showSelect[fieldName] = true;
    this.setData(data);
  },
  hidePicker() {
    let showSelect = this.data.showSelect;
    showSelect = {
      projectSelectShow: false,
      contractSelectShow: false,
      vehicleTypeSelectShow: false,
      templateSelectShow: false,
      yesOrNoSelectShow: false,
      timeSelectShow: 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 === 'vehicleId') {
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
      data.params.projectId = data.vehicleOptionsList[detail.index].projectId;
      data.params.projectId_dictText =
        data.vehicleOptionsList[detail.index].projectId_dictText;
    } else if (fieldname === 'handlingDate') {
      console.log(data.params.projectList);
      data.params[fieldname] = dayjs(new Date(detail)).format('YYYY-MM-DD');
      // data[fieldindex] = detail.index;
      data.handlingDateTamp = detail;
      console.log(data.params.projectList);
    } else if (fieldname === 'validityPeriod') {
      data.params[fieldname] = dayjs(new Date(detail)).format('YYYY-MM-DD');
      // data[fieldindex] = detail.index;
      data.validityPeriodDateTamp = detail;
      console.log(data.params[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] = '请填写';
    }
    console.log(this.data);
    this.setData(data);
    this.hidePicker();
  },
  getVehicleOptions() {
    let parms = {
      plateNumber: ''
    };
    getAction('api/monitor/vehicle/listByAll', parms).then((res: any) => {
      if (res.code == 200) {
        let arr = [] as any;
        res.result.forEach((item: any, index: number) => {
          arr.push({
            text: item.plateNumber,
            value: item.id,
            projectId: item.projectId,
            projectId_dictText: item.projectId_dictText
          });
          if (
            this.data.params.vehicleId != '' &&
            this.data.params.vehicleId == item.id
          ) {
            this.setData({
              vehiclePickerIndex: index
            });
          }
        });
        this.setData({
          vehicleOptionsList: arr
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  getInsuranceCompanyOptions() {
    getAction('api/base/insuranceCompany/insuranceCompanyList').then(
      (res: any) => {
        if (res.code == 200) {
          let arr = [] as any;
          res.result.forEach((item: any, index: number) => {
            arr.push({
              text: item.name,
              value: item.id
            });
            if (
              this.data.params.insuranceCompanyId != '' &&
              this.data.params.insuranceCompanyId == item.id
            ) {
              this.setData({
                insuranceCompanyPickerIndex: index
              });
            }
          });
          this.setData({
            insuranceCompanyList: arr
          });
        } 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 == 'contract_type') {
          this.setData({
            contractList: res.result,
            contractPickerIndex: -1
          });
          if (this.data.params.contractId != '') {
            let i = res.result.findIndex(
              (x: any) => x.value == this.data.params.contractId
            );
            this.setData({
              contractPickerIndex: i
            });
          }
        } else if (dictCode == 'vehicle_type') {
          this.setData({
            vehicleTypeOptions: res.result,
            vehicleTypeIndex: -1
            // checkStatus: res.result[0]
          });
          if (this.data.params.vehicleType != '') {
            let i = res.result.findIndex(
              (x: any) => x.value == this.data.params.vehicleType
            );
            this.setData({
              vehicleTypeIndex: i
            });
          }
        } else {
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  checkStatusOnChange(e: any) {
    let index = e.currentTarget.dataset.pindex;
    let data: any = { ...this.data };
    data.params.projectList[index].checkStatus = e.detail;
    this.setData(data);
  },
  getInput(e: any) {
    console.log(e);
    let { fieldname, fieldindex, fieldkey } = e.currentTarget.dataset;
    let detail = e.detail;
    let data: any = { ...this.data };
    if (
      fieldname == 'testingFee' ||
      fieldname == 'serviceFee' ||
      fieldname == 'miscellaneousFee'
    ) {
      let regex = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
      data.params[fieldname] = detail.value;
      let total = 0;
      if (regex.test(data.params.testingFee)) {
        // data.params[fieldname] = 0
        total += Number(data.params.testingFee);
        data.requireObj.testingFee = '';
      } else {
        data.requireObj.testingFee = '理赔金额为正数且最多保留两位小数';
      }
      if (regex.test(data.params.serviceFee)) {
        // data.params[fieldname] = 0
        total += Number(data.params.serviceFee);
        data.requireObj.serviceFee = '';
      } else {
        data.requireObj.serviceFee = '理赔金额为正数且最多保留两位小数';
      }
      if (regex.test(data.params.miscellaneousFee)) {
        // data.params[fieldname] = 0
        total += Number(data.params.miscellaneousFee);
        data.requireObj.miscellaneousFee = '';
      } else {
        data.requireObj.miscellaneousFee = '理赔金额为正数且最多保留两位小数';
      }
      data.params.totalFee = total;
    } else if (fieldname == 'vehicleList') {
      data.params[fieldname][fieldindex][fieldkey] = detail.value;
    } else {
      data.params[fieldname] = detail.value;
    }
    if (fieldname == 'processedPerson') {
      if (data.params[fieldname]) {
        // delete data.requireObj[fieldname];
        data.requireObj[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);
  },
  addRow(e: any) {
    console.log(123);
    let { fieldname } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    if (fieldname == 'vehicleList') {
      data.params[fieldname].push({
        vehicleNo: '',
        frameNumber: ''
      });
      data.requireObj[fieldname].push({
        vehicleNo: '',
        frameNumber: ''
      });
    }
    this.setData(data);
  },
  delRow(e: any) {
    let { fieldname, fieldindex } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    if (fieldname == 'vehicleList') {
      let arr = data.params[fieldname],
        value = data.params[fieldname][fieldindex];
      let newSet = new Set(arr);
      newSet.delete(value);
      let newArr = [...newSet];
      data.params[fieldname] = newArr;
      let arr2 = data.requireObj[fieldname],
        value2 = data.requireObj[fieldname][fieldindex];
      let newSet2 = new Set(arr2);
      newSet.delete(value2);
      let newArr2 = [...newSet2];
      data.requireObj[fieldname] = newArr2;
    }
    this.setData(data);
    console.log(data);
  },
  radioOnChange(e: any) {
    console.log(e);
    let { fieldname } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    data.params[fieldname] = e.detail;
    this.setData(data);
  },
  // 上传
  afterRead(e: any) {
    console.log(e);
    let { fieldname } = e.currentTarget.dataset;
    const file = e.detail;
    let option = {
      name: 'file',
      filePath: e.detail.file.url
    };
    upload('api/vehicles/repair/fileUpload', option).then((res: any) => {
      let tempData = JSON.parse(res.data);
      if (tempData.code == 200) {
        let otherPhotoFile: any = this.data.params[fieldname + 'List'];
        otherPhotoFile.push({ ...file, url: tempData.result.fileUrl });
        let data: any = this.data;
        let urls = '';
        otherPhotoFile.forEach((p: any) => {
          urls += p.url + ',';
        });
        urls = urls.slice(0, -1);
        data.params[fieldname] = urls;
        data.params[fieldname + 'List'] = otherPhotoFile;
        console.log(data.params);
        this.setData(data);
      } else {
        wx.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  deletePhoto(e: any) {
    let { fieldname } = e.currentTarget.dataset;
    let otherPhotoFile = this.data.params[fieldname + 'List'];
    let index = e.detail.index;
    otherPhotoFile.splice(index, 1);
    let data: any = this.data;
    let urls = '';
    otherPhotoFile.forEach((p: any) => {
      urls += p.url + ',';
    });
    urls = urls.slice(0, -1);
    data.params[fieldname] = urls;
    data.params[fieldname + 'List'] = otherPhotoFile;
    this.setData(data);
  },
  isStepReady() {
    //校验基础信息
    let isAllReady = true;
    let temp: any = this.data.requireObj;
    let params: any = this.data.params;
    for (let key in temp) {
      if (key == 'id') {
        continue;
      }
      if (key == 'vehicleList') {
        params[key].forEach((item: any, index: number) => {
          if (item.vehicleNo == '') {
            isAllReady = false;
            temp[key][index].vehicleNo = '请填写';
          }
          if (item.frameNumber == '') {
            isAllReady = false;
            temp[key][index].frameNumber = '请填写';
          }
        });
      } else if (key == 'insuranceDate') {
        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]$/;
        if (!timeRegex.test(params[key])) {
          isAllReady = false;
          temp[key] = '请填写正确的时间';
        }
        // temp[key] = temp[key] ? temp[key] : '请填写正确的时间';
      } else if (
        key == 'testingFee' ||
        key == 'serviceFee' ||
        key == 'miscellaneousFee'
      ) {
        // 判断是否是正整数
        let regPos = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
        console.log(!regPos.test(params[key]));
        if (!regPos.test(params[key])) {
          isAllReady = false;
          temp[key] = '理赔金额为正数且最多保留两位小数';
        }
        if (params[key] > 99999999) {
          isAllReady = false;
          temp[key] = '费用金额上限为99999999';
        }
      } else if (params[key] === '') {
        isAllReady = false;
        temp[key] = temp[key] ? temp[key] : '请填写';
      } else {
        temp[key] = '';
      }
    }
    this.setData({
      requireObj: temp
    });
    console.log(temp, isAllReady);
    return isAllReady;
  },
  formSubmit() {
    if (!this.isStepReady()) {
      wx.showToast({
        title: '请填写完整对应信息',
        icon: 'none'
      });
      // 验证是否非空
      return;
    }
    wx.showLoading({
      title: '保存中'
    });
    putAction('api/vehicles/annualInspectionInfo/add', this.data.params).then(
      (res: any) => {
        wx.hideLoading();
        if (res.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
          wx.navigateTo({
            url: '../backlogFeedback/backlogFeedback',
            fail: e => {
              console.log(e);
            }
          });
          // setTimeout(() => {
          //   wx.navigateBack({
          //     delta: 2
          //   });
          // }, 500);
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getVehicleOptions();
    this.getInsuranceCompanyOptions();
    // // 接收传参
    const eventChannel = this.getOpenerEventChannel();

    eventChannel &&
      eventChannel.on &&
      eventChannel.on('eventName', data => {
        console.log('接收参数', data);
        data.drivingLicenseList = [];
        if (data.drivingLicense) {
          for (let i = 0; i < data.drivingLicense.split(',').length; i++) {
            let pic = data.drivingLicense.split(',')[i];
            data.drivingLicenseList.push({
              url: pic,
              name: ''
            });
          }
        }
        data.detailsTableList = [];
        if (data.detailsTable) {
          for (let i = 0; i < data.detailsTable.split(',').length; i++) {
            let pic = data.detailsTable.split(',')[i];
            data.detailsTableList.push({
              url: pic,
              name: ''
            });
          }
        }
        data.vehicleQualificationMarkList = [];
        if (data.vehicleQualificationMark) {
          for (
            let i = 0;
            i < data.vehicleQualificationMark.split(',').length;
            i++
          ) {
            let pic = data.vehicleQualificationMark.split(',')[i];
            data.vehicleQualificationMarkList.push({
              url: pic,
              name: ''
            });
          }
        }
        data.otherList = [];
        if (data.other) {
          for (let i = 0; i < data.other.split(',').length; i++) {
            let pic = data.other.split(',')[i];
            data.otherList.push({
              url: pic,
              name: ''
            });
          }
        }
        this.setData({
          params: data
        });
        // this.getDetail(data.id);
      });
  },

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

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

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

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

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

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

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