<template>
  <div class="home" :style="pageStyle">
    <div class="use">
      <el-segmented v-model="valueTop" :options="optionsTop" size="large" />
      <el-scrollbar v-if="valueTop=='我的常用'">
        <div class="icon-wrap">
          <div class="icon-item" @click="handleGridDataStatistics" v-hasPermi="['home:gridDataStatistics']">
            <Icon :icon="'ep:copy-document'" :size="56" />
            <div class="text">院区数据统计</div>
          </div>
          <div class="icon-item" v-for="(c, index) in commonList" :key="index" @click="handleTo(c)">
            <img
              v-if="c.meta.iconImg"
              :src="c.meta.iconImg"
              class="icon"
              :style="{ background: c.meta.backgroundColor }"
            />
            <Icon :icon="c.meta.icon" :size="56" v-else-if="c.meta.icon" />
            <div class="text">{{ c.meta.title }}</div>
          </div>
          <div class="icon-item" @click="handleAddIcon">
            <img
              src="https://kyj-bucket.oss-cn-hangzhou.aliyuncs.com/6794863b96977762288be1534f037af7c4d159711456f1fef3c984a74feb9fa4.png"
              class="icon"
              style="background: #8f80ff"
            />
            <div class="text">添加</div>
          </div>

        </div>
      </el-scrollbar>
      <div v-if="valueTop=='院内统计'" class="statistics-panel">
        <!-- 院内动态 -->
        <div class="stat-row">
          <div class="stat-label blue">
            <Icon icon="ep:house" class="stat-icon" />
            <span>院内动态</span>
          </div>
          <div class="stat-items">
            <div class="stat-item">
              <span class="stat-name">总床位数：</span>
              <span class="stat-value">400</span>
              <span class="stat-unit">张</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">在院人数：</span>
              <span class="stat-value">352</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">新收人数：</span>
              <span class="stat-value">0</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">请假人数：</span>
              <span class="stat-value">9</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">当天请假人数：</span>
              <span class="stat-value">0</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">退院人数：</span>
              <span class="stat-value">0</span>
              <span class="stat-unit">位</span>
            </div>
          </div>
        </div>
        <!-- 护理情况 -->
        <div class="stat-row">
          <div class="stat-label green">
            <Icon icon="ep:first-aid-kit" class="stat-icon" />
            <span>护理情况</span>
          </div>
          <div class="stat-items">
            <div class="stat-item">
              <span class="stat-name">一级：</span>
              <span class="stat-value">264</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">二级：</span>
              <span class="stat-value">17</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">三级：</span>
              <span class="stat-value">22</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">一级(专陪)：</span>
              <span class="stat-value">38</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">二级(专陪)：</span>
              <span class="stat-value">1</span>
              <span class="stat-unit">位</span>
            </div>
            <div class="stat-item">
              <span class="stat-name">无费用：</span>
              <span class="stat-value">10</span>
              <span class="stat-unit">位</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-row class="mt-8px flow" :gutter="8" justify="space-between">
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px">
        <el-skeleton :loading="loading" animated>
          <div class="box">
            <div class="header">
              <div class="title"
                >待审批事项 <span class="num">{{  }}</span></div>
              <div class="all" @click="handleAll">全部<Icon icon="ep:arrow-right" /></div>
            </div>
            <div class="content">
              <ul
                v-infinite-scroll="loadToDoList"
                class="infinite-list"
                :infinite-scroll-disabled="todoDisabled"
              >
                <li v-for="(item, i) in todoList" :key="i" class="item" @click="handleOpen(item)">
                  <div class="left">
                    <span class="title">{{ item.templateContent }}</span>
                    <span class="desc">{{ item.userBpmContent }}</span>
                    <span class="time">{{
                      formatTime(item.createTime, 'yyyy-MM-dd HH:mm:ss')
                    }}</span>
                  </div>
                  <div class="right"><Icon icon="ep:arrow-right" /></div>
                </li>
                <p v-if="todoLoading" class="grey">加载中...</p>
                <p v-if="todoNoMore" class="grey">没有更多数据...</p>
              </ul>
            </div>
          </div>
        </el-skeleton>
      </el-col>
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-8px">
        <el-skeleton :loading="loading" animated :throttle="{ leading: 500, trailing: 500, initVal: true }">
          <div class="box">
            <div class="header">
              <div class="title"
                >待办事项 <span class="num">{{  }}</span></div
              >
              <div class="all" @click="handleAllNew">全部<Icon icon="ep:arrow-right" /></div>
            </div>
            <div class="content">
              <ul
                v-infinite-scroll="loadMyList"
                class="infinite-list"
                :infinite-scroll-disabled="myDisabled"
              >
                <li v-for="(item, i) in myList" :key="i" class="item" @click="handleGoTo(item)">
                  <div class="left">
                    <span class="title">{{ item.templateContent }}</span>
                    <span class="desc">{{ item.userBpmContent }}</span>
                    <span class="time">{{
                      formatTime(item.createTime, 'yyyy-MM-dd HH:mm:ss')
                    }}</span>
                  </div>
                  <div class="right" @click="handleOpen(item)"><Icon icon="ep:arrow-right" /></div>
                </li>
                <p v-if="myLoading" class="grey">加载中...</p>
                <p v-if="myNoMore" class="grey">没有更多数据...</p>
              </ul>
            </div>
          </div>
        </el-skeleton>
      </el-col>
    </el-row>

    <MyCommon ref="commonRef" @success="handleGetIcon" />

    <el-drawer
      class="process-drawer"
      title="审批"
      v-model="settingVisible"
      size="60%">
      <ProcessDetail :id="processId" isHome :taskName="currentItem.templateContent" />
  </el-drawer>

  <MessageDrawer v-model="messageVisible"/>

  <el-dialog
    v-model="statsDialogVisible"
    title="院区运营数据统计"
    width="520px"
    destroy-on-close
  >
    <div v-loading="statsLoading" style="min-height: 220px; line-height: 2; white-space: pre-line">
      {{ statsText }}
    </div>
    <template #footer>
      <el-button @click="handleCopyStatistics">复制</el-button>
      <el-button type="primary" @click="statsDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import { pieOptions, barOptions } from './echarts-data'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { useAppStore } from '@/store/modules/app'
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'
import { getBpmListCount } from '@/api/bpm/processInstance'
import * as ElderlyInfoApi from '@/api/elderly/elder/elderly-Info'
import { ElMessage } from 'element-plus'
import MessageDrawer from './components/message-drawer.vue'
import ProcessDetail from '@/views/bpm/task/process-list/detail.vue'
import MyCommon from './MyCommon.vue'
defineOptions({ name: 'Home' })
const { push } = useRouter()
const { t } = useI18n()
const userStore = useUserStore()
const optionsTop = ['我的常用',
  //'院内统计'
]
const valueTop = ref('我的常用')
const { setWatermark } = useWatermark()
const loading = ref(false)
const processId = ref('')
const settingVisible = ref(false)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
const appStore = useAppStore()
const breakpoints = useBreakpoints(breakpointsTailwind)
const sm = breakpoints.smaller('sm')
const md = breakpoints.between('sm', 'md')
const lg = breakpoints.between('md', 'lg')
const xl = breakpoints.between('lg', 'xl')
const xxl = breakpoints.between('xl', '2xl')
const xxxl = breakpoints['2xl']
const messageVisible = ref(false)
const statsDialogVisible = ref(false)
const statsLoading = ref(false)
const statsText = ref('')
const router = useRouter()

