// pages/backlog/insuranceFeedback/insuranceFeedback.ts
import { putAction, upload, getAction } from '../../../api/base';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    detailInf: {} as any,
    options: [],
    selectIndex: 0,
    selectOption: {} as any,
    marker: '',
    photoList: {
      accidentUrl: [],
      compensateAgreementUrl: [],
      lossAssessmentUrl: [],
      compensateUrl: [],
      otherUrl: [],
      accidentUrlStr: '',
      compensateAgreementUrlStr: '',
      lossAssessmentUrlStr: '',
      compensateUrlStr: '',
      otherUrlStr: ''
    } as any,
    uploadUrl: 'api/vehicles/accidentInfo/upload'
  },
  initPhotoList() {
    let tmp = this.data.photoList;
    // 回显用
    let tmp2: any = Object.assign({}, this.data.photoList);
    for (let key in tmp) {
      if (this.data.detailInf[key]) {
        tmp[key] = this.data.detailInf[key].split(',');
        // 回显用
        tmp[key].forEach((item: any) => {
          tmp2[key].push({
            fileUrl: item
          });
        });
      }
    }
    this.setData({
      photoList: tmp
    });

    // this.selectComponent('#accidentUrl').initPhotoList(tmp2.accidentUrl);
    console.log(this.data.photoList);
  },
  getInsuranceCompanyList() {
    getAction('api/base/insuranceCompany/insuranceCompanyList')
      .then((res: any) => {
        if (res.code == 200) {
          console.log(res);
          let selectIndex = res.result.findIndex(
            (x: any) => x.id == this.data.detailInf.companyId
          );
          this.setData({
            options: res.result,
            selectIndex: selectIndex,
            selectOption: res.result[selectIndex]
          });
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
      .catch((err: any) => {
        this.setData({
          loading: false
        });
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  },
  bindPicker(e: any) {
    console.log(e.detail.value);
    let index = Number(e.detail.value);
    this.setData({
      selectIndex: index,
      selectOption: this.data.options[index]
    });
  },
  getVal(e: any) {
    console.log(e);
    let tmp = this.data.detailInf;
    let key = e.currentTarget.dataset.key;
    if (key == 'insurancePrice') {
      let detail = e.detail;
      tmp[key] = Number(detail.value) > 99999999 ? 99999999 : detail.value;
    } else {
      tmp[key] = e.detail.value;
    }
    this.setData({
      detailInf: tmp
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  returnPic(e: any) {
    console.log(e.detail.photoList);
    let urlList = [] as any;
    e.detail.photoList.forEach((item: any) => {
      urlList.push(item.fileUrl);
    });
    let tmp = this.data.photoList;
    tmp[e.currentTarget.dataset.key] = urlList;
    this.setData({
      photoList: tmp
    });
  },

  // 上传
  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.photoList[fieldname];
        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.photoList[fieldname + 'Str'] = urls;
        data.photoList[fieldname] = otherPhotoFile;
        console.log(data.photoList);
        this.setData(data);
      } else {
        wx.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  deletePhoto(e: any) {
    let { fieldname } = e.currentTarget.dataset;
    let otherPhotoFile = this.data.photoList[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.photoList[fieldname + 'Str'] = urls;
    data.photoList[fieldname] = 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;
  },
  bindSend() {
    let parms = this.data.detailInf;
    parms = Object.assign(parms, {
      accidentUrl: this.data.photoList.accidentUrlStr,
      compensateAgreementUrl: this.data.photoList.compensateAgreementUrlStr,
      lossAssessmentUrl: this.data.photoList.lossAssessmentUrlStr,
      compensateUrl: this.data.photoList.compensateUrlStr,
      otherUrl: this.data.photoList.otherUrlStr
    });
    // 验证非必填
    if (parms.insuranceNo) {
      let msg = this.checkStr(parms.insuranceNo);
      if (msg) {
        wx.showToast({
          title: '理赔案号：' + msg,
          icon: 'none'
        });
        return;
      }
    }
    if (parms.insurancePrice) {
      let regPos = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
      let msg = !regPos.test(parms.insurancePrice);
      if (parms.insurancePrice > 99999999) {
        wx.showToast({
          title: '赔偿金额上限为99999999',
          icon: 'none'
        });
        return;
      }
      if (msg) {
        wx.showToast({
          title: '赔偿金额为正数且最多保留两位小数',
          icon: 'none'
        });
        return;
      }
    }
    if (parms.handleUser) {
      let msg = this.checkStr(parms.insuranceNo);
      if (msg) {
        wx.showToast({
          title: '处理人：' + msg,
          icon: 'none'
        });
        return;
      }
    }
    if (parms.remark) {
      let msg = this.checkStr(parms.remark);
      if (msg) {
        wx.showToast({
          title: '备注：' + msg,
          icon: 'none'
        });
        return;
      }
    }
    wx.showLoading({
      title: '提交中',
      icon: 'none'
    });
    putAction('api/insuranceRecord/edit', parms).then((res: any) => {
      wx.hideLoading();
      if (res.code == 200) {
        console.log(res.result);
        // setTimeout(() => {
        //   wx.navigateBack({ delta: 2 });
        // }, 1500);
        wx.navigateTo({
          url: '../backlogFeedback/backlogFeedback',
          fail: e => {
            console.log(e);
          }
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('onLoad');
    // 接收传参
    const eventChannel = this.getOpenerEventChannel();

    eventChannel &&
      eventChannel.on &&
      eventChannel.on('eventName', data => {
        console.log('接收参数', data);
        let picList = this.data.photoList;
        if (data.accidentUrl) {
          for (let i = 0; i < data.accidentUrl.split(',').length; i++) {
            let pic = data.accidentUrl.split(',')[i];
            picList.accidentUrlStr = data.accidentUrl;
            picList.accidentUrl.push({
              url: pic,
              name: ''
            });
          }
        }
        if (data.compensateAgreementUrl) {
          for (
            let i = 0;
            i < data.compensateAgreementUrl.split(',').length;
            i++
          ) {
            let pic = data.compensateAgreementUrl.split(',')[i];
            picList.compensateAgreementUrlStr = data.compensateAgreementUrl;
            picList.compensateAgreementUrl.push({
              url: pic,
              name: ''
            });
          }
        }
        if (data.compensateUrl) {
          for (let i = 0; i < data.compensateUrl.split(',').length; i++) {
            let pic = data.compensateUrl.split(',')[i];
            picList.compensateUrlStr = data.compensateUrl;
            picList.compensateUrl.push({
              url: pic,
              name: ''
            });
          }
        }
        if (data.lossAssessmentUrl) {
          for (let i = 0; i < data.lossAssessmentUrl.split(',').length; i++) {
            let pic = data.lossAssessmentUrl.split(',')[i];
            picList.lossAssessmentUrlStr = data.lossAssessmentUrl;
            picList.lossAssessmentUrl.push({
              url: pic,
              name: ''
            });
          }
        }
        if (data.otherUrl) {
          for (let i = 0; i < data.otherUrl.split(',').length; i++) {
            let pic = data.otherUrl.split(',')[i];
            picList.otherUrlStr = data.otherUrl;
            picList.otherUrl.push({
              url: pic,
              name: ''
            });
          }
        }
        console.log(picList);
        this.setData({
          detailInf: data,
          photoList: picList
        });
        // this.initPhotoList();
        this.getInsuranceCompanyList();
      });
  },

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

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

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

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

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

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

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