<template>
  <div class="app-container">
    <header>
      <!-- <img :src="userInfos.avatar" alt="" /> -->
      <van-image class="mr10" width="100px" height="100px" round :src="userInfos.avatar" />
      <div class="content">
        <p class="bold">
          <van-text-ellipsis :content="`${userInfos.nickName}(信用分:${userInfos.creditScore})`" />
          <van-icon name="setting" size="20" @click="onRouterPush('/user/edit')" />
        </p>
        <p class="flex justify-between">
          <van-text-ellipsis :content="userInfos.pgName" />
        </p>
        <p>
          <van-text-ellipsis :content="userInfos.deptName" />
        </p>
      </div>
    </header>
    <div class="main">
      <!-- <ul class="links">
        <li @click="onRouterPush('/training')">培训通知</li>
        <li>我的报名</li>
        <li>我的学习</li>
        <li>我的考试</li>
      </ul> -->
      <!-- <ul>
        <li>使用指引</li>
        <li>安全积分:{{ userInfos.creditScore }}分</li>
      </ul> -->
      <div class="card">
        <h4>经费统计</h4>
        <ul class="nav">
          <!-- <li>
            <span>123,000</span>
            <p>账户余额(¥)</p>
          </li> -->
          <li @click="onRouterPush('/my-cash-flow')">
            <span>{{ billInfo.totalFlowCount }}</span>
            <p>费用流水</p>
          </li>
          <li>
            <span>{{ billInfo.currentMonthFee }}</span>
            <p>本月支出</p>
          </li>
          <li>
            <span>{{ billInfo.totalFee }}</span>
            <p>累计支出</p>
          </li>
        </ul>
      </div>
      <div class="card" @click="showFinancePopup = true">
        <h4>课题组经费统计</h4>
        <div class="balance-display">
          <span class="amount">{{ financeStats.calculatedBalance.toFixed(2) }}</span>
          <p class="label">余额(¥)</p>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
      </div>
      <div class="card" @click="showOperatingGuidelines">
        <h4>平台入室操作指引</h4>
      </div>
      <div class="card">
        <van-cell v-auth="'instr_open'" title="打开设备" is-link @click="openInst" />
        <van-cell v-auth="'instr_close'" title="关闭设备" is-link @click="closeInst" />
      </div>
    </div>
    <footer>
      <!-- <wx-open-subscribe template="-pVpM6TH1oz1cZntEhGzQjmMMODF9tLLzh_1yjjWYSk" @success="handleSubscribe">
        <component :is="'script'" type="text/wxtag-template">
          <button class="w100 ">订阅</button>
        </component>
      </wx-open-subscribe> -->
      <van-button class="w100 mt10" color="#1cb4fd" plain @click="onRouterPush('/user/password')">
        修改密码
      </van-button>
      <van-button class="w100 mt10" @click="signOut" type="primary">
        切换账号
      </van-button>
    </footer>

    <van-popup position="bottom" v-model:show="showFinancePopup" round>
      <div class="finance-detail">
        <div class="detail-header">
          <h3>经费统计详情</h3>
          <van-icon name="cross" @click="showFinancePopup = false" />
        </div>
        <div class="detail-content">
          <div class="detail-item" @click="showListPopup = true">
            <span class="label">经费卡数量</span>
            <div class="value-with-arrow">
              <span class="value">{{ financeStats.accountCount }}</span>
              <van-icon name="arrow" />
            </div>
          </div>
          <div class="detail-item">
            <span class="label">授信额度</span>
            <span class="value">¥{{ financeStats.totalCredit.toFixed(2) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">可用余额</span>
            <span class="value">¥{{ financeStats.totalBalance.toFixed(2) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">锁定金额</span>
            <span class="value">¥{{ financeStats.totalLocked.toFixed(2) }}</span>
          </div>
          <div class="detail-item highlight">
            <span class="label">最终可用额度</span>
            <span class="value">¥{{ financeStats.calculatedBalance.toFixed(2) }}</span>
          </div>
          <div class="divider"></div>
          <div class="detail-item">
            <span class="label">已出账单</span>
            <span class="value">¥{{ financeStats.totalIssued.toFixed(2) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">未出账单</span>
            <span class="value">¥{{ financeStats.totalUnpaid.toFixed(2) }}</span>
          </div>
        </div>
        <div class="detail-footer">
          <p class="formula-tip">* 计算公式：可用余额 - 锁定金额</p>
        </div>
      </div>
    </van-popup>

    <van-popup position="bottom" v-model:show="showListPopup" round closeable>
      <div class="finance-list">
        <div class="list-header">
          <h3>经费卡列表</h3>
        </div>
        <div class="list-content">
          <div v-for="item in financeList" :key="item.id" class="finance-card-item">
            <div class="card-title">
              <span class="account-no">{{ item.finAccount }}</span>
              <span class="org-name">{{ item.finOrgName }}-{{ item.projName }}</span>
            </div>
            <div class="card-details">
              <div class="grid">
                <div class="grid-item">
                  <p class="label">余额</p>
                  <p class="value">¥{{ (item.finAvailBalance-item.finLockAmount|| 0).toFixed(2) }}</p>
                </div>
                <div class="grid-item" >
                  <p class="label">可用余额</p>
                  <p class="value">¥{{ (item.finAvailBalance || 0).toFixed(2) }}</p>
                </div>
                <div class="grid-item">
                  <p class="label">授信额度</p>
                  <p class="value">¥{{ (item.finCreditLimit || 0).toFixed(2) }}</p>
                </div>
                <div class="grid-item">
                  <p class="label">锁定金额</p>
                  <p class="value">¥{{ (item.finLockAmount || 0).toFixed(2) }}</p>
                </div>
                <div class="grid-item">
                  <p class="label">已出账单</p>
                  <p class="value">¥{{ (item.finIssuedBill || 0).toFixed(2) }}</p>
                </div>
                <div class="grid-item">
                  <p class="label">未出账单</p>
                  <p class="value">¥{{ (item.finUnpaidBill || 0).toFixed(2) }}</p>
                </div>
              </div>
            </div>
          </div>
          <van-empty v-if="financeList.length === 0" description="暂无经费卡信息" />
        </div>
      </div>
    </van-popup>

    <van-popup position="bottom" v-model:show="showPopup" :style="{ padding: '20px' }">
      <div class="operation-guide">
        <div class="guide-header">
          <h3>操作指引</h3>
          <van-icon name="cross" @click="showPopup = false" />
        </div>

        <div class="steps-container">
          <div v-for="(item, index) in handleStepList" :key="item.step" class="step-item"
            :class="{ 'last-step': index === handleStepList.length - 1 }">
            <div class="step-number-wrapper">
              <div class="step-number">{{ item.step }}</div>
              <div v-if="index < handleStepList.length - 1" class="step-line"></div>
            </div>

            <div class="step-content">
              <h4 class="step-title">{{ item.title }}</h4>
              <p class="step-desc">{{ item.desc }}</p>
              <!-- <van-button
                v-if="item.btn"
                size="small"
                type="primary"
                class="step-btn"
                @click="handleStepAction(item)"
              >
                {{ item.btn }}
              </van-button> -->
            </div>
          </div>
        </div>

        <div class="guide-footer">
          <van-icon name="info-o" />
          <span>请按照步骤顺序完成操作</span>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import to from 'await-to-js'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { useRouter } from 'vue-router'

import { useUserInfo } from '/@/stores/userInfo'
import { Local, Session } from '/@/utils/storage'
import { useBillApi } from '/@/api/instr/finance/bill'
import { useLoginApi } from '/@/api/login'
import { useFinaceApi } from '/@/api/finace'

import { scanCodeWxUrl, InstSwitchType } from '/@/constants/pageConstants'

import wx from 'weixin-js-sdk'

const billApi = useBillApi()
const loginApi = useLoginApi()
const financeApi = useFinaceApi()

const router = useRouter()
const storesUseUserInfo = useUserInfo()
const { userInfos, openId } = storeToRefs(storesUseUserInfo)

const showPopup = ref<boolean>(false)
const billInfo = ref<{
  totalFlowCount: number
  currentMonthFee: number
  totalFee: number
}>({
  totalFlowCount: 0,
  currentMonthFee: 0,
  totalFee: 0,
})

const financeStats = ref({
  accountCount: 0,
  totalBalance: 0,
  totalCredit: 0,
  totalLocked: 0,
  totalIssued: 0,
  totalUnpaid: 0,
  calculatedBalance: 0, // 授信 + 可用 - 锁定
})

const financeList = ref<any[]>([])

const showFinancePopup = ref<boolean>(false)
const showListPopup = ref<boolean>(false)

const handleStepList = ref([
  {
    title: '第一步：入室培训和考试',
    desc: '请先完成入室培训，掌握必要的安全操作知识和实验室规章制度，并通过考试',
    btn: '培训报名',
    step: 1,
  },
  {
    title: '第二步：提交入室申请',
    desc: '完成入室培训考核合格后，在入室管理里面提交入室申请，等待平台管理员审核',
    btn: '前往提交',
    step: 2,
  },
  // {
  //   title: '第三步：上传入室资料',
  //   desc: '整理相关凭证并将入室资料上传到系统中',
  //   step: 3,
  // },
  {
    title: '第三步：等待审核和房间分配',
    desc: '由平台管理老师进行审核并分配细胞房或分配分子储物柜，收到审核通过的通知后，即可在申请的时段进入细胞房或分子室进行实验',
    step: 3,
  },
])

const onRouterPush = (val: string) => {
  router.push(val)
}
const signOut = () => {
  showConfirmDialog({
    message: '确认切换账号?',
  }).then(async () => {
    // 先解绑微信
    const [unbindErr]: ToResponse = await to(
      loginApi.WeChatUnBindOpenId()
    )
    // 解绑失败则终止流程
    if (unbindErr) {
      showToast('解绑失败，请重试')
      return
    }

    // 调用退出登录接口
    const [err]: ToResponse = await to(loginApi.signOut())
    if (err) {
      showToast('退出登录失败，请重试')
      return
    }

    // 清理所有本地缓存
    Local.clear()
    Session.clear()

    // 重置用户信息
    storesUseUserInfo.resetUserInfo()
    // 关闭窗口
    wx.closeWindow()
    // 跳转登录重新走授权
    // router.replace('/login')
  })
}
const handleSubscribe = (errMsg: any, subscribeDetails: any) => {
  console.log(errMsg, subscribeDetails)
}

const showOperatingGuidelines = () => {
  showPopup.value = true
}

const handleStepAction = (item: any) => {
  // Implementation of handleStepAction
}

const checkPermi = (perms: string[]) => {
  const list = userInfos.value?.authBtnList || []
  return perms.some((p) => list.includes(p))
}

const openInst = () => {
  const url = scanCodeWxUrl('START_RUN', InstSwitchType.OPEN)
  window.location.href = url
}

const closeInst = () => {
  const url = scanCodeWxUrl('END_RUN', InstSwitchType.CLOSE)
  window.location.href = url
}

// 获取个人账单信息
const getBillInfo = async () => {
  const [err, res]: ToResponse = await to(billApi.getMyOrderTotal())
  if (err) return
  billInfo.value = res?.data
}

// 获取经费卡统计信息
const getFinanceStats = async () => {
  if (!userInfos.value?.projectGroup?.id) return
  const [err, res]: ToResponse = await to(
    financeApi.getFinanceAccountList({
      projId: userInfos.value.projectGroup.id,
    })
  )
  if (err) return
  const list = res?.data?.list || []
  financeList.value = list
  const totalBalance = list.reduce((sum: number, item: any) => sum + (item.finAvailBalance || 0), 0)
  const totalCredit = list.reduce((sum: number, item: any) => sum + (item.finCreditLimit || 0), 0)
  const totalLocked = list.reduce((sum: number, item: any) => sum + (item.finLockAmount || 0), 0)
  const totalIssued = list.reduce((sum: number, item: any) => sum + (item.finIssuedBill || 0), 0)
  const totalUnpaid = list.reduce((sum: number, item: any) => sum + (item.finUnpaidBill || 0), 0)

  financeStats.value = {
    accountCount: list.length,
    totalBalance,
    totalCredit,
    totalLocked,
    totalIssued,
    totalUnpaid,
    calculatedBalance: totalBalance - totalLocked,
  }
}

onMounted(() => {
  getBillInfo()
  getFinanceStats()
})
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;

  header {
    background-color: #1c9bfd;
    color: #fff;
    padding: 10px;
    border-radius: 8px;
    margin-top: 10px;
    display: flex;

    .content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      overflow: hidden;

      .bold {
        display: flex;
        align-items: center;
        font-weight: bold;
        // flex-wrap: nowrap;
        white-space: nowrap;

        .van-text-ellipsis {
          flex: 1;
        }
      }
    }
  }

  .main {
    flex: 1;
    overflow-y: auto;

    >ul {
      display: flex;
      height: 60px;
      margin-top: 10px;

      li {
        flex: 1;
        background: #fff;
        color: #333;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;

        &+li {
          margin-left: 10px;
        }
      }

      &.links {
        li {
          color: #fff;
          background: #5eb7fc;

          &:nth-child(2) {
            background: #fd9c5e;
          }

          &:nth-child(3) {
            background: #53e3a7;
          }

          &:nth-child(4) {
            background: #888ac3;
          }
        }
      }
    }

    .card {
      margin-top: 10px;
      border-radius: 4px;
      background-color: #fff;
      padding: 10px;

      h4 {
        height: 18px;
        line-height: 18px;

        &::before {
          display: inline-block;
          content: '';
          width: 3px;
          height: 18px;
          background-color: #1c9bfd;
          margin-right: 4px;
          vertical-align: middle;
        }
      }

      .balance-display {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 15px 0;
        position: relative;

        .amount {
          font-size: 24px;
          font-weight: bold;
          color: #1c9bfd;
        }

        .label {
          font-size: 14px;
          color: #666;
          margin-top: 5px;
        }

        .arrow-icon {
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          color: #ccc;
          font-size: 18px;
        }
      }

      .nav {
        display: flex;
        margin: 10px 0;
        flex-wrap: wrap;
        justify-content: space-between;

        li {
          flex: 0 0 33.33%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;

          span {
            font-size: 16px;
            font-weight: bold;
            color: #333;
          }

          p {
            margin-top: 4px;
            font-size: 12px;
            color: #666;
          }

          &:nth-child(n + 4) {
            margin-top: 10px;
          }
        }
      }
    }
  }

  footer {
    flex: 0 0 44px;
    margin-bottom: 20px;
  }
}

:deep(.van-popup--bottom) {
  padding: 20px !important;
}

.finance-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .van-icon {
      font-size: 18px;
      color: #999;
      cursor: pointer;
    }
  }

  .detail-content {
    .detail-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      font-size: 14px;

      .label {
        color: #666;
      }

      .value {
        color: #333;
        font-weight: 500;
      }

      .value-with-arrow {
        display: flex;
        align-items: center;
        color: #1c9bfd;
        font-weight: 500;

        .van-icon {
          margin-left: 4px;
          font-size: 14px;
        }
      }

      &.highlight {
        margin-top: 5px;
        padding-top: 15px;
        border-top: 1px solid #f5f5f5;

        .label {
          color: #333;
          font-weight: 600;
        }

        .value {
          color: #1c9bfd;
          font-size: 18px;
          font-weight: bold;
        }
      }
    }

    .divider {
      height: 1px;
      background-color: #eee;
      margin: 15px 0;
    }
  }

  .detail-footer {
    margin-top: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;

    .formula-tip {
      margin: 0;
      font-size: 12px;
      color: #999;
      line-height: 1.4;
    }
  }
}

.finance-list {
  max-height: 80vh;
  display: flex;
  flex-direction: column;

  .list-header {
    padding: 20px;
    border-bottom: 1px solid #f5f5f5;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      text-align: center;
    }
  }

  .list-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px 15px 30px;

    .finance-card-item {
      background: #f8f9fa;
      border-radius: 12px;
      padding: 15px;
      margin-bottom: 12px;
      border: 1px solid #eee;

      .card-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        padding-bottom: 10px;
        border-bottom: 1px dashed #ddd;

        .account-no {
          font-size: 15px;
          font-weight: bold;
          color: #333;
        }

        .org-name {
          font-size: 12px;
          color: #1c9bfd;
          background: rgba(28, 155, 253, 0.1);
          padding: 2px 8px;
          border-radius: 4px;
        }
      }

      .card-details {
        .grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 12px;

          .grid-item {
            &.full-width {
              grid-column: span 2;
              display: flex;
              justify-content: space-between;
              align-items: center;
              border-bottom: 1px solid #eee;
              padding-bottom: 10px;
              margin-bottom: 4px;

              .label {
                margin-bottom: 0;
                font-size: 13px;
                color: #333;
                font-weight: 500;
              }

              .value {
                font-size: 16px;
                font-weight: bold;
                color: #1c9bfd;
              }
            }

            .label {
              font-size: 12px;
              color: #999;
              margin-bottom: 4px;
            }

            .value {
              font-size: 14px;
              font-weight: 500;
              color: #333;
            }
          }
        }
      }
    }
  }
}

