<template>
  <view class="content">
    <div class="header">
      <div class="message"></div>
      <div class="scan-code" @click="handleScanCode"></div>
    </div>
    <div class="content-wrapper">
      <!-- 搜索 -->
      <div class="search-wrapper">
        <u-input
          placeholder="请输入搜索内容"
          suffixIcon="search"
          suffixIconStyle="color: #909399"
          shape="circle"
          @input="handleSearch"
        ></u-input>
        <HomeMenu :title="projectTitle" :menuList="projList" v-if="projList.length > 0" />
        <HomeMenu :title="educationTitle" :menuList="educationList" v-if="educationList.length > 0" />
        <HomeMenu :title="hiddenDangerTitle" :menuList="hiddenDangerList" v-if="hiddenDangerList.length > 0" />
        <HomeMenu :title="violationTitle" :menuList="violationList" v-if="violationList.length > 0" />
        <HomeMenu :title="safetyTitle" :menuList="safetyList" v-if="safetyList.length > 0" />
      </div>
    </div>

    <Tabbar v-if="showTabbar" />
  </view>
</template>

<script>
import HomeMenu from './component/HomeMenu'
import { getInfo } from '@/api/login'
import { trainingSign } from '@/api/educationTraining'

export default {
  name: 'index',
  components: {
    HomeMenu
  },
  data() {
    return {
      showTabbar: false,
      // 工程管理
      projectTitle: '工程管理',
      projectMenuList: [
        {
          index: 0,
          name: '新建工程',
          url: 'static/images/imgs/new-proj.png',
          isShowItem: true,
          path: 'newProject/index'
        },
        {
          index: 1,
          name: '工程信息',
          url: 'static/images/imgs/proj-Info.png',
          isShowItem: true,
          path: 'projectInfo/index'
        },
        {
          index: 2,
          name: '工程审批',
          url: 'static/images/imgs/proj-approve.png',
          isShowItem: true,
          path: 'projectApproval/index'
        },
        {
          index: 3,
          name: '视频监控',
          url: 'static/images/imgs/video.png',
          isShowItem: true,
          path: 'videoSurveillance/index'
        }
      ],
      // 传递给子组件的数据 - 工程管理
      projList: [],
      // 教育培训
      educationTitle: '教育培训',
      educationMenuList: [
        {
          index: 0,
          name: '学习任务',
          url: 'static/images/imgs/learning-tasks.png',
          isShowItem: true,
          path: 'learningTasks/index'
        },
        {
          index: 1,
          name: '我的培训',
          url: 'static/images/imgs/my-training.png',
          isShowItem: true,
          path: 'myTraining/index'
        },
        {
          index: 2,
          name: '我的考试',
          url: 'static/images/imgs/my-exam.png',
          isShowItem: true,
          path: 'myExam/index'
        },
        {
          index: 4,
          name: '自主练习',
          url: 'static/images/imgs/learning-tasks.png',
          isShowItem: true,
          path: 'myExercise/index'
        }
      ],
      educationList: [],
      // 隐患排查
      hiddenDangerTitle: '隐患排查',
      hiddenDangerMenuList: [
        {
          index: 0,
          name: '安全检查记录',
          url: 'static/images/imgs/safetyCheckRecord.png',
          isShowItem: true,
          path: 'safetyCheckRecord/index'
        },
        {
          index: 1,
          name: '隐患整改验收',
          url: 'static/images/imgs/hiddenDanger.png',
          isShowItem: true,
          path: 'hiddenDangerRectificationApproval/index2'
        },
        {
          index: 2,
          name: '隐患整改审批',
          url: 'static/images/imgs/hiddenDanger.png',
          isShowItem: true,
          path: 'hiddenDangerRectificationApproval/index'
        },
        {
          index: 3,
          name: '延期申请验收',
          url: 'static/images/imgs/delayRectification.png',
          isShowItem: true,
          path: 'delayRectificationApproval/acceptance'
        },
        {
          index: 4,
          name: '延期申请审批',
          url: 'static/images/imgs/delayRectification.png',
          isShowItem: true,
          path: 'delayRectificationApproval/index'
        }
      ],
      hiddenDangerList: [],
      // 违章管理
      violationTitle: '违章管理',
      violationMenuList: [
        {
          index: 0,
          name: '违章列表',
          url: 'static/images/imgs/violation-list.png',
          isShowItem: true,
          path: 'violationManagenment/violationList'
        },
        {
          index: 1,
          name: '违章处罚审核',
          url: 'static/images/imgs/violationPunishment.png',
          isShowItem: true,
          path: 'violationManagenment/violationPenalty'
        }
      ],
      violationList: [],
      // 安全小哨兵
      safetyTitle: '安全小哨兵',
      safetyMenuList: [
        {
          index: 0,
          name: '随手拍',
          url: 'static/images/imgs/takePhotos.png',
          isShowItem: true,
          path: 'randomlySnapPicture/index'
        }
      ],
      safetyList: []
    }
  },
  mounted() {
    console.log('mounted-首页')
    this.getUserInfo()
    this.getSystemInfo()
  },
  methods: {
    // 获取设备信息
    getSystemInfo() {
      uni.getSystemInfo({
        success: res => {
          console.log('设备信息', res.platform)
          uni.setStorageSync('phone-platform', res.platform)
        }
      })
    },
    // 获取用户信息
    getUserInfo() {
      getInfo()
        .then(res => {
          console.log('用户信息', res)
          if (res.code == 200) {
            if (res.permissions[0] == '*:*:*') {
              this.projList = this.projectMenuList
              this.educationList = this.educationMenuList
              this.hiddenDangerList = this.hiddenDangerMenuList
              this.violationList = this.violationMenuList
              this.safetyList = this.safetyMenuList
            } else {
              // res.permissions 是数组, 里面是 'takePhotos/index' 路由地址, 遍历查看是否有对应的路由地址, 有则显示
              res.permissions.forEach(item => {
                this.projectMenuList.forEach(menuItem => {
                  if (menuItem.path == item) {
                    this.projList.push(menuItem)
                    // 根据 index 属性排序
                    this.projList.sort((a, b) => a.index - b.index)
                  }
                })
                this.educationMenuList.forEach(menuItem => {
                  if (menuItem.path == item) {
                    this.educationList.push(menuItem)
                    this.educationList.sort((a, b) => a.index - b.index)
                  }
                })
                this.hiddenDangerMenuList.forEach(menuItem => {
                  if (menuItem.path == item) {
                    this.hiddenDangerList.push(menuItem)
                    this.hiddenDangerList.sort((a, b) => a.index - b.index)
                  }
                })
                this.violationMenuList.forEach(menuItem => {
                  if (menuItem.path == item) {
                    this.violationList.push(menuItem)
                    this.violationList.sort((a, b) => a.index - b.index)
                  }
                })
                this.safetyMenuList.forEach(menuItem => {
                  if (menuItem.path == item) {
                    this.safetyList.push(menuItem)
                    this.safetyList.sort((a, b) => a.index - b.index)
                  }
                })
              })
            }

            const userInfo = {
              nickName: res.user.nickName,
              avatar: res.user.avatar,
              phonenumber: res.user.phonenumber,
              department: res.user.dept.deptName, // 部门
              job: res.user.job, // 岗位
              userType: res.user.userType, // 用户类型
              parentUuid: res.user.parentUuid, // 上级uuid
              consUuid: res.sysIds[0]?.consUuid, // 企业uuid
              supUuid: res.sysIds[0]?.supUuid, // 供应商uuid
              subUuid: res.sysIds[0]?.subUuid, // 分包商uuid
              uuid: res.sysIds[0]?.uuid, // 用户uuid
              userId: res.user.userId, // 用户id
              constructionId: res.user.constructionId // 企业id
            }
            // 保存用户信息
            uni.setStorageSync('userInfo', userInfo)
            uni.setStorageSync('tabbarValue', 1)
            this.showTabbar = true
          }
        })
        .catch(err => {
          console.log('获取用户信息失败', err)
        })
    },
    // 搜索
    handleSearch(value) {
      console.log('搜索', value)
      // 去除空格
      value = value.trim()
      // 搜索关键字有匹配name中字段的则显示, 否则隐藏
      this.projList.forEach(item => {
        if (item.name.includes(value)) {
          item.isShowItem = true
        } else {
          item.isShowItem = false
        }
      })
      this.educationList.forEach(item => {
        if (item.name.includes(value)) {
          item.isShowItem = true
        } else {
          item.isShowItem = false
        }
      })
      this.hiddenDangerList.forEach(item => {
        if (item.name.includes(value)) {
          item.isShowItem = true
        } else {
          item.isShowItem = false
        }
      })
      this.violationList.forEach(item => {
        if (item.name.includes(value)) {
          item.isShowItem = true
        } else {
          item.isShowItem = false
        }
      })
      this.safetyList.forEach(item => {
        if (item.name.includes(value)) {
          item.isShowItem = true
        } else {
          item.isShowItem = false
        }
      })
    },
    // 点击调用扫码
    handleScanCode() {
      console.log('扫码')
      // 获取当前时间 并将格式转换为 yyyy-MM-dd HH:mm:ss
      const date = new Date()
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      const startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      // 调用uniapp的扫码接口
      console.log('🚀 ~ handleScanCode ~ startTime:', startTime)
      uni.scanCode({
        onlyFromCamera: true,
        success: async res => {
          console.log('扫码结果', res)
          console.log('扫码结果', res.result)
          const qrCodeUuid = res.result
          console.log('🚀 ~ handleScanCode ~ qrCodeUuid:', qrCodeUuid)
          if (!qrCodeUuid) {
            uni.showToast({
              title: '请扫描正确的二维码',
              icon: 'none'
            })
            return
          }
          try {
            const res = await trainingSign({ qrCodeUuid: qrCodeUuid, startTime: startTime })
            console.log('🚀 ~ handleSign ~ res:', res)
            if (res.code === 200) {
              uni.showToast({
                title: '签到成功',
                icon: 'success'
              })
            }
          } catch (error) {
            console.log('🚀 ~ handleSign ~ error:', error)
          }
        },
        fail: err => {
          console.log('扫码失败', err)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  padding-top: 60px;
  width: 100%;
  background: linear-gradient(96deg, #5293ff 0%, #3addc8 100%);

  .header {
    display: flex;
    justify-content: flex-end;
    .message {
      width: 18px;
      height: 18px;
      background: url('/static/images/imgs/message.png') no-repeat center;
      background-size: cover;
    }
    .scan-code {
      margin: 0 20px 16px;
      width: 18px;
      height: 18px;
      background: url('/static/images/imgs/scan-code.png') no-repeat center;
      background-size: cover;
    }
  }

  .content-wrapper {
    width: 100%;
    height: 88vh;
    background: #ffffff;
    box-shadow: 0px -1px 3px 0px rgba(56, 136, 255, 0.1);
    border-radius: 32px 32px 0px 0px;

    .search-wrapper {
      padding: 24px 16px 58px;
    }
  }
}
</style>
