// pages/handoverVehicle/rentalDeliveryEdit/rentalDeliveryEdit.ts
import { getAction, upload, putAction, postAction } from '../../../api/base';
const dayjs = require('dayjs');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'KDEBZ-EV5KH-XN5DU-WYZGD-SN3YK-WZBZI'
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabActive: 0,
    showBox: {
      base: true,
      vehicle: true,
      check: true
    },
    showSelect: {
      projectSelectShow: false,
      contractSelectShow: false,
      vehicleTypeSelectShow: false,
      templateSelectShow: false,
      yesOrNoSelectShow: false,
      timeSelectShow: false,
      sentVehicleUserSelectShow: false
    } as any,
    projectOptionsList: [],
    projectPickerIndex: -1,
    contractList: [],
    contractPickerIndex: -1,
    vehicleTypeOptions: [],
    vehicleTypeIndex: -1,
    templateOptions: [],
    templateIndex: -1,
    sentVehicleUserOptions: [],
    sentVehicleUserIndex: -1,
    userList: [],
    sentVehicleUserPickerIndex: -1,
    checkUserPickerIndex: -1,
    yesOrNoOptions: [
      {
        text: '是',
        value: 1
      },
      {
        text: '否',
        value: 0
      }
    ],
    requireObj: {
      id: '',
      projectId: '',
      contractId: '',
      // vehicleType: '',
      // templateId: '',
      // vehicleList: [] as any,
      projectList: [] as any,
      sentVehicleUserId: '',
      checkUserName: '',
      checkTime: '',
      // checkAddress: '',
      checkStatus: ''
    },
    requireObj1: {
      id: '',
      projectId: '',
      contractId: '',
      // vehicleType: '',
      // templateId: '',
      // vehicleList: [] as any,
      // projectList: [] as any,
      sentVehicleUser: '',
      checkUserId: '',
      checkTime: '',
      // checkAddress: '',
      checkStatus: ''
    },
    params: {
      id: '',
      checkType: '2',
      projectId: '',
      projectName: '',
      contractId: '',
      vehicleType: '',
      templateId: '',
      vehicleList: [],
      projectList: [],
      sentVehicleUser: '',
      checkUserName: '',
      acceptUserName: '',
      checkTime: '',
      checkAddress: '',
      checkStatus: '',
      ckeckUrl: '',
      ckeckUrlList: [] as any,
      ensureUrl: '',
      ensureUrlList: [] as any,
      otherUrl: '',
      otherUrlList: [] as any
    } as any,
    changeProjectIndex: -1,
    checkTimeTamp: new Date().getTime(),
    registrationTimeTamp: new Date().getTime(),
    loading: false,
    uploading: false,
    defaultData: {} as any
  },
  // 变更tab
  changeTab(e: any) {
    this.setData({
      tabActive: e.currentTarget.dataset.tab,
      params:
        e.currentTarget.dataset.tab == 0
          ? this.data.defaultData
          : this.data.defaultData.children,
      checkTimeTamp:
        this.data.defaultData.tabActive == '0'
          ? new Date(this.data.defaultData.checkTime).getTime()
          : new Date(this.data.defaultData.children.checkTime).getTime(),
      registrationTimeTamp:
        this.data.defaultData.tabActive == '0'
          ? new Date(this.data.defaultData.checkTime).getTime()
          : new Date(this.data.defaultData.children.checkTime).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;
    } else if (fieldName === 'timeSelectShow') {
      if (!data.params.checkTime) {
        data.checkTimeTamp = new Date().getTime();
      }
    } else if (fieldName === 'registrationTimeShow') {
      if (!data.params.registrationTime) {
        data.registrationTimeTamp = new Date().getTime();
      }
    }
    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 === 'projectId') {
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
      data.params.contractId = '';
      this.getContractOptions(detail.value.value);
    } else if (fieldname === 'vehicleType') {
      // data.params.projectId = detail.value.projectId;
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
      data.params.templateId = '';
      data.templateIndex = -1;
      this.getvehicleCheckTemplate(detail.value.value);
      data.params.projectList = [];
      // if (data.params.projectId) {
      //   delete data.requireObj.projectId;
      // } else {
      //   data.requireObj.projectId = '此项为必填项';
      // }
      // if (data.params.director) {
      //   delete data.requireObj.director;
      // } else {
      //   data.requireObj.director = '此项为必填项';
      // }
    } else if (fieldname === 'templateId') {
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
      this.getTemplateProject(detail.value.value);
    } else if (fieldname === 'checkStatus') {
      console.log(data.params.projectList);
      let index = data.changeProjectIndex;
      data.params.projectList[index][fieldname] = detail.value.value;
      // data[fieldindex] = detail.index;
      console.log(data.params.projectList);
    } else if (fieldname === 'checkTime' || fieldname === 'registrationTime') {
      console.log(data.params.checkTime);
      data.params[fieldname] = dayjs(new Date(detail)).format('YYYY-MM-DD');
      // data[fieldindex] = detail.index;
      console.log(data.params[fieldname]);
    } else {
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
    }

    if (fieldname !== 'checkStatus') {
      if (data.params[fieldname]) {
        // delete data.requireObj[fieldname];
        data.requireObj[fieldname] = '';
      } else {
        data.requireObj[fieldname] = '此项为必填项';
      }
    }
    console.log(this.data);
    this.setData(data);
    this.hidePicker();
    if (
      (fieldname === 'projectId' || fieldname === 'vehicleType') &&
      data.params.projectId != '' &&
      data.params.vehicleType != ''
    ) {
      this.getvehicleByproject();
    }
  },
  changeAddress(e: any) {
    let that = this;
    let { params, requireObj } = this.data;
    let addressErr = e.currentTarget.dataset.fieldkey;
    let address = addressErr == '0' ? this.data.params.checkAddress : '';
    if (!address) {
      wx.getLocation({
        // type: 'wgs84',
        type: 'gcj02', // wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
        isHighAccuracy: true, // 开启高精度定位
        success(res) {
          console.log('getLocation', res);
          wx.chooseLocation({
            latitude: res.latitude,
            longitude: res.longitude,
            success: function (data) {
              console.log('chooseLocation', data);
              params.checkAddress = data.address;
              // if (data.address) {
              //   requireObj.checkAddress = '';
              // } else {
              //   requireObj.checkAddress = '此项为必填项';
              // }
              console.log(params);
              that.setData({
                params: params,
                requireObj: requireObj
              });
            },
            fail(err: any) {
              console.log('chooseLocation', err);
            },
            complete: function () {
              that.setData({
                ischangeAddress: false
              });
            }
          });
        },
        fail(err: any) {
          console.log('getLocation', err);
          wx.showToast({
            title: '小程序版本不支持获取定位信息，请检查是否开启定位权限!',
            icon: 'none'
          });
        }
      });
    } else {
      // var _this = this;
      qqmapsdk.search({
        keyword: this.data.params.checkAddress,
        success: function (res: any) {
          console.log('qqmapsdk.search', res);
          if (res.status == 0) {
            //成功后的回调
            console.log(res);
            if (res.data.length == 0) {
              that.changeAddress({
                currentTarget: {
                  dataset: { fieldkey: '1' }
                }
              });
              return;
            }
            // var res = res.result;
            // _this.setData({
            //   signInAddress: res.result.address
            // });
            // _this.getCheckStatus();
            wx.chooseLocation({
              latitude: res.data[0].location.lat,
              longitude: res.data[0].location.lng,
              success: function (data) {
                console.log('chooseLocation', data);
                params.checkAddress = data.address;
                // if (data.address) {
                //   requireObj.checkAddress = '';
                // } else {
                //   requireObj.checkAddress = '此项为必填项';
                // }
                console.log(params);
                that.setData({
                  params: params,
                  requireObj: requireObj
                });
              },
              fail(err: any) {
                console.log('chooseLocation', err);
              },
              complete: function () {
                that.setData({
                  ischangeAddress: false
                });
              }
            });
          } else {
            // 位置信息获取失败
            wx.showToast({
              title: '位置信息获取失败',
              icon: 'none'
            });
          }
        },
        fail(err: any) {
          console.log('getLocation', err);
          wx.showToast({
            title: '小程序版本不支持获取定位信息，请检查是否开启定位权限!',
            icon: 'none'
          });
        }
      });
    }
  },
  getProjectOptions() {
    getAction('api/projects/list').then((res: any) => {
      if (res.code == 200) {
        let arr = [] as any;
        res.result.forEach((item: any, index: number) => {
          arr.push({
            text: item.projectName,
            value: item.id
          });
          if (
            this.data.params.projectId != '' &&
            this.data.params.projectId == item.id
          ) {
            this.setData({
              projectPickerIndex: index
            });

            this.getContractOptions(item.id);
          }
        });
        this.setData({
          projectOptionsList: arr
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  getContractOptions(projectId: string) {
    let params = {
      contractType: 4,
      projectId: projectId
    };
    getAction('api/contract/list', params).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.contractId != '' &&
            this.data.params.contractId == item.id
          ) {
            this.setData({
              contractPickerIndex: index
            });
          }
        });
        if (arr.length == 0) {
          arr.push({
            text: '当前所选项目无合同数据',
            value: ''
          });
        }
        this.setData({
          contractList: 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
            );
            if (i == -1) {
              return;
            }
            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
            );
            if (i == -1) {
              return;
            }
            this.setData({
              vehicleTypeIndex: i
            });
            this.getvehicleCheckTemplate(res.result[i].value);
          }
        } else {
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 交车模板
  getvehicleCheckTemplate(vehicleType: string) {
    let params = {
      name: '',
      vehicleType: vehicleType,
      checkType: 2 //验收模板类型（1采购交车，2租赁交车，3租赁收车）
    };
    getAction('api/vehicleCheckTemplate/list', params).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.templateId != '' &&
            this.data.params.templateId == item.id
          ) {
            this.setData({
              templateIndex: index
            });
            // this.getTemplateProject(item.id);
          }
        });
        if (arr.length == 0) {
          arr.push({
            text: '当前所选车辆种类无交车模板数据',
            value: ''
          });
        }
        this.setData({
          templateOptions: arr
          // templateIndex: -1
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 交车模板项目
  getTemplateProject(templateId: string) {
    let params = {
      templateId: templateId
    };
    getAction('api/vehicleCheckTemplateProject/list', params).then(
      (res: any) => {
        if (res.code == 200) {
          let data: any = { ...this.data };
          data.requireObj.projectList = [];
          res.result.forEach((item: any, index: number) => {
            item.templateProjectId = item.id;
            item.id = '';
            data.requireObj.projectList.push({ checkStatus: '' });
          });
          data.params.projectList = res.result;
          this.setData(data);
          console.log(this.data.params);
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  // 获取维保员
  getByRoleCode() {
    let params = {
      // roleCode: ''
    };
    getAction('api/user/getByRoleCode', params).then((res: any) => {
      if (res.code == 200) {
        // let data: any = { ...this.data };
        // data.params.userList = res.result;
        // this.setData(data);
        // console.log(this.data.params);
        let arr = [] as any;
        res.result.forEach((item: any, index: number) => {
          arr.push({
            text: item.realname,
            value: item.id
          });
          if (
            this.data.params.sentVehicleUserId != '' &&
            this.data.params.sentVehicleUserId == item.id
          ) {
            this.setData({
              sentVehicleUserPickerIndex: index
            });
          }
          if (
            this.data.params.checkUserId != '' &&
            this.data.params.checkUserId == item.id
          ) {
            this.setData({
              checkUserPickerIndex: index
            });
          }
        });
        this.setData({
          userList: arr
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // 获取车辆数据
  getvehicleByproject() {
    if (!this.data.params.projectId || !this.data.params.vehicleType) {
      wx.showToast({
        title: '请先选择项目与车辆种类',
        icon: 'none'
      });
      return;
    }
    let params = {
      projectId: this.data.params.projectId,
      vehicleType: this.data.params.vehicleType,
      pageSize: -1
    };
    getAction('api/vehicle/list', params).then((res: any) => {
      if (res.code == 200) {
        let data: any = { ...this.data };
        let arr = [] as any;
        res.result.records.forEach((item: any) => {
          arr.push({
            vehicleId: item.id,
            // vehicle: item,
            plateNumber: item.plateNumber,
            frameNumber: item.frameNumber,
            vehicleModel: item.vehicleModel,
            vehicleBrand: item.vehicleBrand,
            vehicleBrand_dictText: item.vehicleBrand_dictText,
            vehicleType: item.vehicleType,
            vehicleType_dictText: item.vehicleType_dictText
          });
        });
        data.params.vehicleList = arr;
        this.setData(data);
        wx.showToast({
          title: '车辆信息已重置',
          icon: 'none'
        });
      } 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 == 'projectList') {
      data.params.projectList[fieldindex][fieldkey] = detail.value;
      if (data.params[fieldname][fieldindex][fieldkey]) {
        // delete data.requireObj[fieldname];
        // data.requireObj[fieldname][fieldindex].remark = '';
      } else {
        // data.requireObj[fieldname][fieldindex].remark = this.checkStr(data.params[fieldname][fieldindex][fieldkey]);
      }
    } else if (fieldname == 'vehicleList') {
      data.params[fieldname][fieldindex][fieldkey] = detail.value;
      if (data.params[fieldname][fieldindex][fieldkey]) {
        // delete data.requireObj[fieldname];
        data.requireObj[fieldname][fieldindex][fieldkey] = '';
      } else {
        data.requireObj[fieldname][fieldindex][fieldkey] = '此项为必填项';
      }
    } else if (fieldname == 'remark') {
      data.params[fieldname] = detail.value;
      // if (data.params[fieldname]) {
      //   data.requireObj[fieldname] = this.checkStr(data.params[fieldname]);
      // }
    } else {
      data.params[fieldname] = detail.value;
      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][fieldkey] = '';
    } 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: ''
      });
    } else if (fieldname == 'projectList') {
      data.params[fieldname].push({
        name: '',
        content: '',
        checkStatus: '1',
        remark: ''
      });
    }
    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;
    } else if (fieldname == 'projectList') {
      data.params[fieldname].splice(fieldindex, 1);
    }
    this.setData(data);
    console.log(data);
  },
  radioOnChange(e: any) {
    console.log(e);
    let { fieldname, fieldindex } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    if (fieldname == 'projectList') {
      data.params.projectList[fieldindex].checkStatus = e.detail;
    } else {
      data.params[fieldname] = e.detail;
    }
    if (data.params[fieldname]) {
      // delete data.requireObj[fieldname];
      data.requireObj[fieldname] = '';
    } else {
      data.requireObj[fieldname] = '此项为必填项';
    }
    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
    };
    this.setData({
      uploading: true
    });
    upload('api/vehicleCheck/upload', option).then((res: any) => {
      this.setData({
        uploading: false
      });
      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 = '' as any;
        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 = '' as any;
    otherPhotoFile.forEach((p: any) => {
      urls += p.url + ',';
    });
    urls = urls.slice(0, -1);
    data.params[fieldname] = urls;
    data.params[fieldname + 'List'] = otherPhotoFile;
    this.setData(data);
  },
  checkStr(str: string) {
    let returnStr = '';
    let spaceRegex = /^\S*$/;
    let regex = /[!@#$%^&*?><|\\\\]/;
    let tooLong = str.length > 32;
    if (!spaceRegex.test(str)) {
      returnStr = '不支持含有空格';
    } else if (regex.test(str)) {
      returnStr = '不支持特殊字符';
    } else if (tooLong) {
      returnStr = '输入长度不得超过32个字符';
    } else {
      returnStr = '';
    }
    return returnStr;
  },
  isStepReady() {
    //校验基础信息
    let isAllReady = true;
    let temp: any =
      this.data.tabActive == 0 ? this.data.requireObj : this.data.requireObj1;
    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['vehicleList'][index].vehicleNo = '此项为必填项';
          }
          if (item.frameNumber == '') {
            isAllReady = false;
            temp['vehicleList'][index].frameNumber = '此项为必填项';
          }
        });
      } else if (key == 'projectList') {
        params[key].forEach((item: any, index: number) => {
          if (item.checkStatus == '') {
            isAllReady = false;
            temp['projectList'][index].checkStatus = '此项为必填项';
          }
        });
      } else 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;
        let timeRegex =
          /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1]))$/ as any;
        if (!timeRegex.test(params[key])) {
          isAllReady = false;
          temp[key] = '请填写正确的时间';
        }
        // temp[key] = temp[key] ? temp[key] : '请填写正确的时间';
      } else if (key == 'checkAddress') {
        temp[key] = params[key] ? '' : '此项为必填项';
        if (temp[key]) {
          isAllReady = false;
        }
      } else if (!params[key]) {
        isAllReady = false;
        temp[key] = temp[key] ? temp[key] : '此项为必填项';
      } else {
        temp[key] = this.checkStr(params[key]);
        if (temp[key]) {
          isAllReady = false;
        }
      }
    }
    this.setData({
      requireObj: temp
    });
    console.log(temp, isAllReady);
    return isAllReady;
  },
  formSubmit(e: any) {
    let btnStatus = e.currentTarget.dataset.status;
    if (this.data.uploading) {
      wx.showToast({
        title: '文件上传中，请稍后',
        icon: 'none'
      });
      return;
    }
    if (this.data.loading) {
      wx.showToast({
        title: '信息保存中，请勿重复提交',
        icon: 'none'
      });
      return;
    }
    if (!this.isStepReady()) {
      wx.showToast({
        title: '请填写完整对应信息',
        icon: 'none'
      });
      // 验证是否非空
      return;
    }
    // if (
    //   !this.data.params.vehicleList ||
    //   this.data.params.vehicleList.length == 0
    // ) {
    //   wx.showToast({
    //     title: '无车辆信息，请增加车辆信息',
    //     icon: 'none'
    //   });
    //   return;
    // }
    if (this.data.params.projectList.length > 0) {
      let res = this.data.params.projectList.some((item: any) => {
        return item.content === '' || item.name === '';
      });
      if (res) {
        wx.showToast({
          title: '验收信息中，验收项目与验收内容不能为空',
          icon: 'none'
        });
        return;
      }
    }
    // 验证非必填
    if (this.data.params.remark) {
      let msg = this.checkStr(this.data.params.remark);
      if (msg) {
        wx.showToast({
          title: '验收结论：' + msg,
          icon: 'none'
        });
        return;
      }
    }
    let params = this.data.params;
    params.status = btnStatus; // 状态（0待提交，1已提交）
    wx.showLoading({
      title: '保存中'
    });
    this.setData({
      loading: true
    });
    if (this.data.params.id || this.data.params.parentId) {
      putAction('api/vehicleCheck/edit', params).then((res: any) => {
        wx.hideLoading();
        this.setData({
          loading: false
        });
        if (res.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
          wx.navigateBack({
            delta: 2
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      });
    } else {
      postAction('api/vehicleCheck/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() {
    // 接收传参
    const eventChannel = this.getOpenerEventChannel();

    eventChannel &&
      eventChannel.on &&
      eventChannel.on('eventName', (data: any) => {
        console.log('接收参数', data);
        // 收车编辑数据初始化
        if (data.status == '1' && !data.children) {
          data.children = {
            checkType: '3',
            contractId: data.contractId,
            contractId_dictText: data.contractId_dictText,
            projectId: data.projectId,
            projectId_dictText: data.projectId_dictText,
            vehicleType: data.vehicleType,
            vehicleType_dictText: data.vehicleType_dictText,
            templateId: data.templateId,
            templateId_dictText: data.templateId_dictText,
            status: '0',
            vehicleList: [],
            projectList: [],
            ckeckUrl: '',
            ensureUrl: '',
            otherUrl: '',
            ckeckUrlList: [],
            ensureUrlList: [],
            otherUrlList: []
          };
        }

        data.ckeckUrlList = [];
        data.ensureUrlList = [];
        data.otherUrlList = [];
        if (data.ckeckUrl) {
          for (let i = 0; i < data.ckeckUrl.split(',').length; i++) {
            let pic = data.ckeckUrl.split(',')[i];
            data.ckeckUrlList.push({
              url: pic,
              name: ''
            });
          }
        }
        if (data.ensureUrl) {
          for (let i = 0; i < data.ensureUrl.split(',').length; i++) {
            let pic = data.ensureUrl.split(',')[i];
            data.ensureUrlList.push({
              url: pic,
              name: ''
            });
          }
        }
        if (data.otherUrl) {
          for (let i = 0; i < data.otherUrl.split(',').length; i++) {
            let pic = data.otherUrl.split(',')[i];
            data.otherUrlList.push({
              url: pic,
              name: ''
            });
          }
        }
        // 收车
        if (data.children) {
          data.children.parentId = data.id;
          data.children.projectList = data.projectList;
          data.children.vehicleList = data.vehicleList;
          data.children.ckeckUrlList = [];
          data.children.ensureUrlList = [];
          data.children.otherUrlList = [];
          if (data.children.ckeckUrl) {
            for (let i = 0; i < data.children.ckeckUrl.split(',').length; i++) {
              let pic = data.children.ckeckUrl.split(',')[i];
              data.children.ckeckUrlList.push({
                url: pic,
                name: ''
              });
            }
          }
          if (data.children.ensureUrl) {
            for (
              let i = 0;
              i < data.children.ensureUrl.split(',').length;
              i++
            ) {
              let pic = data.children.ensureUrl.split(',')[i];
              data.children.ensureUrlList.push({
                url: pic,
                name: ''
              });
            }
          }
          if (data.children.otherUrl) {
            for (let i = 0; i < data.children.otherUrl.split(',').length; i++) {
              let pic = data.children.otherUrl.split(',')[i];
              data.children.otherUrlList.push({
                url: pic,
                name: ''
              });
            }
          }
        }
        // if (data.vehicleList) {
        //   for (let i = 0; i < data.vehicleList.length; i++) {
        //     this.data.requireObj.vehicleList.push({
        //       vehicleNo: '',
        //       frameNumber: ''
        //     });
        //   }
        // }
        if (data.projectList) {
          for (let i = 0; i < data.projectList.length; i++) {
            this.data.requireObj.projectList.push({
              checkStatus: ''
            });
          }
        }
        this.setData({
          defaultData: data,
          tabActive: data.tabActive,
          params: data.tabActive == '0' ? data : data.children,
          checkTimeTamp:
            data.tabActive == '0'
              ? new Date(data.checkTime).getTime()
              : new Date(data.children.checkTime).getTime(),
          registrationTimeTamp:
            data.tabActive == '0'
              ? new Date(data.checkTime).getTime()
              : new Date(data.children.checkTime).getTime()
        });
        this.getProjectOptions();
        // this.getDictOptions('contract_type');
        this.getDictOptions('vehicle_type');
        this.getByRoleCode();
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // this.getProjectOptions()
    // this.getDictOptions('contract_type')
    // this.getDictOptions('vehicle_type')
    if (this.data.userList.length == 0) {
      this.getByRoleCode();
    }
  },

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

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

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

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

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

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