const buildStatsText = (data: Record<string, any>) => {
  const lines = [
    `1、院名：${data?.institutionName ?? '-'}`,
    `2、本周期初数：${data?.periodBeginCount ?? 0}`,
    `3、本周入住数：${data?.weeklyCheckInCount ?? 0}`,
    `4、本周退住数：${data?.weeklyCheckOutCount ?? 0}`,
    `5、本月入住数：${data?.monthlyCheckInCount ?? 0}`,
    `6、本月退住数：${data?.monthlyCheckOutCount ?? 0}`,
    `7、本周期末数：${data?.periodEndCount ?? 0}`,
    `8、本周净增长长者数：${data?.weeklyNetGrowthCount ?? 0}`,
    `9、本月净增长长者数合计：${data?.monthlyNetGrowthCount ?? 0}`,
    `10、本周期末院内空余床位数：${data?.periodEndEmptyBedCount ?? 0}`
  ]
  return lines.join('\n')
}

const handleGridDataStatistics = async () => {
  statsDialogVisible.value = true
  statsLoading.value = true
  try {
    const res = await ElderlyInfoApi.getWeeklyOperationSummary()
    const data = res?.data ?? res
    statsText.value = buildStatsText(data || {})
  } catch (error) {
    statsText.value = ''
    ElMessage.error('获取运营数据失败')
  } finally {
    statsLoading.value = false
  }
}

