import { snConfig, updateConfig } from '../../../utils/api/api'
import { getWaterDrop, throttle } from '../../../utils/index/index'

const app = getApp()
Page({
  data: {
    radioList: [{
      name: '是否打印访客单',
      val: 'printVisitorList',
      chooseItem: [],
    },
    {
      name: '是否启用签离',
      val: 'signOut',
      chooseItem: [],
    },
    {
      name: '启用风险人员核查',
      val: 'riskCheck',
      chooseItem: [],
    },
    {
      name: '首页隐藏 通讯录、访客记录 等按钮',
      val: 'hiddenButton',
      chooseItem: [],
    },
    // {
    //   name: '隐藏底部导航栏',
    //   val: 'hideNavigationBar',
    //   chooseItem: [],
    // },
    {
      name: '启用注意事项提示语',
      val: 'reminderAuth',
      chooseItem: [],
    },
    ],
    checkBoxList: [{
      name: '访客记录不脱敏',
      val: 'notDesensitizedColumn',
      chooseItem: [{
        value: 1,
        name: '姓名',
        checked: false
      },
      {
        value: 2,
        name: '身份证',
        checked: false
      },
      {
        value: 3,
        name: '手机',
        checked: false
      }],
    },
    {
      name: '登记页不脱敏',
      val: 'registerNotDesensitizedColumn',
      chooseItem: [{
        value: 1,
        name: '姓名',
        checked: false
      },
      {
        value: 2,
        name: '身份证',
        checked: false
      },],
    },
    ],
    form: {
      printVisitorList: false, // 是否打印访客单
      signOut: true, // 是否启用签离
      riskCheck: false, // 启用风险人员核查
      hiddenButton: false, // 首页隐藏设置、通讯录等按钮
      // hideNavigationBar: false, // 隐藏底部导航栏
      reminderAuth: false, // 启用注意事项提示语
      generalQrcode: true, // 启用通用二维码
      generalQrcodeTitle: "", // 通用二维码标题
      ethQrcode: true, // 启用梯控二维码
      ethQrcodeTitle: "梯控二维码", // 梯控二维码标题
      ethQrcodeUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/visitor/eth/qrCode", // 梯控二维码接口
      notDesensitizedColumn: [], // 访客记录不脱敏
      registerNotDesensitizedColumn: [], // 登记页不脱敏
      confirmCountdownSwitch: true, // 是否启用确定倒计时
      confirmCountdownTime: 15,
    },
    // 梯控
    isShowTK: false,
    TKList: ['https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/visitor/eth/qrCode'],
    isPortraitScreen: false,// 是否为竖屏：true竖屏 false横屏
    screenIntervalId: null, //定时器
  },
  async onLoad() {
    my.hideBackHome();
    const _this = this
    this.initScreenType().then(isPortraitScreenRes => {
      console.log('isPortraitScreenRes', isPortraitScreenRes)
      _this.setData({
        isPortraitScreen: isPortraitScreenRes
      })
    })
    await this.initRadioDefaultData()
    await this.initData()
    // my.showLoading()
  },
  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 () {
          console.log('asdasdsaddasdad', app.globalData)
          if (app.globalData.isPortraitScreen != null) {
            resolve(app.globalData.isPortraitScreen)
            clearInterval(that.data.screenIntervalId);
          }
        }, 1000);
      }
    })
  },
  // 赋值
  async initData(e) {
    my.showLoading()
    try {
      let dto = {
        sn: app.globalData.sn,
        token: app.globalData.FKJConfiguration,
      }
      let res = await snConfig(dto);
      let resultData = res.data || {}
      console.log(resultData)
      let {
        radioList,
        checkBoxList
      } = this.data
      radioList.forEach((radioItem) => {
        if (typeof (resultData[radioItem.val]) !== 'undefined') {
          let checkValue = !!resultData[radioItem.val]
          radioItem.chooseItem[0].checked = checkValue
          radioItem.chooseItem[1].checked = !checkValue
        }
      });
      checkBoxList.forEach((checkBoxItem) => {
        if (typeof (resultData[checkBoxItem.val]) !== 'undefined') {
          let checkValue = resultData[checkBoxItem.val]
          checkBoxItem.chooseItem.forEach((cItem, cIndex) => {
            cItem.checked = checkValue.includes(cItem.value);
          })
        }
      });
      this.setData({
        radioList,
        checkBoxList,
        form: resultData
      })
    } catch (error) { } finally {
      my.hideLoading()
    }
  },
  // 处理单选默认数据
  initRadioDefaultData() {
    let options = [{
      value: true,
      name: '是',
      checked: false
    },
    {
      value: false,
      name: '否',
      checked: false
    },
    ]
    let {
      radioList,
      checkBoxList
    } = this.data
    radioList.forEach(radioItem => {
      radioItem.chooseItem = JSON.parse(JSON.stringify(options))
      let isTrue = ['signOut', 'generalQrcode', 'ethQrcode'].includes(radioItem.val)
      radioItem.chooseItem[0].checked = isTrue
      radioItem.chooseItem[1].checked = !isTrue
    });
    checkBoxList.forEach((checkBoxItem) => {
      checkBoxItem.chooseItem.forEach((cItem, cIndex) => {
        cItem.checked = false;
      })
    });
    this.setData({
      checkBoxList,
      radioList
    })
  },
  // 单选选中
  onRadioChange(e) {
    console.log('onRadioChange', e)
    let currentItem = e.currentTarget.dataset.item;
    let currentIndex = e.currentTarget.dataset.index;
    let checkIndex = e.currentTarget.dataset.checkIndex;
    let checkValue = false;
    currentItem.chooseItem.forEach((cItem, cIndex) => {
      if (cIndex == currentIndex) {
        cItem.checked = true
        checkValue = cItem.value
      } else {
        cItem.checked = false
      }
    })
    console.log(currentItem.chooseItem, currentFormItem)
    let currentRadioItem = `[radioList[${checkIndex}]]`;
    let currentFormItem = `form[${currentItem.val}]`;
    this.setData({
      [currentRadioItem]: currentItem,
      [currentFormItem]: checkValue
    })
  },
  // 多选选中
  onCheckBoxChange(e) {
    console.log(e)
    let currentItem = e.currentTarget.dataset.item;
    let currentIndex = e.currentTarget.dataset.index;
    let checkIndex = e.currentTarget.dataset.checkIndex;
    currentItem.chooseItem.forEach((cItem, cIndex) => {
      if (cIndex == currentIndex) {
        cItem.checked = !cItem.checked
      }
    })
    let checkValue = (currentItem.chooseItem || []).filter(v => v.checked).map(mI => mI.value);
    let currentCheckBoxItem = `[checkBoxList[${checkIndex}]]`;
    let currentFormItem = `form[${currentItem.val}]`;
    this.setData({
      [currentCheckBoxItem]: currentItem,
      [currentFormItem]: checkValue
    })
  },
  onSwitchChange(e) {
    let key = e.currentTarget.dataset.fieldKey
    let value = e.currentTarget.dataset.checked
    console.log(key, value)
    let checkValue = !value
    let forKey = `form[${key}]`
    switch (key) {
      case 'generalQrcode': // 启用通用二维码
        if (!checkValue) {
          this.setData({
            'form.generalQrcodeTitle': '', // 通用二维码标题
          })
        }
        this.setData({
          [forKey]: checkValue
        })
        break;
      case 'ethQrcode': // 启用梯控二维码
        if (checkValue) {
          this.setData({
            'form.ethQrcodeTitle': '梯控二维码', // 梯控二维码标题
            'form.ethQrcodeUrl': 'https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/visitor/eth/qrCode', // 梯控二维码接口
          })
        }
        this.setData({
          [forKey]: checkValue
        })
        break;
      case 'confirmCountdownSwitch': // 标语页确定倒计时
        if (!checkValue) {
          this.setData({
            'form.confirmCountdownTime': 15
          })
        }
        this.setData({
          [forKey]: checkValue
        })
        break;
    }
  },
  // 减
  minus(e) {
    let key = 'confirmCountdownTime'
    let value = this.data.form[key]
    let NameVal = `form[${key}]`
    if (value <= 0 || !value) {
      return
    }
    this.setData({
      [NameVal]: value - 1
    })
  },
  // 加
  add(e) {
    let key = 'confirmCountdownTime'
    let value = this.data.form[key]
    if (!value) {
      value = 0
    }
    let NameVal = `form[${key}]`
    this.setData({
      [NameVal]: value + 1
    })
  },
  // 二维码相关字段选中操作
  getVal(e) {
    let key = e.currentTarget.dataset.key
    let val = e.currentTarget.dataset.val
    console.log(key, val)
    let checkValue = e.detail.value
    let forKey = `form[${key}]`
    switch (key) {
      case 'TK':
        this.setData({
          'form.ethQrcodeUrl': val
        })
        break;
      case 'generalQrcode': // 启用通用二维码
        if (!checkValue) {
          this.setData({
            'form.generalQrcodeTitle': '', // 通用二维码标题
          })
        }
        this.setData({
          [forKey]: checkValue
        })
        break;
      case 'ethQrcode': // 启用梯控二维码
        if (checkValue) {
          this.setData({
            'form.ethQrcodeTitle': '梯控二维码', // 梯控二维码标题
            'form.ethQrcodeUrl': 'https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/visitor/eth/qrCode', // 梯控二维码接口
          })
        }
        this.setData({
          [forKey]: checkValue
        })
        break;
      case 'generalQrcodeTitle': // 通用二维码标题
      case 'ethQrcodeTitle': // 梯控二维码标题
      case 'ethQrcodeUrl': // 梯控二维码接口
      case 'confirmCountdownTime': // 倒计时时长（s）
        this.setData({
          [forKey]: checkValue
        })
        break;
    }
  },

  // 遮罩层
  closeMask() {
    this.setData({
      isShowTK: false,
    })
  },
  // 打开选择框
  openMask(e) {
    let key = e.currentTarget.dataset.key
    switch (key) {
      case 'TK':
        let {
          isShowTK
        } = this.data
        this.setData({
          isShowTK: !isShowTK
        })
        break;
      default:
        break;
    }
  },
  clickAudio() {
    this.setData({
      isShowTK: false,
    })
    getWaterDrop()
  },
  sure: throttle(async function (e) {
    let {
      form
    } = this.data
    console.log(form)
    form.modifyType = app.globalData.modifyType[0];
    form.token = app.globalData.FKJConfiguration;
    form.sn = app.globalData.sn;
    my.showLoading()
    try {
      let res = await updateConfig(form)
      app.globalData.snDisposition.printVisitorList = form.printVisitorList;
      app.globalData.snDisposition.signOut = form.signOut;
      app.globalData.snDisposition.riskCheck = form.riskCheck;
      app.globalData.snDisposition.hiddenButton = form.hiddenButton;
      app.globalData.snDisposition.reminderAuth = form.reminderAuth;
      app.globalData.snDisposition.generalQrcode = form.generalQrcode;
      app.globalData.snDisposition.generalQrcodeTitle = form.generalQrcodeTitle;
      app.globalData.snDisposition.ethQrcode = form.ethQrcode;
      app.globalData.snDisposition.ethQrcodeTitle = form.ethQrcodeTitle;
      app.globalData.snDisposition.ethQrcodeUrl = form.ethQrcodeUrl;
      app.globalData.snDisposition.notDesensitizedColumn = form.notDesensitizedColumn;
      app.globalData.snDisposition.registerNotDesensitizedColumn = form.registerNotDesensitizedColumn;
      app.globalData.snDisposition.confirmCountdownSwitch = form.confirmCountdownSwitch;
      app.globalData.snDisposition.confirmCountdownTime = form.confirmCountdownTime;
      // console.log(app.globalData.snDisposition);
      my.setStorageSync({
        data: app.globalData.snDisposition,
        key: 'snDisposition'
      });
      my.reLaunch({
        url: "/pages/settings/index/index"
      })
    } catch (error) {
      console.log(error);
    } finally {
      my.hideLoading()
    }
  }, 5000),
});
