// pages/insurancePolicyReport/insurancePolicyReport.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: {
    showBox: {
      base: true,
      vehicle: true,
      lost: true,
      insurance: true,
      insuranceCost: true,
      check: true
    },
    showSelect: {
      projectSelectShow: false,
      contractSelectShow: false,
      vehicleTypeSelectShow: false,
      templateSelectShow: false,
      yesOrNoSelectShow: false,
      timeSelectShow: false,
      claimToCompanyAccountDate: false,
      claimToThirdAccountDate: false
    } as any,
    vehicleOptionsList: [],
    vehiclePickerIndex: -1,
    insuranceCompanyList: [],
    insuranceCompanyPickerIndex: -1,
    handleStatusOptions: [],
    handleStatusIndex: -1,
    yesOrNoOptions: [
      {
        text: '已处理',
        value: 1
      },
      {
        text: '未处理',
        value: 0
      }
    ],
    requireObj: {
      projectId: '',
      vehicleId: '',
      companyId: '',
      insuranceDate: '',
      insuranceNo: '',
      // insurancePrice: '',
      handleUser: '',
      handleStatus: '',
      vehicleLossAmount: '',
      thirdPropertyDamageAmount: '',
      vehiclePersonalInjuryAmount: '',
      thirdPersonalInjuryAmount: '',
      claimToCompanyAccountDate: '',
      claimToThirdAccountDate: '',
      claimToCompanyAccountAmount: '',
      claimToThirdAccountAmount: '',
      uncompensatedAmount: ''
    },
    params: {
      vehicleId: '',
      vehicleModel: '',
      vehicleType: '',
      projectId: '',
      insuranceDate: '',
      companyId: '',
      // insurancePrice: '',
      insuranceNo: '',
      handleUser: '',
      handleStatus: '',
      remark: '',
      accidentUrl: '',
      accidentUrlList: [],
      compensateAgreementUrl: '',
      compensateAgreementUrlList: [],
      lossAssessmentUrl: '',
      lossAssessmentUrlList: [],
      compensateUrl: '',
      compensateUrlList: [],
      otherUrl: '',
      otherUrlList: [],
      vehicleLossAmount: 0,
      thirdPropertyDamageAmount: 0,
      vehiclePersonalInjuryAmount: 0,
      thirdPersonalInjuryAmount: 0,
      estimatedTotalLossAmount: 0,
      claimToCompanyAccountDate: '',
      claimToThirdAccountDate: '',
      claimToCompanyAccountAmount: 0,
      claimToThirdAccountAmount: 0,
      uncompensatedAmount: 0,
      totalCompensationAmount: 0,
      insurancePrice: 0
    } as any,
    changeProjectIndex: -1,
    insuranceDateTamp: new Date().getTime(),
    claimToCompanyAccountDateTamp: new Date().getTime(),
    claimToThirdAccountDateTamp: 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;
      data.params.vehicleModel =
        data.vehicleOptionsList[detail.index].vehicleModel;
      data.params.vehicleType =
        data.vehicleOptionsList[detail.index].vehicleType;
    } 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 === 'insuranceDate' ||
      fieldname === 'claimToCompanyAccountDate' ||
      fieldname === 'claimToThirdAccountDate'
    ) {
      data.params[fieldname] = dayjs(new Date(detail)).format('YYYY-MM-DD');
      data[fieldindex + 'Temp'] = detail;
    } 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();
  },
  changeAddress() {
    let that = this;
    let { params } = this.data;
    if (this.data.params.checkAddress == '') {
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          wx.chooseLocation({
            latitude: res.latitude,
            longitude: res.longitude,
            success: function (data) {
              console.log(data);
              params.checkAddress = data.address;
              console.log(params);
              that.setData({
                params: params
              });
            }
          });
        }
      });
    } else {
      var _this = this;
      qqmapsdk.search({
        keyword: this.data.params.checkAddress,
        success: function (res: any) {
          if (res.status == 0) {
            //成功后的回调
            console.log(res);
            // 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(data);
                params.checkAddress = data.address;
                console.log(params);
                that.setData({
                  params: params
                });
              }
            });
          } else {
            // 位置信息获取失败
            wx.showToast({
              title: '位置信息获取失败',
              icon: 'none'
            });
          }
        }
      });
    }
  },
  getVehicleOptions() {
    let parms = {
      plateNumber: '',
      pageSize: -1
    };
    getAction('api/vehicle/list', parms).then((res: any) => {
      if (res.code == 200) {
        let arr = [] as any;
        res.result.records.forEach((item: any, index: number) => {
          arr.push({
            text: item.plateNumber,
            value: item.id,
            projectId: item.projectId,
            projectId_dictText: item.projectId_dictText,
            vehicleModel: item.vehicleModel,
            vehicleType: item.vehicleType
          });
          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.companyId != '' &&
              this.data.params.companyId == 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, type } = e.currentTarget.dataset;
    let detail = e.detail;
    let data: any = { ...this.data };
    if (fieldname == 'projectList') {
      data.params.projectList[fieldindex].remark = detail.value;
    } else if (fieldname == 'vehicleList') {
      data.params[fieldname][fieldindex][fieldkey] = detail.value;
    } else if (type == 'number') {
      let num = detail.value;
      if (num < 0 || !num) {
        data.params[fieldname] = 0;
      } else {
        data.params[fieldname] =
          Number(detail.value) > 99999999
            ? 99999999
            : Number(Number(detail.value).toFixed(2));
      }
    } else {
      data.params[fieldname] = detail.value;
    }
    if (data.params[fieldname]) {
      // delete data.requireObj[fieldname];
      data.requireObj[fieldname] = '';
    } else if (
      data.params[fieldname] === '' ||
      data.params[fieldname] === null
    ) {
      data.requireObj[fieldname] = '请填写';
    }
    // 计算预估损失总金额
    if (
      fieldname == 'vehicleLossAmount' ||
      fieldname == 'thirdPropertyDamageAmount' ||
      fieldname == 'vehiclePersonalInjuryAmount' ||
      fieldname == 'thirdPersonalInjuryAmount'
    ) {
      data.params.estimatedTotalLossAmount = Number(
        (
          data.params.vehicleLossAmount +
          data.params.thirdPropertyDamageAmount +
          data.params.vehiclePersonalInjuryAmount +
          data.params.thirdPersonalInjuryAmount
        ).toFixed(2)
      );
    }
    // 计算出险理赔总金额
    else if (
      fieldname == 'claimToCompanyAccountAmount' ||
      fieldname == 'claimToThirdAccountAmount' ||
      fieldname == 'uncompensatedAmount'
    ) {
      data.params.totalCompensationAmount = Number(
        (
          data.params.claimToCompanyAccountAmount +
          data.params.claimToThirdAccountAmount
        ).toFixed(2)
      );
      data.params.insurancePrice = Number(
        (
          data.params.totalCompensationAmount + data.params.uncompensatedAmount
        ).toFixed(2)
      );
    }
    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) {
    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' ||
        key == 'claimToCompanyAccountDate' ||
        key == 'claimToThirdAccountDate'
      ) {
        let timeRegex =
          /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1]))$/;
        if (!timeRegex.test(params[key])) {
          isAllReady = false;
          temp[key] = '请填写正确的时间';
        }
        // temp[key] = temp[key] ? temp[key] : '请填写正确的时间';
      } else if (key == 'insurancePrice') {
        // if(params[key] === '') {
        //   isAllReady = false;
        //   temp[key] = temp[key] ? temp[key] : '请填写';
        // }
        // 判断是否是正整数
        let regPos = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
        console.log(!regPos.test(params[key]));
        if (params[key] > 99999999) {
          temp[key] = '赔偿金额上限为99999999';
        }
        if (!regPos.test(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;
        }
      }
    }
    this.setData({
      requireObj: temp
    });
    console.log(temp, isAllReady);
    return isAllReady;
  },
  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;
  },
  formSubmit() {
    if (!this.isStepReady()) {
      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;
      }
    }
    wx.showLoading({
      title: '保存中'
    });
    postAction('api/insuranceRecord/add', this.data.params).then((res: any) => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 1000);
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getVehicleOptions();
    this.getInsuranceCompanyOptions();
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      insuranceDateTamp: new Date().getTime(),
      claimToCompanyAccountDateTamp: new Date().getTime()
    });
  },

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

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

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

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

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