const handleCopyStatistics = async () => {
  if (!statsText.value) {
    ElMessage.warning('暂无可复制内容')
    return
  }
  try {
    await navigator.clipboard.writeText(statsText.value)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 页面宽度
const pageStyle = computed(() => {
  // if(appStore.newScene){
  if (sm.value) {
    return { padding: '15px 10px' }
  } else if (md.value) {
    return { padding: '15px 20px' }
  } else if (lg.value) {
    return { padding: '15px 50px' }
  } else if (xl.value) {
    return { padding: '15px 80px' }
  } else if (xxl.value) {
    return { padding: '15px 120px' }
  } else if (xxxl.value) {
    return { padding: '15px 150px' }
  }
  // }
})

// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const data = [
    {
      name: 'ruoyi-vue-pro',
      icon: 'akar-icons:github-fill',
      message: 'https://github.com/YunaiV/ruoyi-vue-pro',
      personal: 'Spring Boot 单体架构',
      time: new Date()
    },
    {
      name: 'yudao-ui-admin-vue3',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-vue3',
      personal: 'Vue3 + element-plus',
      time: new Date()
    },
    {
      name: 'yudao-ui-admin-vben',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-vben',
      personal: 'Vue3 + vben(antd)',
      time: new Date()
    },
    {
      name: 'yudao-cloud',
      icon: 'akar-icons:github',
      message: 'https://github.com/YunaiV/yudao-cloud',
      personal: 'Spring Cloud 微服务架构',
      time: new Date()
    },
    {
      name: 'yudao-ui-mall-uniapp',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-uniapp',
      personal: 'Vue3 + uniapp',
      time: new Date()
    },
    {
      name: 'yudao-ui-admin-vue2',
      icon: 'logos:vue',
      message: 'https://github.com/yudaocode/yudao-ui-admin-vue2',
      personal: 'Vue2 + element-ui',
      time: new Date()
    }
  ]
  projects = Object.assign(projects, data)
}

// 获取通知公告
let notice = reactive<Notice[]>([])
const getNotice = async () => {
  const data = [
    {
      title: '系统支持 JDK 8/17/21，Vue 2/3',
      type: '通知',
      keys: ['通知', '8', '17', '21', '2', '3'],
      date: new Date()
    },
    {
      title: '后端提供 Spring Boot 2.7/3.2 + Cloud 双架构',
      type: '公告',
      keys: ['公告', 'Boot', 'Cloud'],
      date: new Date()
    },
    {
      title: '全部开源，个人与企业可 100% 直接使用，无需授权',
      type: '通知',
      keys: ['通知', '无需授权'],
      date: new Date()
    },
    {
      title: '国内使用最广泛的快速开发平台，超 300+ 人贡献',
      type: '公告',
      keys: ['公告', '最广泛'],
      date: new Date()
    }
  ]
  notice = Object.assign(notice, data)
}

