<template>
  <div class="payable-detail-page">
    <van-nav-bar
        title="应付详情"
        left-arrow
        @click-left="goBack"
    />

    <van-loading v-if="detailLoading" class="loading-container" size="24px">
      加载中...
    </van-loading>

    <div v-else class="page-content">
      <div class="header-info">
        <div class="title">{{ currentPayable.paymentBillCode || '未知编号' }}</div>
        <div class="status-badge" :class="isReadOnly ? 'completed' : 'pending'">
          {{ isReadOnly ? '已审批' : '待审批' }}
        </div>
      </div>

      <van-tabs v-model:active="activeTab" sticky>
        <!-- Tab 1: 付款信息 -->
        <van-tab title="付款信息" name="info">
          <div class="info-card">
            <div class="card-title">基本信息</div>
            <div class="info-row">
              <span class="label">付款单编号</span>
              <span class="value">{{ currentPayable.paymentBillCode }}</span>
            </div>
            <div class="info-row">
              <span class="label">制造商名称</span>
              <span class="value">{{ currentPayable.vendorName }}</span>
            </div>
            <div class="info-row">
              <span class="label">付款条件</span>
              <span class="value">{{ currentPayable.payType }}</span>
            </div>
            <div class="info-row">
              <span class="label">付款周期</span>
              <span class="value">{{ currentPayable.payConfigDay }}</span>
            </div>
            <div class="info-row">
              <span class="label">含税总价</span>
              <span class="value amount">{{ formatAmount(currentPayable.totalPriceWithTax) }}</span>
            </div>
            <div class="info-row">
              <span class="label">未税总价</span>
              <span class="value">{{ formatAmount(currentPayable.totalPriceWithoutTax) }}</span>
            </div>
            <div class="info-row">
              <span class="label">税额</span>
              <span class="value">{{ formatAmount(currentPayable.taxAmount) }}</span>
            </div>
            <div class="info-row">
              <span class="label">支付方式</span>
              <span class="value">{{ formatDictLabel(paymentMethodOptions, currentPayable.paymentMethod) }}</span>
            </div>
            <div class="info-row">
              <span class="label">银行账号</span>
              <span class="value">{{ currentPayable.payBankNumber }}</span>
            </div>
            <div class="info-row">
              <span class="label">账户名称</span>
              <span class="value">{{ currentPayable.payName }}</span>
            </div>
            <div class="info-row">
              <span class="label">银行开户行</span>
              <span class="value">{{ currentPayable.payBankOpenAddress }}</span>
            </div>
            <div class="info-row">
              <span class="label">银行行号</span>
              <span class="value">{{ currentPayable.bankNumber }}</span>
            </div>
            <div class="info-row">
              <span class="label">特别说明</span>
              <span class="value">{{ currentPayable.remark }}</span>
            </div>
          </div>
        </van-tab>

        <!-- Tab 2: 应付单列表 -->
        <van-tab title="应付单列表" name="list">
          <div class="detail-list-container">
            <div v-if="currentPayable.payableDetails && currentPayable.payableDetails.length > 0">
              <div
                  v-for="(item, index) in currentPayable.payableDetails"
                  :key="index"
                  class="detail-item"
              >
                <div class="item-header">
                  <span class="code">应付单信息</span>
                  <span class="amount">{{ formatAmount(item.paymentAmount) }}</span>
                </div>
                <div class="item-body">
                  <div class="info-row">
                    <span class="label">应付单编号：</span>
                    <span class="value">{{ item.payableBillCode }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">项目名称：</span>
                    <span class="value">{{ item.projectName }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">产品类型：</span>
                    <span class="value">{{ formatDictLabel(productTypeOptions, item.productType) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">含税总价：</span>
                    <span class="value">{{ formatAmount(item.totalPriceWithTax) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">本次付款金额：</span>
                    <span class="value">{{ formatAmount(item.paymentAmount) }}</span>
                  </div>
                </div>
              </div>
            </div>
            <van-empty v-else description="暂无应付单数据"/>
          </div>
        </van-tab>
      </van-tabs>

      <!-- Approval Action Bar -->
      <div v-if="!isReadOnly" class="action-bar">
        <van-button type="danger" block plain @click="showApprovalDialog(0)">驳回</van-button>
        <van-button type="primary" block @click="showApprovalDialog(1)">通过</van-button>
      </div>
    </div>

    <!-- Approval Dialog -->
    <van-popup v-model:show="showDialog" position="bottom" round>
      <div class="dialog-content">
        <div class="dialog-header">
          <span>{{ actionType === 1 ? '审批通过' : '审批驳回' }}</span>
          <van-icon name="cross" @click="showDialog = false"/>
        </div>
        <div class="dialog-body">
          <!-- 默认意见标签 -->
          <div class="opinion-tags">
            <div class="tags-title">常用意见</div>
            <div class="tags-container">
              <van-tag
                  v-for="tag in getOpinionTags()"
                  :key="tag"
                  :type="selectedTag === tag ? 'primary' : 'default'"
                  size="medium"
                  @click="selectTag(tag)"
                  class="opinion-tag"
              >
                {{ tag }}
              </van-tag>
            </div>
          </div>

          <van-field
              v-model="comment"
              rows="3"
              autosize
              type="textarea"
              placeholder="请输入审批意见"
          />
        </div>
        <div class="dialog-footer">
          <van-button block type="primary" :loading="submitting" @click="submit">
            提交
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, computed} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {storeToRefs} from 'pinia'
import {useFinanceStore} from '@/store/finance'
import {formatAmount} from '@/utils'
import {showToast, showSuccessToast} from 'vant'
import http from '@/utils/http'
import {getDicts, type DictData} from '@/api/system'

const route = useRoute()
const router = useRouter()
const financeStore = useFinanceStore()
const {currentPayable, currentPayableTodo, detailLoading} = storeToRefs(financeStore)

const activeTab = ref('info')
const showDialog = ref(false)
const actionType = ref(1) // 1: pass, 0: reject
const comment = ref('')
const submitting = ref(false)
const selectedTag = ref('')

const paymentMethodOptions = ref<DictData[]>([])
const productTypeOptions = ref<DictData[]>([])

const isReadOnly = computed(() => route.query.readonly === 'true')

const goBack = () => {
  router.back()
}

// 字典翻译
const formatDictLabel = (datas: DictData[], value: string | undefined) => {
  if (!value) return ''
  const action = datas.find(d => d.dictValue === value)
  return action ? action.dictLabel : value
}

const loadDicts = async () => {
  try {
    const [paymentRes, productRes] = await Promise.all([
      getDicts('payment_method'),
      getDicts('product_type')
    ])

    if (paymentRes.data.code === 0) {
      paymentMethodOptions.value = paymentRes.data.data || []
    }
    if (productRes.data.code === 0) {
      productTypeOptions.value = productRes.data.data || []
    }
  } catch (error) {
    console.error('加载字典数据失败', error)
  }
}

const showApprovalDialog = (type: number) => {
  actionType.value = type
  comment.value = '' // Clear comment initially
  selectedTag.value = '' // Clear selected tag
  showDialog.value = true
}

// 获取默认意见标签
const getOpinionTags = () => {
  if (actionType.value === 0) {
    // 驳回常用意见
    return ['经审查有问题,驳回']
  } else {
    // 通过常用意见
    return ['所有信息已阅,审核通过']
  }
}

// 选择标签
const selectTag = (tag: string) => {
  if (selectedTag.value === tag) {
    // 如果点击的是已选中的标签,则取消选择并清空输入框
    selectedTag.value = ''
    comment.value = ''
  } else {
    // 选择新标签并填入输入框
    selectedTag.value = tag
    comment.value = tag
  }
}

const submit = async () => {
  if (!comment.value && actionType.value === 0) {
    showToast('请输入驳回意见')
    return
  }

  // 优先从列表传递的 taskId 获取
  const taskId = (route.query.taskId as string) || currentPayableTodo.value?.taskId;

  if (!taskId && !isReadOnly.value) {
    showToast('无法获取审批任务ID')
    return
  }

  submitting.value = true
  try {
    await http.post('/flow/todo/approve', {
      taskId: taskId,
      processKey: 'finance_payment',
      businessKey: currentPayable.value.paymentBillCode, // Updated to use paymentBillCode
      variables: {
        approveBtn: actionType.value,
        comment: comment.value
      }
    })
    showSuccessToast('审批成功')
    showDialog.value = false
    router.back()
  } catch (e) {
    console.error(e)
    showToast('审批失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  const paymentBillCode = route.params.paymentBillCode
  if (paymentBillCode) {
    financeStore.fetchPayableDetail(paymentBillCode as string)
  }
  loadDicts()
})
</script>

<style lang="scss" scoped>
.payable-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

.loading-container {
  text-align: center;
  padding: 50px;
}

.header-info {
  background: #fff;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;

  .title {
    font-size: 18px;
    font-weight: 600;
  }

  .status-badge {
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;

    &.pending {
      background: #fff7e6;
      color: #fa8c16;
    }

    &.completed {
      background: #f6ffed;
      color: #52c41a;
    }
  }
}

.info-card {
  background: #fff;
  margin: 12px 0;
  padding: 16px;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    border-left: 4px solid #1989fa;
    padding-left: 8px;
  }

  .info-row {
    display: flex;
    margin-bottom: 12px;
    font-size: 14px;

    .label {
      color: #666;
      width: 100px;
      flex-shrink: 0;
    }

    .value {
      flex: 1;
      color: #333;
      word-break: break-all;
      text-align: right;
    }

    .amount {
      color: #f5222d;
      font-weight: 500;
    }
  }
}

.detail-list-container {
  padding: 12px;

  .detail-item {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 12px;

    .item-header {
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #f0f0f0;
      padding-bottom: 8px;
      margin-bottom: 8px;

      .code {
        font-weight: 600;
        font-size: 15px;
      }

      .amount {
        color: #f5222d;
        font-weight: 500;
      }
    }

    .item-body {
      .info-row {
        display: flex;
        margin-bottom: 6px;
        font-size: 13px;

        .label {
          color: #666;
          width: 150px;
        }

        .value {
          flex: 1;
          color: #333;
          word-break: break-all;
        }
      }
    }
  }
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 16px;
  z-index: 99;
}

.dialog-content {
  padding: 16px;

  .dialog-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 600;
  }

  .dialog-footer {
    margin-top: 16px;
  }
}

// 意见标签样式
.opinion-tags {
  margin-bottom: 12px;

  .tags-title {
    font-size: 14px;
    color: #999;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .opinion-tag {
      cursor: pointer;
      padding: 4px 12px;
      transition: all 0.2s ease;

      &:hover {
        transform: translateY(-1px);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}
</style>