import {
  getDate,
  getWaterDrop,
  formatTime
} from '../../../utils/index/index'
import {
  publicInterface,
} from '../../../utils/api/api'
const app = getApp()
Page({
  data: {
    formPath: null, //从哪个页面来
    searchList: [{
      name: '姓名',
      val: 'name',
      placeholder: '请输入姓名',
    },
      {
        name: '身份证',
        val: 'idNumber',
        placeholder: '请输入身份证',
      },
      {
        name: '手机号',
        val: 'phone',
        placeholder: '请输入手机号',
      },
      {
        name: '来访单位',
        val: 'company',
        placeholder: '请输入来访单位',
      },
      {
        name: '受访人',
        val: 'visiteeXm',
        placeholder: '请输入受访人',
      },
      {
        name: '受访部门',
        val: 'visiteeBm',
        placeholder: '请输入受访部门',
      },
    ],
    isShowSearch: false, // 搜索项
    dateRangePickerVisible: false,
    searchForm: {
      name: '',
      phone: '',
      idNumber: '',
      defaultDateRange: null,
      startTime: '',
      endTime: '',
      sn: '',
      company: '',
      visiteeXm: '',
      visiteeBm: '',
      carno: '',
      signOutStartTime: '',
      signOutEndTime: '',
      reason: '',
    },
    notDesensitizedColumn: [],
    signOutList: [{
      id: true,
      name: '已签离'
    },
      {
        id: false,
        name: '未签离'
      },
    ],
    tableList: [], // 表格展示数据
    pagination: {
      // 分页
      current: 1, // 当前页码
      pageSize: 8, // 每页条数
      pageNum: 0, //总页数
      total: 0, // 总数
    },
    causeMatterList: [],
    provinceArr: ["粤", "京", "津", "渝", "沪", "冀", "晋", "辽", "吉", "黑", "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "琼", "川", "贵", "云", "陕", "甘", "青", "蒙", "桂", "宁", "新", "藏", "使", "领", "警", "学", "港", "澳"],
    strArr: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    hiddenPro: true, // 隐藏省份键盘
    hiddenStr: true, // 隐藏数字字母键盘
    carnum: '', //车牌号码
    // 键盘结束
    downBtn: '关闭',

    isPortraitScreen: false,// 是否为竖屏:true竖屏 false横屏
    screenIntervalId: null, //定时器
  },
  onLoad(e) {
    my.hideBackHome();
    const _this = this
    this.initScreenType().then(isPortraitScreenRes => {
      _this.setData({
        isPortraitScreen: isPortraitScreenRes
      })
    })
    let visitReasonList = (app.globalData.snDisposition.visitReason || '业务拜访/会议邀请/施工单位/其他事项').split('/');
    this.setData({
      causeMatterList: visitReasonList,
      formPath: e.formPath || null,
      notDesensitizedColumn: app.globalData.snDisposition.notDesensitizedColumn
    })
    this.data.searchFormCopy = JSON.parse(JSON.stringify(this.data.searchForm));
    this.getTable()
  },
  initScreenType() {
    let that = this
    return new Promise((resolve, reject) => {
      if (app.globalData.isPortraitScreen) {
        if (app.globalData.isPortraitScreen != null) {
          resolve(app.globalData.isPortraitScreen)
        }
      } else {
        that.data.screenIntervalId = setInterval(function () {
          if (app.globalData.isPortraitScreen != null) {
            resolve(app.globalData.isPortraitScreen)
            clearInterval(that.data.screenIntervalId);
          }
        }, 1000);
      }
    })
  },
  async getTable(newCurrent = 1) {
    let {
      searchForm,
      pagination: { pageSize },
      carnum
    } = this.data;
    searchForm.sn = app.globalData.sn
    let params = {
      data: {
        ...searchForm,
        carno: carnum
      },
      pageNum: newCurrent,
      pageSize,
    }
    my.showLoading()
    try {
      let res = await publicInterface({
        prop: 'fkjRecordUrl',
        defaultProp: '/visitorReportPageList',
        data: params,
        method: 'post',
        errorTip: '访客记录api请求失败'
      })
      const resData = res.data || {}
      this.setData({
        'pagination.current': newCurrent,
        'pagination.pageNum': resData.pages,
        'pagination.total': resData.total,
        tableList: resData.list,
      })
    } catch (error) {
      my.hideLoading();
      console.log(error);
          my.showToast({
            content: error.msg || '访客记录api请求失败',
            duration: 2000
          });
    } finally {
      my.hideLoading()
    }

  },
  // 是否显示搜索项
  getIsShow() {
    let {
      isShowSearch
    } = this.data
    this.setData({
      isShowSearch: !isShowSearch,
    })
  },
  clickAudio() {
    getWaterDrop()
  },
  //签离
  async signOff(e) {
    let item = e.currentTarget.dataset.item
    let data = {
      sn: app.globalData.sn,
      userVisitorListDetailId: item.userVisitorListDetailId,
    }

    try {
      let res = await publicInterface({
        prop: 'fkjSignOutUrl',
        defaultProp: '/visitorSignOut',
        data: data,
        method: 'post',
        errorTip: '手动签离api请求失败'
      })
      my.showToast({
        content: '签离成功',
        duration: 2000
      });
      let {
        pagination: { current },
      } = this.data
      this.getTable(current)
    } catch (error) {
      console.log(error);
      my.showToast({
        content: error.msg || '手动签离api请求失败',
        duration: 2000
      });
    }
  },
  getVal(e) {
    let key = e.currentTarget.dataset.key
    let searchFormKey = `searchForm[${key}]`
    let causeMatterList = this.data.causeMatterList
    let signOutList = this.data.signOutList
    switch (key) {
      case 'reason':
        this.setData({
          'searchForm.reason': causeMatterList[e.detail.value],
        })
        break;
      case 'isSignOut':
        this.setData({
          'searchForm.isSignOut': signOutList[e.detail.value].id,
          'searchForm.isSignOutName': signOutList[e.detail.value].name,
        })
        break;
      default:
        this.setData({
          [searchFormKey]: e.detail.value
        })
        break;
    }

  },
  // 获取日期
  datePicker(e) {
    my.datePicker({
      format: 'yyyy-MM-dd HH:mm:ss', //返回的日期格式
      currentDate: getDate(), //初始选择的日期时间,默认当前时间
      startDate: '2012-01-01 11:11:11', //最小日期时间
      endDate: getDate(), //最大日期时间
      success: res => {
        let key = e.currentTarget.dataset.key
        this.setData({
          [`searchForm.${key}`]: res.date
        });
      },
    });
  },
  // 查询
  inquireFun() {
    my.showLoading()
    try {
      this.setData({
        'pagination.current': 1,
      })
      this.getTable()
    } catch (error) {
      console.log(error);
    } finally {
      my.hideLoading()
    }
  },
  //清空
  clearFun() {
    let searchForm = JSON.parse(JSON.stringify(this.data.searchFormCopy));
    console.log(searchForm)
    this.setData({
      searchForm,
      carnum: '',
      hiddenPro: true, // 隐藏省份键盘
      hiddenStr: true, // 隐藏数字字母键盘
      downBtn: '关闭',
    })
    this.getTable()
  },
  // 上一页
  previousFun() {
    let {
      pagination: { current },
    } = this.data
    if (current <= 1) {
      return
    }
    let newCurrent = current - 1;
    this.getTable(newCurrent)
  },
  // 下一页
  nextFun() {
    let {
      pagination: { pageNum, current },
    } = this.data
    if (current >= pageNum) {
      return
    }
    let newCurrent = current + 1;
    this.getTable(newCurrent)
  },
  handleTriggerControlledDateRangePicker(visible, e) {
    console.log('handleTriggerControlledDateRangePicker', visible, e);
    this.setData({
      dateRangePickerVisible: visible,
    });
  },
  handleRangeOk(date, format, e) {
    console.log('onRangeOk', date, format, e);
    this.setData({
      'searchForm.startTime': formatTime(date[0], 'YYYY-MM-DD HH:NN:SS'),
      'searchForm.endTime': formatTime(date[1], 'YYYY-MM-DD HH:NN:SS'),
      'searchForm.defaultDateRange': date,
    })
  },
  // 关闭
  closeFun() {
    my.reLaunch({
      url: this.data.formPath ? '/pages/home/index' : '/pages/settings/index/index',
    })
  },

  // 键盘函数开始
  proTap(e) { //点击省份
    let that = this;
    let province = e.currentTarget.dataset.province;
    let carnum = this.data.carnum;
    if (carnum.length < 1) { //避免连续点击
      carnum += province;
    }
    this.setData({
      carnum: carnum,
      hiddenPro: true,
      hiddenStr: false,
    })
  },
  strTap(e) { //点击字母数字
    let that = this;
    this.setData({
      waiting: true
    })
    let province = e.currentTarget.dataset.str;
    let carnum = this.data.carnum;
    // console.log(carnum.length)
    if (carnum.length <= 8) { //避免连续点击
      carnum += province;
      console.log(carnum);
    }
    this.setData({
      notNum: false,
      carnum: carnum,
    })
    this.setData({
      notNum: false,
      carnum: carnum,
    })
    setTimeout(() => {
      that.setData({
        waiting: false
      })
    }, 100);
    if (carnum.length > 6) {
      this.setData({
        downBtn: '完成',
        strDisabled: true,
      })
      // this.searchCardInfo()
      return; // 车牌长度最多为7个
    }
  },
  backSpace() { //退格
    let carnum = this.data.carnum;
    if (carnum.length <= 7) {
      this.setData({
        downBtn: '关闭',
        strDisabled: false,
      })
    }
    var arr = carnum.split('');
    arr.splice(-1, 1)
    var str = arr.join('')
    if (arr.length < 2) {
      this.setData({
        notNum: true
      })
    }
    if (str == '') {
      this.setData({
        hiddenPro: false,
        hiddenStr: true
      })
    }
    this.setData({
      carnum: str
    })
  },
  backKeyboard() { //返回省份键盘
    if (this.data.carnum.length > 6) {
      this.setData({
        downBtn: '完成',
        hiddenPro: true,
        hiddenStr: false
      })
    } else if (this.data.carnum.length > 0) {
      this.setData({
        hiddenPro: true,
        hiddenStr: false
      })
    } else {
      this.setData({
        hiddenPro: false,
        hiddenStr: true
      })
    }
  },
  applyNum() {
    this.setData({
      hiddenPro: true,
      hiddenStr: true,
    })
  },
  // 点击其他地方关闭弹窗
  hidePopup() {
    if (!this.data.hiddenPro || !this.data.hiddenStr) {
      this.applyNum();
    }
  },
});