.operation-guide {
  max-height: 70vh;
  overflow-y: auto;

  .guide-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .van-icon {
      font-size: 18px;
      color: #999;
      cursor: pointer;

      &:hover {
        color: #666;
      }
    }
  }

  .steps-container {
    .step-item {
      display: flex;
      margin-bottom: 20px;

      &.last-step {
        margin-bottom: 0;
      }

      .step-number-wrapper {
        position: relative;
        margin-right: 15px;
        display: flex;
        flex-direction: column;
        align-items: center;

        .step-number {
          width: 32px;
          height: 32px;
          background: linear-gradient(135deg, #1c9bfd, #5eb7fc);
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          font-size: 14px;
          box-shadow: 0 2px 8px rgba(28, 155, 253, 0.3);
        }

        .step-line {
          width: 2px;
          height: 40px;
          background: linear-gradient(to bottom, #1c9bfd, #e0e0e0);
          margin-top: 8px;
        }
      }

      .step-content {
        flex: 1;
        padding-top: 2px;

        .step-title {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 600;
          color: #333;
          line-height: 1.4;
        }

        .step-desc {
          margin: 0 0 12px 0;
          font-size: 14px;
          color: #666;
          line-height: 1.5;
        }

        .step-btn {
          border-radius: 20px;
          padding: 8px 16px;
          font-size: 12px;
          background: linear-gradient(135deg, #1c9bfd, #5eb7fc);
          border: none;
          box-shadow: 0 2px 8px rgba(28, 155, 253, 0.3);

          &:active {
            transform: translateY(1px);
          }
        }
      }
    }
  }

  .guide-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;

    .van-icon {
      margin-right: 6px;
      color: #1c9bfd;
      font-size: 16px;
    }

    span {
      font-size: 13px;
      color: #666;
    }
  }
}
</style>
