/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：主页应用
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		admin		   2024-02-20	    1.00		   	首页
 *******************************************************************************/
const app = getApp()

const api = require('@/utils/api.js');
const config = require('@/config/config.js');
const util = require('@/utils/util.js')
const Constants = require('@/utils/Constants');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl:config.image_url + '/static/img/',
    editTip:'长按拖动可以调整应用位置',
    size: 4,
    showMore: false,
    editFlag: false, // 编辑模式
    comMenuList: [], // 常用功能
    comMenuListForCheck: [],// 常用功能（简单数组）用于判断
    allCondition: '',//搜索菜单
    noticeShowFlag: true,// 是否显示通知的
    loadingShow: false,
    // 功能分区全部勾选标识
    RegionCheck: true,
    bingFlag: 0,
    //用户信息
    userInfo: {},
    //角标
    infocodes: ['0303'],
    infos: [
      // 公告查阅
      {
        code: '0303',
        num: 6
      }
    ],
    functionItem: {
      text: '功能分区'
    },
    functionRegion: [
    ],
    functionRegions: [],

    //功能分类-大功能模块
    regions: [

    ],
    //功能分类-大功能模块-页面
    functionItems: [
    ],
  },
  /**
   * @desc   : 展开收缩
   * @author : 周兴
   * @date   : 2024/1/26 11:46
   */
  expand() {
    let showMore = this.data.showMore;
    this.setData({
      showMore: !showMore
    })
  },
  /**
  * @desc : 操作常用应用
  * @author : 周兴
  * @date : 2024/3/29
  */
  comItemClick(e){
    console.log('e',e);
    // 操作常用应用
    this.toApp(e,true);
    setTimeout(()=>{
      this.initDrag()
    },50)
  },
  /**
  * @desc : 初始化drag组件
  * @author : 周兴
  * @date : 2024/3/29
  */
  initDrag(){
    let drag = this.selectComponent('#drag');
    if(drag){
      drag.init();
    }
  },
  /**
  * @desc : drag结束
  * @author : 周兴
  * @date : 2024/3/29
  */
  dragEnd(e) {
    this.setData({
      comMenuList:e.detail.listData
    })
	},
  /**
  * @desc : 进入编辑模式
  * @author : 周兴
  * @date : 2024/3/29
  */
  toEdit() {
    let editFlag = this.data.editFlag
    // 变为编辑模式
    if (!editFlag) {
      wx.setNavigationBarTitle({
        title: '管理应用',
      })
      editFlag = !editFlag;
      let showMore = this.data.showMore
      if (editFlag) {
        showMore = true;
      }
      this.setData({
        showMore: showMore,
        editFlag: editFlag
      })
      // 模仿异步加载数据
      setTimeout(() => {
        this.initDrag();
      }, 100)
    } else {
      // 保存常用功能
      this.saveComMenu();
    }
  },
  /**
  * @desc : 退出编辑模式
  * @author : 周兴
  * @date : 2024/3/29
  */
  cancel() {
    wx.setNavigationBarTitle({
      title: '应用中心',
    })
    this.setData({
      editFlag: false,
      showMore: false
    })
  },
  /**
  * @desc : 保存常用功能
  * @author : 周兴
  * @date : 2024/3/29
  */
  saveComMenu() {
    let comMenuList = this.data.comMenuList || []
    comMenuList.forEach((it, index) => {
      it.staffId = app.globalData.user.staffId,
        it.appCode = Constants.APP_CODE,
        it.displayNo = index
    })

    let service = app.globalData['comMenuService']
    api.request(service.prefix + service.save, 'POST', comMenuList).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        wx.showToast({
          title: "保存成功",
          image: '/static/image/success.png',
          duration: 1000
        })
      }
    });
  },
  /**
  * @desc : 查询常用应用
  * @author : 周兴
  * @date : 2024/3/29
  */
  getComMenu() {
    let params = {
      staffId: app.globalData.user.staffId,
      appCode: Constants.APP_CODE,
    }
    let service = app.globalData['comMenuService']
    api.request(service.prefix + service.selectByCond, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        let comMenuList = res.data.data
        let comMenuListForCheck = comMenuList.map(it => it.menuUuid)
        this.setData({
          comMenuList: comMenuList,
          comMenuListForCheck: comMenuListForCheck
        })
      }
    });
  },
  /**
 * 过滤菜单
 */
  filterFunction() {
    let _this = this
    let searchtext = _this.data.allCondition
    let regionsAll = [...app.globalData.menus]

    let functionRegionItem = {}
    let region = {}
    // 导航权限数组
    let functionRegion = []
    let functionRegions = []
    let regions = []
    let navigrightsTemp = []
    navigrightsTemp = regionsAll.filter((item) => item.menuType == 0 && item.objectCode != 'mine') || []

    if (searchtext) {
      navigrightsTemp = navigrightsTemp.filter((item) => item.menuName.indexOf(searchtext) >= 0)
    }

    navigrightsTemp.forEach(item => {
      functionRegionItem = {
        title: item.menuName,
        checked: true
      }
      region = {
        FunctionName: item.menuName,
        FunctionCodeOrder: item.menuUuid
      }
      functionRegion.push(functionRegionItem)
      functionRegions.push(item.menuName)
      regions.push(region)
    })
    //页面权限数组
    let functionItems = []
    let pagerights = regionsAll.filter((item) => item.menuType == 1) || []
    let pagerightsTemp = pagerights.filter((item) => item.objectPath) || []
    let pagerightsTempTwo = []
    pagerightsTempTwo = pagerightsTemp.filter((item) => item.objectCode != 'store-index') || []
    if (searchtext) {
      //过滤子级
      pagerightsTempTwo = pagerightsTempTwo.filter((item) => item.menuName.indexOf(searchtext) >= 0) || []

      // 增加子级菜单的父级
      let copyRights = [...pagerightsTempTwo]
      for (let i in pagerightsTempTwo) {
        let rightitem = regionsAll.filter((item) => item.menuUuid.indexOf(pagerightsTempTwo[i].parentUuid) >= 0 && item.menuType == 0 && item.objectCode != 'mine')
        if (rightitem.length > 0) {
          rightitem.forEach(item => {
            functionRegionItem = {
              title: item.menuName,
              checked: true
            }
            region = {
              FunctionName: item.menuName,
              FunctionCodeOrder: item.menuUuid
            }
            functionRegion.push(functionRegionItem)
            functionRegions.push(item.menuName)
            regions.push(region)

          })
        }
      }
      functionRegion = this.uniqueFunc(functionRegion, 'title')
      functionRegions = this.removeDuplicate(functionRegions)
      regions = this.uniqueFunc(regions, 'FunctionName')
    }

    pagerightsTempTwo.forEach(item => {
      let pageitem = {
        FunctionName: item.menuName,
        FormName: item.objectPath,
        ImageUri: item.icon ? (this.data.imageUrl + item.icon + '.png') : '',
        PFunctionCode: item.parentUuid,
        FunctionCode: item.menuUuid
      }
      functionItems.push(pageitem)
    })

    // console.log('functionItems',functionRegion);
    this.setData({
      regions: regions,
      functionItems: functionItems,
      functionRegion: functionRegion,
      functionRegions: functionRegions,
      regionsAll: regionsAll,
    })

    // 画面的按钮的数组  
  },

  uniqueFunc(arr, uniId) {
    const res = new Map();
    return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
  },
  removeDuplicate(arr) {
    const newArr = []
    arr.forEach(item => {

      if (newArr.indexOf(item) === -1) {
        newArr.push(item)
      }
    })
    return newArr // 返回一个新数组
  },

  /**
   * 设置权限
   * @param {*} rights 
   * @param {*} initFlag 
   */


  // 测试fixed函数
  //  this.testObjectValue()
  // console.log("ceshi",parseInt('1'),  );
  setRight: function (rights, initFlag) {
    this.setData({
      rights: rights
    })
    let regions = []
    let regionsAll = []
    let functionItems = []
    let functionRegion = []
    let functionRegionItem = {}
    let functionRegions = []

    if (rights != null) {
      for (let i in rights) {
        var item = rights[i]
        if (!item.FunctionFlag) {
          // 功能分区
          regions.push(item)
          if (initFlag) {
            regionsAll.push(item)
          }
          functionRegionItem = { title: item.FunctionName, checked: true }
          functionRegion.push(functionRegionItem)
          functionRegions.push(item.FunctionName)
        }
        else {
          // 子级功能
          functionItems.push(item)
        }
      }
    }

    this.setData({
      regions: regions,
      functionItems: functionItems,
      functionRegion: functionRegion,
      functionRegions: functionRegions
    })
    if (initFlag) {
      this.setData({
        regionsAll: regionsAll,
      })
    }
  },

  /**
    * 选择下拉后查询
    */
  dropdowncommit(e) {
    this.setData({
      functionRegions: e.detail.dataTitle
    })
    this.selectComponent('#functionItem').toggle();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 调用权限时候放开
    this.filterFunction();
    // 查询常用功能
    this.getComMenu();
  },

  /* 点击icon事件 */
  toApp(e,comFlag) {
    // 编辑模式不跳页
    if (this.data.editFlag) {
      if(comFlag){
        // 删除常用功能
        this.delCom(e.detail.data);
      }else{
        // 增加到常用功能
        this.addToCom(e.currentTarget.dataset.item);
        // 刷新drag组件
        setTimeout(() => {
          this.initDrag();
        }, 100)
      }
      // let comFlag = e.currentTarget.dataset.com
      // // 删除常用功能
      // if (comFlag) {
      //   this.delCom(e.currentTarget.dataset.item);
      // } else {
      //   // 增加到常用功能
      //   this.addToCom(e.currentTarget.dataset.item);
      // }
      return;
    }
    let url = e.currentTarget.dataset.url
    let code = e.currentTarget.dataset.code
    if (!url) {
      wx.showToast({
        title: '功能开发中',
        image: '/static/image/warning.png',
        duration: 2000
      })
      return
    }
    // 调转页面
    wx.navigateTo({
      url: url,
      success: function (res) {
        res.eventChannel.emit('params', { formMode: 'index', menuUuid: code })
      }
    })
  },
  /**
   * @desc : 删除常用应用
   * @author : 周兴
   * @date : 2024/3/29 9:16
   */
  delCom(item) {
    let comMenuList = this.data.comMenuList
    let comMenuListForCheck = this.data.comMenuListForCheck
    comMenuList = comMenuList.filter(it => it.menuUuid != item.menuUuid)
    comMenuListForCheck = comMenuListForCheck.filter(it => it != item.menuUuid)
    this.setData({
      comMenuList: comMenuList,
      comMenuListForCheck: comMenuListForCheck
    })
  },
  /**
   * @desc : 添加到常用应用中
   * @author : 周兴
   * @date : 2024/3/29 9:16
   */
  addToCom(item) {
    let comMenuList = this.data.comMenuList
    let comMenuListForCheck = this.data.comMenuListForCheck
    let it = {}
    it.menuUuid = item.FunctionCode
    it.objectPath = item.FormName
    let imageUri = item.ImageUri + ''
    it.objectIcon = imageUri ? (imageUri.substring(imageUri.lastIndexOf('/') + 1)) : ''
    it.menuName = item.FunctionName

    console.log('er', it, comMenuList);
    let filters = comMenuList.filter(t => t.menuUuid == it.menuUuid);
    if (!filters || filters.length == 0) {
      if (comMenuList && comMenuList.length >= 9) {
        util.showToast('常用应用不能超过9个');
        return
      }
      comMenuList.push(it);
      comMenuListForCheck.push(it.menuUuid)
    }
    this.setData({
      comMenuList: comMenuList,
      comMenuListForCheck: comMenuListForCheck
    })
  },

  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function () {
    let that = this
    //调用刷新时将执行的方法
    this.getBindStatus().then(res => {
      // 调用权限时候放开
      this.filterFunction()
      //隐藏导航条加载动画
      wx.hideNavigationBarLoading();
      setTimeout(function () {
        that.setData({
          loadingShow: false,
        })
        //停止下拉刷新
        wx.stopPullDownRefresh();
      }, 800)
    })
  },


  /**
   * 从app。js中获取真实的 企业userid和企业corpid
   * @param {*} param 
   */
  getBindStatus() {
    return new Promise((resolve, reject) => {
      this.setData({
        loadingShow: true,
      })
      let p = {
        qvcorpid: app.globalData.qvcorpid,
        qvuserid: app.globalData.qvuserid,
        appUuid: Constants.APP_WX_HEGII,
        clientId: Constants.CLIENT_ID
      }
      // 从app。js中获取真实的 企业userid和企业corpid
      app.getBindStatus(p).then(resstatus => {
        // 返回值 用户对象存在
        if (resstatus.data.data) {
          let user = resstatus.data.data
          app.globalData.user = user
          app.globalData.token = user.token
          app.globalData.menus = user.menu
          //按钮权限
          if (user.menus && user.menus.length > 0) {
            let buttonRights = []
            user.menus.forEach(it => {
              buttonRights.push(it.levelCode)
            })
            app.globalData.buttonRights = buttonRights
          }
        }
      })
      resolve()
    })
  },
  toprint() {
    wx.navigateTo({
      url: '/package4/pages/order-printing/order-printing',
    })
  },

  toOrgCategory() {
    wx.navigateTo({
      url: '/package-purchase/pages/kpi-org-category/kpi-org-category',
    })
  },

  toOrgSpu() {
    wx.navigateTo({
      url: '/package-purchase/pages/kpi-org-spu/kpi-org-spu',
    })
  },

  toStaffCategory() {
    wx.navigateTo({
      url: '/package-purchase/pages/kpi-staff-category/kpi-staff-category',
    })
  },
  toStaffSpu() {
    wx.navigateTo({
      url: '/package-purchase/pages/kpi-staff-spu/kpi-staff-spu',
    })
  },
})