// 获取快捷入口
let shortcut = reactive<Shortcut[]>([])

const getShortcut = async () => {
  const data = [
    {
      name: 'Github',
      icon: 'akar-icons:github-fill',
      url: 'github.io'
    },
    {
      name: 'Vue',
      icon: 'logos:vue',
      url: 'vuejs.org'
    },
    {
      name: 'Vite',
      icon: 'vscode-icons:file-type-vite',
      url: 'https://vitejs.dev/'
    },
    {
      name: 'Angular',
      icon: 'logos:angular-icon',
      url: 'github.io'
    },
    {
      name: 'React',
      icon: 'logos:react',
      url: 'github.io'
    },
    {
      name: 'Webpack',
      icon: 'logos:webpack',
      url: 'github.io'
    }
  ]
  shortcut = Object.assign(shortcut, data)
}

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 335, name: 'analysis.directAccess' },
    { value: 310, name: 'analysis.mailMarketing' },
    { value: 234, name: 'analysis.allianceAdvertising' },
    { value: 135, name: 'analysis.videoAdvertising' },
    { value: 1548, name: 'analysis.searchEngines' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const handleAll = () => {
  push({
    name: 'BpmProcessList',
    query: {
      activeName: '1'
    }
  })
}

const handleAllNew = () => {
  messageVisible.value = true
}

const handleGoTo = (item) => {
  router.push(item.gotoUrl)
}

const currentItem = ref({})
const handleOpen = (row) => {
  processId.value = row.processInstanceId
  currentItem.value = row
  settingVisible.value = true
}

// 获取待审批列表
const params = reactive({
  pageNo: 1,
  pageSize: 10,
  businessType: 1,
  queryType: 1
})
const todoTotal = ref(0)
const todoList = ref([])
const todoLoading = ref(false)
const todoDisabled = computed(() => todoLoading.value || todoNoMore.value)
const getTodoList = async () => {
  try {
    todoLoading.value = true
    const data = await ProcessInstanceApi.getMyPage(params)
    todoList.value = todoList.value.concat(data.list)
  } finally {
    todoLoading.value = false
  }
}
const todoNoMore = computed(() => todoList.value.length == todoTotal.value)
const loadToDoList = () => {
  if(params.pageNo * params.pageSize < todoTotal.value){
    params.pageNo += 1
    getTodoList()
  }
}

// 获取待办列表
const myParams = reactive({
  pageNo: 1,
  pageSize: 10,
  businessType: 0,
  queryType: 5
})
const myTotal = ref(0)
const myList = ref([])
const myLoading = ref(false)
const myDisabled = computed(() => myLoading.value || myNoMore.value)
const getMyList = async () => {
  // loading.value = true
  try {
    const data = await ProcessInstanceApi.getMyPage(myParams)
    myList.value = myList.value.concat(data.list)
    myTotal.value = data.total
  } finally {
    // loading.value = false
  }
}
const myNoMore = computed(() => myList.value.length == myTotal.value)
const loadMyList = () => {
  myParams.pageNo += 1
  getMyList()
}

// 我的常用
const commonList = ref([])

const handleTo = (item) => {
  router.push({ name: item.name })
}

const handleGetIcon = (val) => {
  commonList.value = val
}

const commonRef = ref()
const handleAddIcon = async () => {
  nextTick(() => {
    commonRef.value.init(commonList.value)
  })
}

// 获取未读数量
const getTodoCount = async () => {
  const res = await ProcessInstanceApi.getBpmListCount({queryType: 0})
  todoTotal.value = res.todoCount
}

onMounted(() => {
  getTodoList()
  getMyList()
  getTodoCount()
  commonList.value = JSON.parse(localStorage.getItem('common-icon')) || []
})
</script>
<style lang="scss" scoped>
.new-scene {
  padding: 15px 240px;
}
.home {
  .use {
    padding: 13px 17px;
    background: linear-gradient(181deg, #dde7ff 0%, #f1f5ff 100%);
    border-radius: 12px;
    border: 1px solid;
    border-image: linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0)) 1 1;
    box-sizing: border-box;
    .title {
      font-weight: 600;
      font-size: 16px;
      color: #000000;
    }
    .statistics-panel {
      margin-top: 15px;
      padding: 16px;
      background: #fff;
      border-radius: 8px;
      .stat-row {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #e8e8e8;
        &:last-child {
          border-bottom: none;
        }
        .stat-label {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100px;
          height: 36px;
          border-radius: 4px;
          color: #fff;
          font-size: 14px;
          font-weight: 500;
          flex-shrink: 0;
          &.blue {
            background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
          }
          &.green {
            background: linear-gradient(135deg, #52c41a 0%, #95de64 100%);
          }
          .stat-icon {
            margin-right: 6px;
            font-size: 16px;
          }
        }
        .stat-items {
          display: flex;
          flex: 1;
          justify-content: space-around;
          padding-left: 20px;
          .stat-item {
            display: flex;
            align-items: center;
            font-size: 14px;
            .stat-name {
              color: #666;
            }
            .stat-value {
              color: #1890ff;
              font-size: 18px;
              font-weight: 600;
              margin: 0 4px;
            }
            .stat-unit {
              color: #999;
            }
          }
        }
      }
    }
    .icon-wrap {
      display: grid;
      grid-template-columns: repeat(11, 1fr);
      gap: 20;
      margin-top: 15px;
      padding: 16px;
      box-sizing: border-box;
      .icon-item {
        min-width: 100px;
        text-align: center;
        cursor: pointer;
        .icon {
          width: 56px;
          height: 56px;
          border-radius: 16px;
          margin-bottom: 4px;
        }
        .text {
          margin-top: 12px;
          font-weight: 400;
          font-size: 16px;
          color: #2a2f42;
        }
      }
    }
  }
  .flow {
    .box {
      box-sizing: border-box;
      padding: 20px;
      border: 2px solid #fff;
      border-radius: 10px;
      background-color: #f2f6fc;
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 16px;
        .title {
          font-size: 18px;
          font-weight: bolder;
          .num {
            color: var(--el-color-danger);
          }
        }
        .all {
          display: flex;
          background-color: #f2f6fc;
          align-items: center;
          cursor: pointer;
        }
      }
      .content {
        margin-top: 15px;
        .infinite-list {
          padding: 0;
          margin: 0;
          list-style: none;
          height: 380px;
          overflow: hidden;
          overflow-y: auto;
        }
        .item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px;
          margin-bottom: 10px;
          background-color: #fff;
          border-radius: 10px;
          cursor: pointer;
          .left {
            display: flex;
            flex-direction: column;
            overflow: hidden; /* 隐藏溢出内容 */
            .title {
              font-size: 16px;
              font-weight: bold;
              margin-bottom: 10px;
              overflow: hidden;
              text-overflow: ellipsis; /* 当文本溢出时显示省略号 */
              white-space: nowrap; /* 禁止文本换行 */
            }
            .desc {
              font-size: 14px;
            }
            .time {
              font-size: 16px;
              margin-top: 10px;
              color: #666;
            }
          }
          .right {
            cursor: pointer;
          }
        }
      }
    }
    .grey {
      font-size: 12px;
      margin-top: 10px;
      color: #999999;
      text-align: center;
    }
  }
  ::-webkit-scrollbar {
    width: 3px; //滚动条宽度
  }
  ::-webkit-scrollbar-thumb {
    //上层
    border-radius: 10px; //滚动条圆弧半径
    //-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);	//滚动条阴影
    background: var(--el-border-color-dark); //背景颜色
  }
  ::-webkit-scrollbar-track {
    //底层
    //-webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: #f7f8fa;
  }
}
</style>
<style lang="scss">
.home {
  .use {
    .el-scrollbar {
      .is-vertical {
        display: none !important;
      }
    }
  }
}
</style>
