// pages/eventReport/eventReportAdd/eventReportAdd.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: {
    showSelect: {
      projectSelectShow: false,
      eventCategoryShow: false,
      yesOrNoSelectShow: false,
      timeSelectShow: false,
      userSelectShow: false
    } as any,
    projectOptionsList: [],
    projectPickerIndex: -1,
    eventCategoryOptions: [], // 事件分类
    eventCategoryIndex: -1,
    userList: [],
    checkUserPickerIndex: -1,
    acceptUserPickerIndex: -1,
    yesOrNoOptions: [
      {
        text: '是',
        value: 1
      },
      {
        text: '否',
        value: 0
      }
    ],
    requireObj: {
      projectId: '',
      eventTheme: '',
      eventCategory: '',
      reportTime: '',
      phoneNumber: '',
      eventText: ''
    },
    params: {
      projectId: '',
      eventTheme: '',
      eventCategory: '',
      reportTime: '',
      phoneNumber: '',
      eventText: '',
      remark: '',
      fileUrl: '',
      fileUrlList: [] as any
    } as any,
    changeProjectIndex: -1,
    reportTimestamp: new Date().getTime(),
    userInf: {} as any
  },
  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.reportTime) {
        data.reportTimestamp = 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;
    }
    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 === 'reportTime') {
      console.log(data.params.reportTime);
      data.params[fieldname] = dayjs(new Date(detail)).format(
        'YYYY-MM-DD HH:mm'
      );
      console.log(data.params[fieldname]);
    } else {
      data.params[fieldname] = detail.value.value;
      data[fieldindex] = detail.index;
    }
    if (data.params[fieldname]) {
      // delete data.requireObj[fieldname];
      data.requireObj[fieldname] = '';
    } else {
      data.requireObj[fieldname] = '此项为必填项';
    }
    console.log(this.data);
    this.setData(data);
    this.hidePicker();
  },
  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'
            });
          }
        }
      });
    }
  },
  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.setData({
          projectOptionsList: 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 == 'event_category') {
          this.setData({
            eventCategoryOptions: res.result,
            eventCategoryIndex: -1
            // checkStatus: res.result[0]
          });
          if (this.data.params.eventCategory != '') {
            let i = res.result.findIndex(
              (x: any) => x.value == this.data.params.eventCategory
            );
            this.setData({
              eventCategoryIndex: i
            });
          }
        } else {
        }
      } 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.checkUserId != '' &&
            this.data.params.checkUserId == item.id
          ) {
            this.setData({
              checkUserPickerIndex: index
            });
          }
          if (
            this.data.params.acceptUserId != '' &&
            this.data.params.acceptUserId == item.id
          ) {
            this.setData({
              acceptUserPickerIndex: index
            });
          }
        });
        this.setData({
          userList: arr
        });
      } 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].remark = detail.value;
    } else if (fieldname == 'reportTime') {
      data.reportTimestamp = detail;
      data.params[fieldindex] = dayjs(detail).format('YYYY-MM-DD HH:mm');
    } 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].remark = '';
    } else if (fieldname == 'vehicleList') {
      data.params[fieldname][fieldindex][fieldkey] = '';
    } else {
      data.params[fieldname] = '';
    }
    this.setData(data);
  },
  addRow(e: any) {
    console.log(123);
    let { fieldname } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    if (fieldname == 'vehicleList') {
      data.params[fieldname].push({
        vehicleNo: '',
        frameNumber: ''
      });
      data.requireObj[fieldname].push({
        vehicleNo: '',
        frameNumber: ''
      });
    }
    this.setData(data);
  },
  delRow(e: any) {
    let { fieldname, fieldindex } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    if (fieldname == 'vehicleList') {
      let arr = data.params[fieldname],
        value = data.params[fieldname][fieldindex];
      let newSet = new Set(arr);
      newSet.delete(value);
      let newArr = [...newSet];
      data.params[fieldname] = newArr;
      let arr2 = data.requireObj[fieldname],
        value2 = data.requireObj[fieldname][fieldindex];
      let newSet2 = new Set(arr2);
      newSet.delete(value2);
      let newArr2 = [...newSet2];
      data.requireObj[fieldname] = newArr2;
    }
    this.setData(data);
    console.log(data);
  },
  radioOnChange(e: any) {
    console.log(e);
    let { fieldname } = e.currentTarget.dataset;
    let data: any = { ...this.data };
    data.params[fieldname] = e.detail;
    this.setData(data);
  },
  // 上传
  afterRead(e: any) {
    console.log(e);
    let { fieldname } = e.currentTarget.dataset;
    const file = e.detail;
    let option = {
      name: 'file',
      filePath: e.detail.file.url
    };
    upload('api/event/info/upload', 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);
  },
  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.requireObj;
    let params: any = this.data.params;
    for (let key in temp) {
      if (key == 'id') {
        continue;
      }
      if (key == 'reportTime') {
        let timeRegex =
          /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/;
        if (!timeRegex.test(params[key])) {
          isAllReady = false;
          temp[key] = '请填写正确的时间';
        }
        // temp[key] = temp[key] ? temp[key] : '请填写正确的时间';
      } else if (key == 'phoneNumber') {
        let timeRegex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
        if (!timeRegex.test(params[key])) {
          isAllReady = false;
          temp[key] = '请填写正确的联系电话';
        }
      } else if (key == 'eventText') {
        // 空格输入校验
        let spaceRegex = /^\S*$/;
        let regex = /[!@#$%^&*?><|\\\\]/;
        let tooLong = temp[key].length > 500;
        if (!params[key]) {
          temp[key] = '此项为必填项';
        } else if (params[key] && !spaceRegex.test(params[key])) {
          temp[key] = '不支持含有空格';
        } else if (params[key] && regex.test(params[key])) {
          temp[key] = '不支持特殊字符';
        } else if (params[key] && tooLong) {
          temp[key] = '输入长度不得超过500个字符';
        } else {
          temp[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() {
    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/event/info/add', this.data.params).then((res: any) => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        wx.navigateBack({
          delta: 1
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getProjectOptions();
    this.getDictOptions('event_category');
    this.getByRoleCode();
    let userInf = wx.getStorageSync('userInfo');
    this.setData({
      userInf: userInf
    });
    // 接收传参
    // const eventChannel = this.getOpenerEventChannel();
    // eventChannel &&
    //   eventChannel.on &&
    //   eventChannel.on('eventName', data => {
    //     console.log('接收参数', data);

    //     data.fileUrlList = [];
    //     if (data.fileUrl) {
    //       for (let i = 0; i < data.fileUrl.split(',').length; i++) {
    //         let pic = data.fileUrl.split(',')[i];
    //         data.fileUrlList.push({
    //           url: pic,
    //           name: ''
    //         });
    //       }
    //     }
    //     this.setData({
    //       params: data,
    //       checkTimeTamp: new Date(data.checkTime).getTime()
    //     });
    //   });
  },

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

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

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

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

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

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

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