import { getAction, upload, postAction } from '../../api/base';

// pages/accidentReporting/accidentReporting.ts
const dayjs = require('dayjs');
const isSpecialChar: RegExp = /[\"'{};<>!@#$%^&*|\\\\]/; //特殊字符校验
const plateNumberExp: RegExp =
  /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
const phoneNumberExp: RegExp = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/; //手机号码验证
const moneyNumberExp: RegExp = /^\d{1,9}(\.\d{1,2})?$/; //金额限制整数部分不能大于9位 小数部分不能大于2位
// const driverLicenseNumberExp: RegExp = /^[1-6]\d{15}$/; //驾驶证格式验证
// const driverLicenseNumberExp: RegExp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
Page({
  /**
   * 页面的初始数据
   */
  data: {
    step: 1, //步骤
    busList: [],
    accidentTimestamp: new Date().getTime(),
    insuranceDateTimestamp: new Date().getTime(),
    claimToCompanyAccountDateTimestamp: new Date().getTime(),
    claimToThirdAccountDateTimestamp: new Date().getTime(),
    closingTimestamp: new Date().getTime(),
    insuranceCompanyList: [], // 保险公司信息
    companyText: '', // 保险公司名
    isRecord: false, // 是否出险 用于判断是否必填
    formatter(type: any, value: any) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    // 基础信息校验提示
    tips: {
      //必填及错误提示
      plateNumber: '',
      projectId: '',
      processedPerson: '',
      reportNumber: '',
      accidentTime: '',
      // driver: '',
      // driverLicenseNumber: '',
      // driverPhoneNumber: '',
      accidentLocation: '',
      accidentDetails: '',
      accidentEstimatedLoss: '',
      accidentScenePhoto: '',
      insuranceInvestigationReport: ''
    },
    // 保险信息校验提示
    insureTips: {
      caseReceiptNumber: '', // 保险单号
      companyId: '', // 保险公司
      insuranceDate: '', // 出险日期
      liabilityConfirm: '', // 确认事故责任
      natureConfirm: '', // 确认事故性质
      vehicleLossAmount: '', // 标的车损失金额
      thirdPropertyDamageAmount: '', // 第三方物损金额
      vehiclePersonalInjuryAmount: '', // 标的车人伤金额
      thirdPersonalInjuryAmount: '', // 第三方人伤金额
      claimToCompanyAccountDate: '', // 理赔至公司账户日期
      claimToThirdAccountDate: '', // 理赔至第三方账户日期
      claimToCompanyAccountAmount: '', // 理赔至公司账户金额
      claimToThirdAccountAmount: '', // 理赔至第三方账户金额
      uncompensatedAmount: '' // 出险未理赔金额
    },
    // 基础信息
    submitParam: {
      plateNumber: '',
      projectId: '',
      projectId_dictText: '',
      processedPerson: '',
      reportNumber: '',
      accidentTime: '',
      driver: '',
      driverLicenseNumber: '',
      driverPhoneNumber: '',
      accidentLocation: '',
      accidentDetails: '',
      accidentEstimatedLoss: '',
      replacedParts: '',
      thirdPlateNumber: '',
      thirdInsuranceCompany: '',
      thirdPhoneNumber: '',
      accidentForm: '1',
      accidentType: '1',
      accidentInjuryType: '0',
      liabilityEstimate: '99',
      natureEstimate: '1',
      accidentScenePhoto: '',
      accidentSceneVideo: '',
      insuranceInvestigationReport: '',
      accidentLossTypeList: ''
    },
    //保险信息
    insureParam: {
      caseReceiptNumber: '',
      isRecord: '0',
      companyId: '',
      insuranceDate: '',
      liabilityConfirm: '',
      natureConfirm: '',
      vehicleLossAmount: '',
      thirdPropertyDamageAmount: '',
      vehiclePersonalInjuryAmount: '',
      thirdPersonalInjuryAmount: '',
      estimatedTotalLossAmount: '',
      claimToCompanyAccountDate: '',
      claimToThirdAccountDate: '',
      claimToCompanyAccountAmount: '',
      claimToThirdAccountAmount: '',
      documentImage: '',
      totalCompensationAmount: '',
      uncompensatedAmount: '',
      totalAmountActuallyIncurred: ''
    },
    //案件进度
    caseParam: {
      caseClosed: '',
      closingTime: '',
      remarks: '',
      accidentCertificatePhoto: '',
      compensationAgreementPhoto: '',
      lossAssessmentPhoto: '',
      otherPhoto: ''
    },
    accidentFormList: [], //事故发生类型
    accidentTypeList: [], //事故类型
    accidentInjuryTypeList: [], //伤亡类型
    liabilityEstimateList: [], //初步预估责任
    natureEstimateList: [], //初步预估性质
    accidentLossTypeList: [], //事故损失

    liabilityTypeList: [], //确认事故责任
    natureTypeList: [], //确认事故责任
    yesNoList: [], //是否结案

    plateNumberShow: false,
    accidentTimeShow: false,
    accidentFormShow: false,
    accidentTypeShow: false,
    accidentInjuryTypeShow: false,
    liabilityEstimateShow: false,
    natureEstimateShow: false,
    liabilityConfirmShow: false,
    insuranceDateShow: false,
    companyShow: false,
    natureConfirmShow: false,
    claimToCompanyAccountDateShow: false,
    claimToThirdAccountDateShow: false,
    caseClosedShow: false,
    closingTimeShow: false,

    accidentFormText: '',
    accidentTypeText: '',
    accidentInjuryTypeText: '',
    liabilityEstimateText: '',
    natureEstimateText: '',
    liabilityConfirmText: '',
    accidentSceneFile: [],
    accidentSceneVideo: [],
    insuranceInvestigationReportFile: [],
    documentImageFile: [], //理赔单据
    accidentCertificatePhotoFile: [],
    compensationAgreementPhotoFile: [],
    lossAssessmentPhotoFile: [],
    otherPhotoFile: [],

    busInfoExpand: true,
    accidentInfoExpand: true,
    lossAccessmentExpand: true,
    lossSituationExpand: true,
    settleAClaimExpand: true,
    accountOfMoneyExpand: true,
    plateNumberSearchVal: '',
    accidentLocationTextfocus: false,
    accidentDetailsTextfocus: false,
    accidentEstimatedLossTextfocus: false,
    validate: {
      driverPhoneNumber: '',
      thirdPlateNumber: '',
      thirdPhoneNumber: '',

      vehicleLossAmount: '',
      thirdPropertyDamageAmount: '',
      vehiclePersonalInjuryAmount: '',
      thirdPersonalInjuryAmount: '',

      claimToCompanyAccountAmount: '',
      claimToThirdAccountAmount: '',
      uncompensatedAmount: '',
      caseReceiptNumber: '',
      remarks: ''
    }
  },
  handleExpand(event: any) {
    let type = event.currentTarget.dataset.type;
    let data: any = this.data;
    data[type] = !data[type];
    this.setData(data);
  },
  isStepReady() {
    console.log(this.data.step);

    //校验基础信息
    let isAllReady = true;
    let temp: any = this.data.tips;
    let temp2: any = this.data.insureTips;
    let validate: any = this.data.validate;
    for (let key in temp) {
      if (!temp[key] || temp[key].indexOf('此项为必填项') != -1) {
        isAllReady = false;
        temp[key] = temp[key] ? temp[key] : '此项为必填项';
      } else {
        temp[key] = temp[key];
      }
    }
    // 校验保险信息
    if (this.data.step == 2 && this.data.isRecord) {
      for (let key in temp2) {
        if (!temp2[key] || temp2[key].indexOf('此项为必填项') != -1) {
          isAllReady = false;
          temp2[key] = temp2[key] ? temp2[key] : '此项为必填项';
        } else {
          temp2[key] = temp2[key];
        }
      }
    }
    for (let key in validate) {
      if (validate[key]) {
        isAllReady = false;
      }
    }
    this.setData({
      tips: temp,
      insureTips: temp2
    });
    return isAllReady;
  },
  changeStep(event: any) {
    //换步骤
    if (!this.isStepReady()) {
      //含有必填项未填
      return;
    }
    let index = event.currentTarget.dataset.index;
    this.setData({
      step: index + 1
    });
  },
  toNextStep() {
    //下一步
    if (!this.isStepReady()) {
      //含有必填项未填
      return;
    }
    let step: number = this.data.step;
    this.setData({
      step: step + 1
    });
  },
  formSubmit() {
    if (!this.isStepReady()) {
      //含有必填项未填
      return;
    }
    // 校验是否有错误文件
    if (!this.checkFile()) {
      wx.showToast({
        title: '请删除错误文件',
        icon: 'none'
      });
      return;
    }
    let {
      caseParam: cParam,
      step: step,
      documentImageFile: fileArr
    } = { ...this.data };
    let aParam: any = this.data.submitParam;
    let bParam: any = this.data.insureParam;
    let arr: any = [];
    this.data.accidentLossTypeList.map((item: any) => {
      //事故损失类型选中项
      if (item.isSelect) {
        arr.push(item.value);
      }
    });
    aParam.accidentLossTypeList = arr;
    let params: any = {
      ...aParam,
      accidentInsuranceInfo: { isRecord: '0' }, // 是否出险默认为否
      accidentProgress: {}
    };
    for (let index in aParam) {
      console.log(isSpecialChar.test(aParam[index]));
    }
    if (step == 2) {
      bParam.vehicleLossAmount = Number(bParam.vehicleLossAmount);
      bParam.thirdPropertyDamageAmount = Number(
        bParam.thirdPropertyDamageAmount
      );
      bParam.vehiclePersonalInjuryAmount = Number(
        bParam.vehiclePersonalInjuryAmount
      );
      bParam.thirdPersonalInjuryAmount = Number(
        bParam.thirdPersonalInjuryAmount
      );
      bParam.estimatedTotalLossAmount = Number(bParam.estimatedTotalLossAmount);
      bParam.claimToCompanyAccountAmount = Number(
        bParam.claimToCompanyAccountAmount
      );
      bParam.claimToThirdAccountAmount = Number(
        bParam.claimToThirdAccountAmount
      );
      bParam.totalCompensationAmount = Number(bParam.totalCompensationAmount);
      bParam.uncompensatedAmount = Number(bParam.uncompensatedAmount);
      params.accidentInsuranceInfo = { ...bParam };
    } else if (step == 3) {
      params.accidentInsuranceInfo = { ...bParam };
      params.accidentProgress = { ...cParam };
    }
    if (step != 1 && fileArr.length > 0) {
      let arr: any = [];
      fileArr.map((item: any) => {
        arr.push(item.url);
      });
      params.accidentInsuranceInfo.documentImage = arr.join(',');
    }
    postAction('api/vehicles/accidentInfo/add', params).then((res: any) => {
      if (res.code == 200) {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/maintenanceIndex/maintenanceIndex'
          });
        }, 1000);
      }
    });
  },
  // 校验文件
  checkFile() {
    let accidentSceneVideo: any = this.data.accidentSceneVideo;
    let result = true;
    if (
      accidentSceneVideo.some((item: any) => {
        return item.status == 'failed';
      })
    )
      result = false;
    return result;
  },
  pickerChange(event: any) {
    //下拉弹出窗修改
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    data[fieldName] = true;
    this.setData(data);
  },
  hidePicker() {
    this.setData({
      plateNumberShow: false,
      accidentFormShow: false,
      accidentTypeShow: false,
      accidentInjuryTypeShow: false,
      liabilityEstimateShow: false,
      natureEstimateShow: false,
      accidentTimeShow: false,
      natureConfirmShow: false,
      liabilityConfirmShow: false,
      insuranceDateShow: false,
      companyShow: false,
      claimToCompanyAccountDateShow: false,
      claimToThirdAccountDateShow: false,
      caseClosedShow: false,
      closingTimeShow: false
    });
  },
  numberplateSelect(event: any) {
    let item: any = event.detail.value;
    let tips: any = this.data.tips;
    delete tips.plateNumber;
    delete tips.projectId;
    this.setData({
      plateNumberShow: false,
      [`submitParam.plateNumber`]: item.text,
      [`submitParam.projectId_dictText`]: item.projectId_dictText,
      [`submitParam.projectId`]: item.projectId,
      tips
    });
  },
  accidentFormConfirm(event: any) {
    let item: any = event.detail.value;
    this.setData({
      accidentFormText: item.text,
      [`submitParam.accidentForm`]: item.value
    });
    this.hidePicker();
  },
  accidentTypeConfirm(event: any) {
    let item: any = event.detail.value;
    this.setData({
      accidentTypeText: item.text,
      [`submitParam.accidentType`]: item.value
    });
    this.hidePicker();
  },
  accidentInjuryTypeConfirm(event: any) {
    let item: any = event.detail.value;
    this.setData({
      accidentInjuryTypeText: item.text,
      [`submitParam.accidentInjuryType`]: item.value
    });
    this.hidePicker();
  },
  liabilityEstimateConfirm(event: any) {
    let item: any = event.detail.value;
    this.setData({
      liabilityEstimateText: item.text,
      [`submitParam.liabilityEstimate`]: item.value
    });
    this.hidePicker();
  },
  natureEstimateConfirm(event: any) {
    let item: any = event.detail.value;
    this.setData({
      natureEstimateText: item.text,
      [`submitParam.natureEstimate`]: item.value
    });
    this.hidePicker();
  },

  confirmAccidentTime(event: any) {
    let tips: any = this.data.tips;
    delete tips.accidentTime;
    this.setData({
      accidentTimeShow: false,
      [`submitParam.accidentTime`]: dayjs(event.detail).format('YYYY-MM-DD'),
      accidentTimestamp: event.detail,
      tips
    });
  },
  changeAccidentLossType(event: any) {
    //事故损失
    let { item, index } = event.currentTarget.dataset;
    item.isSelect = !item.isSelect;
    this.setData({
      [`accidentLossTypeList[${index}`]: item
    });
  },
  // 确认是否出险
  isRecordChange(event: any) {
    this.setData({
      [`insureParam.isRecord`]: event.detail,
      isRecord: event.detail === '0' ? false : true
    });
  },
  // 确认保险公司
  confirmCompany(event: any) {
    let insureTips: any = this.data.insureTips;
    delete insureTips.companyId;
    this.setData({
      [`insureParam.companyId`]: event.detail.value.value,
      companyText: event.detail.value.text,
      insureTips
    });
    this.hidePicker();
  },
  // 确认出险日期
  confirmInsuranceDate(event: any) {
    let insureTips: any = this.data.insureTips;
    delete insureTips.insuranceDate;
    this.setData({
      [`insureParam.insuranceDate`]: dayjs(event.detail).format('YYYY-MM-DD'),
      insuranceDateTimestamp: event.detail,
      insureTips
    });
    this.hidePicker();
  },
  liabilityPickerConfirm(event: any) {
    let insureTips: any = this.data.insureTips;
    delete insureTips.liabilityConfirm;
    //确认事故责任
    let item: any = event.detail.value;
    this.setData({
      liabilityConfirmText: item.text,
      [`insureParam.liabilityConfirm`]: item.value,
      insureTips
    });
    this.hidePicker();
  },
  natureConfirmPickerChange(event: any) {
    let insureTips: any = this.data.insureTips;
    delete insureTips.natureConfirm;
    //确认事故性质
    let item: any = event.detail.value;
    this.setData({
      natureConfirmText: item.text,
      [`insureParam.natureConfirm`]: item.value,
      insureTips
    });
    this.hidePicker();
  },
  claimToCompanyAccountDateChange(event: any) {
    let insureTips: any = this.data.insureTips;
    delete insureTips.claimToCompanyAccountDate;
    this.setData({
      [`insureParam.claimToCompanyAccountDate`]: dayjs(event.detail).format(
        'YYYY-MM-DD'
      ),
      claimToCompanyAccountDateTimestamp: event.detail,
      insureTips
    });
    this.hidePicker();
  },
  claimToThirdAccountDateChange(event: any) {
    let insureTips: any = this.data.insureTips;
    delete insureTips.claimToThirdAccountDate;
    this.setData({
      [`insureParam.claimToThirdAccountDate`]: dayjs(event.detail).format(
        'YYYY-MM-DD'
      ),
      claimToThirdAccountDateTimestamp: event.detail,
      insureTips
    });
    this.hidePicker();
  },
  getListByProjectId(event: any) {
    // 获取车辆列表
    getAction('api/vehicle/list', {
      pageSize: -1,
      plateNumber: event ? event.detail : ''
    }).then((res: any) => {
      let list: any = res.result.records;
      let arr: any = [];
      list.map((item: any) => {
        let obj: any = {
          text: item.plateNumber,
          projectId: item.projectId,
          projectId_dictText: item.projectId_dictText,
          id: item.id
        };
        arr.push(obj);
      });
      this.setData({
        busList: arr,
        plateNumberSearchVal: event ? event.detail : ''
      });
    });
  },
  getDict() {
    getAction('api/sys/dict/queryAllDictItems').then((res: any) => {
      let result: any = res.result;
      let {
        accidentForm,
        accidentType,
        accidentInjuryType,
        liabilityEstimate,
        natureEstimate
      } = this.data.submitParam;
      let accidentFormText = result.accident_form.filter(
        (x: any) => x.value === accidentForm
      )[0].text;
      let accidentTypeText = result.accident_type.filter(
        (x: any) => x.value === accidentType
      )[0].text;
      let accidentInjuryTypeText = result.accident_injury_type.filter(
        (x: any) => x.value === accidentInjuryType
      )[0].text;
      let liabilityEstimateText = result.liability_type.filter(
        (x: any) => x.value === liabilityEstimate
      )[0].text;
      let natureEstimateText = result.nature_type.filter(
        (x: any) => x.value === natureEstimate
      )[0].text;
      this.setData({
        accidentFormList: result.accident_form,
        accidentTypeList: result.accident_type,
        accidentInjuryTypeList: result.accident_injury_type,
        liabilityEstimateList: result.liability_type,
        natureEstimateList: result.nature_type,
        accidentLossTypeList: result.accident_loss_type,
        liabilityTypeList: result.liability_type,
        natureTypeList: result.nature_type,
        yesNoList: result.yes_no,
        accidentFormText,
        accidentTypeText,
        accidentInjuryTypeText,
        liabilityEstimateText,
        natureEstimateText
      });
    });
  },
  inputBlur(e: any) {
    let fieldName: any = e.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    // data.submitParam[fieldName] = e.detail.value;
    let value: any = e.detail.value * 1;
    if (e.detail.value) {
      if (fieldName === 'thirdPlateNumber') {
        if (!plateNumberExp.test(e.detail.value)) {
          //第三方车牌号
          data.validate[fieldName] = '车牌号码格式不正确';
        } else {
          data.validate[fieldName] = '';
        }
      }
      if (
        fieldName === 'thirdInsuranceCompany' ||
        fieldName === 'replacedParts'
      ) {
        //第三方保险公司 -- 需要更换配件
        if (isSpecialChar.test(e.detail.value)) {
          data.validate[fieldName] = '内容含有特殊字符';
        } else {
          data.validate[fieldName] = '';
        }
      }
      if (fieldName === 'thirdPhoneNumber') {
        if (!phoneNumberExp.test(e.detail.value)) {
          //第三方保险电话
          data.validate[fieldName] = '电话号码格式不正确';
        } else {
          data.validate[fieldName] = '';
        }
      }
    }
    if (
      fieldName === 'vehicleLossAmount' ||
      fieldName === 'thirdPropertyDamageAmount' ||
      fieldName === 'vehiclePersonalInjuryAmount' ||
      fieldName === 'thirdPersonalInjuryAmount' ||
      fieldName === 'claimToCompanyAccountAmount' ||
      fieldName === 'claimToThirdAccountAmount' ||
      fieldName === 'uncompensatedAmount'
    ) {
      if (data.insureParam[fieldName]) {
        if (!moneyNumberExp.test(value)) {
          data.validate[fieldName] = '金额整数部分为9位，小数部分为2位';
        } else {
          data.validate[fieldName] = '';
          delete data.validate[fieldName];
        }
      } else {
        data.validate[fieldName] = '';
        delete data.validate[fieldName];
      }
    }
    this.setData(data);
  },
  handleFieldChange(e: any) {
    //基础信息input填写
    let fieldName: any = e.currentTarget.dataset.fieldname;
    let data: any = { ...this.data };
    data.submitParam[fieldName] = e.detail.value;
    if (!data.submitParam[fieldName]) {
      data.tips[fieldName] = '此项为必填项';
      if (
        fieldName === 'thirdPlateNumber' ||
        fieldName === 'thirdPhoneNumber' ||
        fieldName === 'thirdInsuranceCompany' ||
        fieldName === 'replacedParts' ||
        fieldName === 'driverPhoneNumber' ||
        fieldName === 'driverLicenseNumber' ||
        fieldName === 'driver'
      ) {
        data.validate[fieldName] = '';
        delete data.validate[fieldName];
        data.tips[fieldName] = '';
        delete data.tips[fieldName];
      }
    } else {
      if (isSpecialChar.test(data.submitParam[fieldName])) {
        data.tips[fieldName] = '内容含有特殊字符';
      } else if (
        fieldName === 'driverPhoneNumber' &&
        !phoneNumberExp.test(e.detail.value)
      ) {
        data.validate[fieldName] = '电话号码格式不正确';
      }
      // else if (
      //   fieldName === 'driverLicenseNumber' &&
      //   !driverLicenseNumberExp.test(e.detail.value)
      // ) {
      //   data.tips[fieldName] = '驾驶证号格式不正确';
      // }
      else {
        data.tips[fieldName] = '';
        delete data.tips[fieldName];
      }
    }
    this.setData(data);
    this.inputBlur(e);
  },
  accidentSceneAfterRead(event: any) {
    //事故现场图片
    const file = event.detail;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let accidentSceneFile: any = this.data.accidentSceneFile;
    accidentSceneFile = [
      {
        status: 'uploading',
        message: '上传中'
      }
    ];
    this.setData({ accidentSceneFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        accidentSceneFile[0] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ accidentSceneFile });
        return;
      }
      if (tempData.result) {
        accidentSceneFile[0] = {
          ...file,
          url: tempData.result.fileUrl,
          status: 'done',
          message: '上传完成'
        };
        let tips: any = this.data.tips;
        delete tips.accidentScenePhoto;
        this.setData({
          accidentSceneFile,
          [`submitParam.accidentScenePhoto`]: tempData.result.fileUrl,
          tips
        });
      }
    });
  },
  accidentVideoAfterRead(event: any) {
    //事故现场视频
    const file = event.detail;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let accidentSceneVideo: any = this.data.accidentSceneVideo;
    accidentSceneVideo.push([
      {
        status: 'uploading',
        message: '上传中'
      }
    ]);
    this.setData({ accidentSceneVideo });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/uploadVideo', option)
      .then((res: any) => {
        wx.hideLoading();
        let tempData = JSON.parse(res.data);
        if (!tempData.success) {
          wx.showToast({
            title: tempData.message,
            icon: 'none'
          });
          accidentSceneVideo[accidentSceneVideo.length - 1] = {
            status: 'failed',
            message: '上传失败'
          };
          this.setData({ accidentSceneVideo });
          return;
        }
        if (tempData.result) {
          accidentSceneVideo[accidentSceneVideo.length - 1] = {
            ...file,
            url: tempData.result.fileUrl,
            status: 'done',
            message: '上传完成'
          };
          let submitParam: any = this.data.submitParam;
          if (submitParam.accidentSceneVideo)
            submitParam.accidentSceneVideo =
              submitParam.accidentSceneVideo + ',' + tempData.result.fileUrl;
          else submitParam.accidentSceneVideo = tempData.result.fileUrl;
          this.setData({
            accidentSceneVideo,
            [`submitParam.accidentSceneVideo`]: submitParam.accidentSceneVideo
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        accidentSceneVideo[accidentSceneVideo.length - 1] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ accidentSceneVideo });
      });
  },
  deleteAccidentSceneFile(event: any) {
    let accidentSceneFile = this.data.accidentSceneFile;
    let index = event.detail.index;
    accidentSceneFile.splice(index, 1);
    this.setData({
      accidentSceneFile,
      [`submitParam.accidentScenePhoto`]: '',
      [`tips.accidentScenePhoto`]: '请上传事故现场图片'
    });
  },
  deleteAccidentSceneVideo(event: any) {
    let accidentSceneVideo: any = this.data.accidentSceneVideo;
    let index = event.detail.index;
    let submitParam: any = this.data.submitParam;
    submitParam.accidentSceneVideo = submitParam.accidentSceneVideo.split(',');
    // 如果不是错误文件，才能删除
    if (accidentSceneVideo[index].status == 'done') {
      submitParam.accidentSceneVideo.splice(index, 1);
    }
    accidentSceneVideo.splice(index, 1);
    this.setData({
      accidentSceneVideo,
      [`submitParam.accidentSceneVideo`]:
        submitParam.accidentSceneVideo.join(',')
    });
  },
  insuranceInvestigationReportAfterRead(event: any) {
    //保险公司现场勘察报告
    const file = event.detail;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let insuranceInvestigationReportFile: any = [
      {
        status: 'uploading',
        message: '上传中'
      }
    ];
    this.setData({ insuranceInvestigationReportFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        insuranceInvestigationReportFile[0] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ insuranceInvestigationReportFile });
        return;
      }
      insuranceInvestigationReportFile[0] = {
        ...file,
        url: tempData.result.fileUrl,
        status: 'done',
        message: '上传完成'
      };
      let tips: any = this.data.tips;
      delete tips.insuranceInvestigationReport;
      this.setData({
        insuranceInvestigationReportFile,
        [`submitParam.insuranceInvestigationReport`]: tempData.result.fileUrl,
        tips
      });
    });
  },
  deleteInsuranceInvestigationReportFile(event: any) {
    let file = this.data.insuranceInvestigationReportFile;
    let index = event.detail.index;
    file.splice(index, 1);
    this.setData({
      insuranceInvestigationReportFile: file,
      insuranceInvestigationReport: '',
      [`tips.insuranceInvestigationReport`]: '请上传保险公司现场勘察报告'
    });
  },
  documentImageAfterRead(event: any) {
    console.log(event);
    //理赔单据
    const file = event.detail;
    let uploadIdx: any = event.detail.index;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let documentImageFile: any = this.data.documentImageFile;
    documentImageFile[uploadIdx] = {
      status: 'uploading',
      message: '上传中'
    };
    this.setData({ documentImageFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        documentImageFile[uploadIdx] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ documentImageFile });
        return;
      }
      documentImageFile[uploadIdx] = {
        ...file,
        url: tempData.result.fileUrl,
        status: 'done',
        message: '上传完成'
      };
      this.setData({
        documentImageFile
      });
    });
  },
  deleteDocumentImage(event: any) {
    let file = this.data.documentImageFile;
    let index = event.detail.index;
    file.splice(index, 1);
    this.setData({
      documentImageFile: file
    });
  },
  // 保险填报
  // 预估损失总金额(元)：等于标的车损失金额(元) + 标的车人伤金额(元) + 第三方物损金额(元) + 第三方人伤金额(元)
  // 出险理赔总金额=理赔至公司账户金额之和+理赔至第三方账户金额之和
  // 案件实际发生总金额=出险理赔总金额+出险未理赔金额
  handleCountNum() {
    let {
      vehicleLossAmount: a,
      thirdPropertyDamageAmount: b,
      vehiclePersonalInjuryAmount: c,
      thirdPersonalInjuryAmount: d,
      claimToCompanyAccountAmount: e,
      claimToThirdAccountAmount: f,
      uncompensatedAmount: h
    } = this.data.insureParam;
    this.setData({
      [`insureParam.estimatedTotalLossAmount`]: !isNaN(
        Number(a) + Number(b) + Number(c) + Number(d)
      )
        ? (Number(a) + Number(b) + Number(c) + Number(d)).toFixed(2)
        : '',
      [`insureParam.totalCompensationAmount`]: !isNaN(Number(e) + Number(f))
        ? (Number(e) + Number(f)).toFixed(2)
        : '',
      [`insureParam.totalAmountActuallyIncurred`]: !isNaN(
        Number(e) + Number(f) + Number(h)
      )
        ? (Number(e) + Number(f) + Number(h)).toFixed(2)
        : ''
    });
  },
  inputChange(event: any) {
    let fieldName: any = event.currentTarget.dataset.fieldname;
    let data: any = this.data;
    if (fieldName === 'remarks') {
      data.caseParam[fieldName] = event.detail.value;
      if (event.detail.value) {
        if (isSpecialChar.test(event.detail.value)) {
          data.validate.remarks = '内容含有特殊字符';
        } else {
          data.validate.remarks = '';
          delete data.validate.remarks;
        }
      } else {
        data.validate.remarks = '';
        delete data.validate.remarks;
      }
      this.setData(data);
      return;
    } else {
      data.insureParam[fieldName] = event.detail.value;
      // 是出险，需要必填
      if (this.data.isRecord) {
        if (!data.insureParam[fieldName]) {
          data.insureTips[fieldName] = '此项为必填项';
        } else {
          data.insureTips[fieldName] = '';
          delete data.insureTips[fieldName];
        }
      } else {
        data.insureTips[fieldName] = '';
        delete data.insureTips[fieldName];
      }
      if (fieldName === 'caseReceiptNumber') {
        if (event.detail.value) {
          if (isSpecialChar.test(event.detail.value)) {
            data.validate.caseReceiptNumber = '内容含有特殊字符';
          } else {
            data.validate.caseReceiptNumber = '';
            delete data.validate.caseReceiptNumber;
          }
        } else {
          data.validate.caseReceiptNumber = '';
          delete data.validate.caseReceiptNumber;
        }
      }
    }
    this.inputBlur(event);
    this.setData(data);
    this.handleCountNum();
  },
  yesNoListConfirm(event: any) {
    let item: any = event.detail.value;
    this.setData({
      caseClosedText: item.text,
      [`caseParam.caseClosed`]: item.value
    });
    this.hidePicker();
  },
  closingTimeChange(event: any) {
    this.setData({
      closingTimestamp: event.detail,
      [`caseParam.closingTime`]: dayjs(event.detail).format('YYYY-MM-DD')
    });
    this.hidePicker();
  },
  accidentCertificatePhotoAfterRead(event: any) {
    const file = event.detail;
    let index: any = event.detail.index;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let accidentCertificatePhotoFile: any =
      this.data.accidentCertificatePhotoFile;
    accidentCertificatePhotoFile[index] = {
      status: 'uploading',
      message: '上传中'
    };
    this.setData({ accidentCertificatePhotoFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        accidentCertificatePhotoFile[index] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ accidentCertificatePhotoFile });
        return;
      }
      accidentCertificatePhotoFile[index] = {
        ...file,
        url: tempData.result.fileUrl,
        status: 'done',
        message: '上传完成'
      };
      this.setData({
        accidentCertificatePhotoFile,
        [`caseParam.accidentCertificatePhoto`]: tempData.result.fileUrl
      });
    });
  },
  deleteAccidentCertificatePhoto(event: any) {
    let accidentCertificatePhotoFile = this.data.accidentCertificatePhotoFile;
    let index = event.detail.index;
    accidentCertificatePhotoFile.splice(index, 1);
    this.setData({
      accidentCertificatePhotoFile,
      [`caseParam.accidentCertificatePhoto`]: ''
    });
  },
  compensationAgreementPhotoAfterRead(event: any) {
    const file = event.detail;
    let index: any = event.detail.index;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let compensationAgreementPhotoFile: any =
      this.data.compensationAgreementPhotoFile;
    compensationAgreementPhotoFile[index] = {
      status: 'uploading',
      message: '上传中'
    };
    this.setData({ compensationAgreementPhotoFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        compensationAgreementPhotoFile[index] = {
          status: 'uploading',
          message: '上传失败'
        };
        this.setData({ compensationAgreementPhotoFile });
        return;
      }
      compensationAgreementPhotoFile[index] = {
        ...file,
        url: tempData.result.fileUrl,
        status: 'done',
        message: '上传完成'
      };
      this.setData({
        compensationAgreementPhotoFile,
        [`caseParam.compensationAgreementPhoto`]: tempData.result.fileUrl
      });
    });
  },
  deleteCompensationAgreementPhoto(event: any) {
    let compensationAgreementPhotoFile =
      this.data.compensationAgreementPhotoFile;
    let index = event.detail.index;
    compensationAgreementPhotoFile.splice(index, 1);
    this.setData({
      compensationAgreementPhotoFile,
      [`caseParam.compensationAgreementPhoto`]: ''
    });
  },
  lossAssessmentPhotoAfterRead(event: any) {
    const file = event.detail;
    let index: any = event.detail.index;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let lossAssessmentPhotoFile: any = this.data.lossAssessmentPhotoFile;
    lossAssessmentPhotoFile[index] = {
      status: 'uploading',
      message: '上传中'
    };
    this.setData({ lossAssessmentPhotoFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        lossAssessmentPhotoFile[index] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ lossAssessmentPhotoFile });
        return;
      }
      lossAssessmentPhotoFile[index] = {
        ...file,
        url: tempData.result.fileUrl,
        status: 'done',
        message: '上传完成'
      };
      this.setData({
        lossAssessmentPhotoFile,
        [`caseParam.lossAssessmentPhoto`]: tempData.result.fileUrl
      });
    });
  },
  deleteLossAssessmentPhoto(event: any) {
    let lossAssessmentPhotoFile = this.data.lossAssessmentPhotoFile;
    let index = event.detail.index;
    lossAssessmentPhotoFile.splice(index, 1);
    this.setData({
      lossAssessmentPhotoFile,
      [`caseParam.lossAssessmentPhoto`]: ''
    });
  },
  otherPhotoAfterRead(event: any) {
    const file = event.detail;
    let index = event.detail.index;
    let option = {
      name: 'file',
      filePath: event.detail.file.url
    };
    let otherPhotoFile: any = this.data.otherPhotoFile;
    otherPhotoFile[index] = {
      status: 'uploading',
      message: '上传中'
    };
    this.setData({ otherPhotoFile });
    wx.showLoading({
      title: '上传中',
      mask: true
    });
    upload('api/vehicles/accidentInfo/upload', option).then((res: any) => {
      wx.hideLoading();
      let tempData = JSON.parse(res.data);
      if (!tempData.success) {
        wx.showToast({
          title: tempData.message,
          icon: 'none'
        });
        otherPhotoFile[index] = {
          status: 'failed',
          message: '上传失败'
        };
        this.setData({ otherPhotoFile });
        return;
      }
      otherPhotoFile[index] = {
        ...file,
        url: tempData.result.fileUrl,
        status: 'done',
        message: '上传完成'
      };
      this.setData({
        otherPhotoFile,
        [`caseParam.otherPhoto`]: tempData.result.fileUrl
      });
    });
  },
  deleteOtherPhoto(event: any) {
    let otherPhotoFile = this.data.otherPhotoFile;
    let index = event.detail.index;
    otherPhotoFile.splice(index, 1);
    this.setData({
      otherPhotoFile,
      [`caseParam.otherPhoto`]: ''
    });
  },
  // 获取保险公司
  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
            });
          });
          this.setData({
            insuranceCompanyList: arr
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }
    );
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getListByProjectId(null);
    this.getDict();
    let tips: any = this.data.tips;
    if (wx.getStorageSync('userInfo').realname) {
      delete tips.processedPerson;
    }
    this.setData({
      [`submitParam.processedPerson`]: wx.getStorageSync('userInfo').realname,
      tips
    });
    this.getInsuranceCompanyOptions();
  },
  textAreaFocus(event: any) {
    let fieldname: any = event.currentTarget.dataset.focus_field_name;
    let data: any = this.data;
    data[fieldname] = true;
    this.setData(data);
  },
  textAreaBlur(event: any) {
    let fieldname: any = event.currentTarget.dataset.focus_field_name;
    let data: any = this.data;
    data[fieldname] = false;
    this.setData(data);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

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

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

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

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

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

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