<script setup lang="ts">
import type { FileItem } from '../../common/otherCharge/FileUploader.vue'
import CardContainer from '@af-mobile-client-vue3/components/data/CardContainer/CardContainer.vue'
import CardHeader from '@af-mobile-client-vue3/components/data/CardContainer/CardHeader.vue'
import OtherChargeGroupModal from '@af-mobile-client-vue3/components/data/OtherCharge/OtherChargeGroupModal.vue'
import { getConfigByNameAsync, runLogic } from '@af-mobile-client-vue3/services/api/common'
import useUserStore from '@af-mobile-client-vue3/stores/modules/user'
import {
  showDialog,
  showFailToast,
  showToast,
  Button as VanButton,
  Field as VanField,
  Icon as VanIcon,
} from 'vant'
import { computed, onMounted, reactive, ref } from 'vue'
// import { otherCharge } from '@/services/api/business'
import ChargePrintSelectorAndRemarks from '../../common/otherCharge/ChargePrintSelectorAndRemarks.vue'
import {
  CodePayment,
  FileUploader,
  GridFileUploader,
  PaymentMethodSelectorCard,
  ReceiptModal,
} from '../../common/otherCharge/index'
import OtherChargeItem from './OtherChargeItem.vue'
import OtherChargeItemModal from './OtherChargeItemModal.vue'

interface BusinessUser {
  f_workflow_id?: string
  f_userinfo_id: string
  f_userinfo_code: string
  f_user_name: string
  f_userfiles_id?: string
  f_orgid?: string
  // f_user_phone: string
  // f_user_type: string
  // f_address: string
  // f_meter_type: string
  // f_meternumber: string
  // f_balance: string
  // f_user_state: string
  // f_last_gas_date?: string
}

interface ChargeItem {
  id: number
  workOrderCode?: string
  workOrderId?: string
  type: string
  item: string
  model?: string // 添加型号字段
  unitPrice: number
  quantity: number
  total: string
}

interface ReceiptData {
  transactionId: string
  userName: string
  userId: string
  cardNo: string
  items: ChargeItem[]
  totalAmount: string
  paymentMethod: string
  remarks: string
  operator: string
  dateTime: string
}

// 收费类型配置接口
interface ModelItem {
  name: string
  price?: number
}

interface ItemType {
  name: string
  children?: ModelItem[]
}

interface ChargeTypeCategory {
  name: string
  children: ItemType[]
}

interface ChargeTypeConfig {
  value: ChargeTypeCategory[]
}

// 添加其他收费配置接口
interface OtherChargeConfig {
  hasPrint: boolean
  printType: string
  payment: string
  allowedMethods: string[] | null
  floor: boolean
  calculatePreByCollection: boolean
  printLogic: string
  submitLogic: string
  updatePriceRoles: string[]
  fileTypes?: {
    userType: string
    picMinNum: number
    description?: string
  }[]
}

// 接收用户信息prop
const props = defineProps<{
  user?: BusinessUser
  isWorkOrder?: boolean
  workOrderData?: any
  serviceName?: string
  showGroup?: boolean
}>()

const emit = defineEmits<{
  (e: 'closeOperation'): void
  (e: 'complete'): void
}>()

// 获取操作员信息
const currUser = useUserStore().getLogin().f

// 组件状态
const chargeItems = ref<ChargeItem[]>([])
const paymentMethod = ref('现金缴费') // 默认支付方式，会被配置覆盖
const receiptType = ref('普通收据')
const remarks = ref('')
const fileList = ref<FileItem[]>([])
const showAddItemModal = ref(false)
const showQrCodePayment = ref(false)
// 材料组相关状态
const showAddGroupModal = ref(false)
// 子组件的响应组件引用
const printRef = ref()
// 收费类型数据
const chargeTypeConfig = reactive<ChargeTypeConfig>({
  value: [],
})
// 配置数据
const config = reactive<Partial<OtherChargeConfig>>({
  payment: '现金缴费',
  allowedMethods: null,
  printLogic: '',
  fileTypes: [],
  submitLogic: '',
  updatePriceRoles: [],
})
// 判断当前用户是否是更新价格角色
const isUpdatePriceRole = computed(() => {
  // 检查配置是否存在且不为空数组
  if (!Array.isArray(config.updatePriceRoles) || config.updatePriceRoles.length === 0) {
    return false
  }

  // 检查用户角色信息是否存在
  if (!currUser?.resources?.f_role_name || typeof currUser.resources.f_role_name !== 'string') {
    return false
  }

  // 如果配置中包含"全部"角色，直接返回true
  if (config.updatePriceRoles.includes('全部')) {
    return true
  }

  // 分割用户角色字符串并清理空值
  const userRoles = currUser.resources.f_role_name
    .split(' ')
    .map(role => role.trim())
    .filter(role => role.length > 0)

  // 检查用户角色是否在配置的角色列表中
  return config.updatePriceRoles.some(role =>
    userRoles.includes(role),
  )
})

const gridFileUploaderRef = ref()

// 判断是否使用宫格上传组件
const useGridUploader = computed(() => {
  return config.fileTypes && config.fileTypes.length > 0
})

// 是否显示添加材料组按钮
const showAddGroupButton = computed(() => {
  return props.showGroup ?? false
})
// 初始化获取配置
async function initConfig() {
  try {
    // 新的收费类型数据
    await runLogic('getMaterialInfo', {
      f_org_id: currUser.resources.orgid,
    }, 'af-revenue').then((res: any[]) => {
      // 1. 获取所有不同的 f_material_type，且不为空
      const types = Array.from(new Set(res.filter(item => item.f_material_type).map(item => item.f_material_type)))

      // 2. 组装树结构
      const materialsConfig = types.map((typeName) => {
        // 找到该类型下所有分类
        const categories = res.filter(item => item.type === '分类' && item.f_material_type === typeName)
        return {
          value: typeName,
          label: typeName,
          children: categories.map((cat) => {
            // 找到该分类下所有型号
            const models = res.filter(item => item.type === '型号' && String(item.parent_id) === String(cat.id))
            return {
              value: cat.name,
              label: cat.name,
              children: models.map(model => ({
                value: model.name,
                label: model.name,
                price: model.f_material_price,
              })),
            }
          }).filter(cat => cat.children.length > 0), // 只保留有型号的分类
        }
      }).filter(type => type.children.length > 0) // 只保留有分类的类型

      const chargeTypes = materialsConfig.map(item => ({
        name: item.label,
        children: item.children?.map(child => ({
          name: child.label,
          children: child.children?.map(model => ({
            name: model.label,
            price: model.price ? Number(model.price) : undefined,
          })) || [],
        })) || [],
      }))
      chargeTypeConfig.value = chargeTypes
      console.log('新的收费类型数据', chargeTypes)
    })
    // 获取其他收费类型配置
    const chargeConfig = await getConfigByNameAsync('mobile_otherChargeConfig', props.serviceName || import.meta.env.VITE_APP_SYSTEM_NAME)
    if (chargeConfig) {
      // 更新配置
      Object.assign(config, chargeConfig)

      // 设置默认支付方式
      if (config.payment) {
        paymentMethod.value = config.payment
      }
    }
  }
  catch (error) {
    console.error('初始化配置信息失败', error)
  }
}

// 在组件挂载时调用初始化配置函数
onMounted(async () => {
  await initConfig()
})

// 计算总金额
const totalAmount = computed(() => {
  if (chargeItems.value.length === 0)
    return '0.00'
  const total = chargeItems.value.reduce((sum, item) => sum + Number.parseFloat(item.total), 0)
  return total.toFixed(2)
})

// 收据数据
const receiptData = reactive<ReceiptData>({
  transactionId: '',
  userName: '',
  userId: '',
  cardNo: '',
  items: [],
  totalAmount: '0.00',
  paymentMethod: 'cash',
  remarks: '',
  operator: '营业员',
  dateTime: '',
})

// 计算属性获取用户信息
const userInfo = computed(() => {
  if (!props.user)
    return null
  return {
    name: props.user.f_user_name,
    id: props.user.f_userinfo_code,
    // meterNumber: props.user.f_meternumber,
  }
})

// 添加费用项
function addChargeItem(item: ChargeItem) {
  chargeItems.value.push(item)
}

// 移除费用项
function removeChargeItem(itemId: number) {
  chargeItems.value = chargeItems.value.filter(item => item.id !== itemId)
}

// 更新费用项
function updateChargeItem(updatedItem: ChargeItem) {
  const index = chargeItems.value.findIndex(item => item.id === updatedItem.id)
  if (index !== -1) {
    chargeItems.value[index] = updatedItem
  }
}

// 生成收据
function generateReceipt() {
  // 验证是否有费用项
  if (chargeItems.value.length === 0) {
    showToast('请至少添加一个费用项！')
    return
  }
  if (!paymentMethod.value) {
    showToast('请选择付款方式！')
    return
  }

  // 验证文件上传要求
  if (useGridUploader.value && gridFileUploaderRef.value) {
    const isValid = gridFileUploaderRef.value.validateAll()
    if (!isValid) {
      return
    }
  }
  // 微信/支付宝支付走单独的流程，通过事件回调处理支付结果
  if (paymentMethod.value.includes('支付宝') || paymentMethod.value.includes('微信')) {
    showQrCodePayment.value = true
  }
  // 其他支付方式直接调用收费接口进行处理
  else {
    processPayment()
  }
}

// 抽取支付处理逻辑为单独函数
async function processPayment(tradeNo = ''): Promise<any> {
  try {
    // 更新收据数据
    receiptData.items = chargeItems.value
    receiptData.totalAmount = totalAmount.value
    receiptData.paymentMethod = paymentMethod.value
    receiptData.remarks = remarks.value

    // 更新用户信息
    if (userInfo.value) {
      receiptData.userName = userInfo.value.name
      receiptData.userId = userInfo.value.id
      // receiptData.cardNo = userInfo.value.meterNumber
    }

    // 生成交易单号
    receiptData.transactionId = `OC${Date.now().toString().slice(-10)}`

    // 获取操作员信息
    const currUser = useUserStore().getLogin().f
    receiptData.operator = currUser.resources.name

    // 设置日期时间
    const now = new Date()
    receiptData.dateTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

    // 调用API提交数据
    const newChargeItems = chargeItems.value.map((item) => {
      return {
        f_work_order_id: item.workOrderId || '',
        f_service_id: item.workOrderCode || '',
        f_brand_spec: item.type,
        f_typename: item.item,
        f_typenumber: item.model,
        f_number: item.quantity,
        f_unitprice: item.unitPrice,
        f_collection: item.total,
      }
    })
    const param = {
      f_workflow_id: props.user.f_workflow_id,
      f_userinfo_id: props.user.f_userinfo_id,
      // f_serial_id: this.model.f_serial_id,
      // nopay_id: this.model.nopay_id,
      f_collection: totalAmount.value,
      f_comments: remarks.value,
      f_sale_person: currUser.resources.name,
      f_payment: paymentMethod.value,
      // f_voucher_number: this.model.f_voucher_number,
      f_bill_style: receiptType.value,
      // f_service_person: this.model.f_service_person,
      fileIds: fileList.value.map(file => file.result?.id).filter(Boolean),
      f_operator: currUser.resources.name,
      f_operatorid: currUser.resources.id,
      f_orgid: currUser.resources.orgid,
      f_orgname: currUser.resources.orgs,
      f_depid: currUser.resources.depids,
      f_depname: currUser.resources.deps,
      otherDetail: newChargeItems,
    }
    console.log('param---->', param)
    runLogic(config.submitLogic, param).then(
      async (res) => {
        await printRef.value.printParams(config.printLogic, (res as any).id)
      },
    ).catch(() => {
      showFailToast('其他收费失败')
    })
  }
  catch (error) {
    console.error(error)
    showToast(`其他收费失败${error.message || error.msg || '未知错误'}`)
    throw error
  }
}

async function handleQrCodePaymentSuccess(paymentResult) {
  try {
    // 使用公共处理函数处理支付
    await processPayment(paymentResult.tradeNo)
    showQrCodePayment.value = false
  }
  catch (error) {
    console.error(error)
  }
}

function handleQrCodePaymentCancel() {
  showQrCodePayment.value = false
}

// 取消操作
function cancelOperation() {
  showDialog({
    title: '确认取消',
    message: '是否确认取消当前收费操作？',
    showCancelButton: true,
    confirmButtonText: '确认',
    cancelButtonText: '返回',
    confirmButtonColor: '#2563eb',
  }).then((result) => {
    if (result === 'confirm') {
      emit('closeOperation')
    }
  })
}

// 文件上传相关
function onFileAdded(): void {
}

function onFileRemoved(): void {
}
</script>

<template>
  <div id="other-charge-form" class="other-charge-form">
    <!-- 信息提示 -->
    <div class="other-charge-form__info-box">
      <VanIcon name="info-o" class="other-charge-form__info-icon" />
      <div class="other-charge-form__info-content">
        <p class="other-charge-form__info-text">
          请填写收费信息，系统将自动计算应收金额。
        </p>
        <p class="other-charge-form__info-user">
          当前用户：<span class="other-charge-form__user-name">{{ userInfo ? userInfo.name : '' }}</span>
        </p>
      </div>
    </div>

    <form class="other-charge-form__container" @submit.prevent="generateReceipt">
      <!-- 费用项列表区域 -->
      <CardContainer class="other-charge-form__section-margin">
        <CardHeader title="费用项目">
          <template #extra>
            <VanButton
              v-if="showAddGroupButton"
              type="primary"
              size="small"
              icon="plus"
              plain
              @click="showAddGroupModal = true"
            >
              选择材料组
            </VanButton>
            <VanButton
              type="primary"
              size="small"
              icon="plus"
              plain
              style="margin-left: 8px;"
              @click="showAddItemModal = true"
            >
              添加费用项
            </VanButton>
          </template>
        </CardHeader>

        <div class="other-charge-form__items-container">
          <template v-if="chargeItems.length > 0">
            <OtherChargeItem
              v-for="(item, index) in chargeItems"
              :key="item.id"
              :item="item"
              :index="index"
              :is-work-order="props.isWorkOrder"
              :work-order-data="props.workOrderData"
              :is-update-price="isUpdatePriceRole"
              @remove="removeChargeItem"
              @update="updateChargeItem"
            />
          </template>
          <p v-else class="text-gray-400 text-center">
            尚未添加收费项目
          </p>
        </div>
      </CardContainer>

      <!-- 收费信息 -->
      <CardContainer class="other-charge-form__section-margin">
        <CardHeader title="收费信息" />
        <div class="other-charge-form__field">
          <label class="other-charge-form__label">应收金额</label>
          <div class="other-charge-form__amount-input">
            <VanField
              v-model="totalAmount"
              readonly
              input-align="right"
            >
              <template #prefix>
                <span class="other-charge-form__prefix">¥</span>
              </template>
              <template #suffix>
                <span class="other-charge-form__suffix">元</span>
              </template>
            </VanField>
          </div>
        </div>

        <div class="other-charge-form__field">
          <label class="other-charge-form__label">收费项目数</label>
          <div class="other-charge-form__count-input">
            <VanField
              :model-value="chargeItems.length.toString()"
              readonly
              input-align="right"
            >
              <template #suffix>
                <span class="other-charge-form__suffix">项</span>
              </template>
            </VanField>
          </div>
        </div>
      </CardContainer>

      <!-- 打印及备注 -->
      <ChargePrintSelectorAndRemarks
        v-model="receiptType"
        v-model:remarks="remarks"
        class="other-charge-form__section-margin"
      />

      <!-- 支付方式 -->
      <PaymentMethodSelectorCard
        v-model="paymentMethod"
        title="支付方式"
        :user="props.user"
        :allowed-methods="config.allowedMethods"
        class="other-charge-form__section-margin"
      />

      <!-- 文件上传区域 -->
      <!-- 宫格上传组件（多种文件类型时使用） -->
      <GridFileUploader
        v-if="useGridUploader"
        ref="gridFileUploaderRef"
        v-model:file-list="fileList"
        :file-types="config.fileTypes"
        title="上传附件"
        class="other-charge-form__section-margin"
      />
      <CardContainer
        v-else
        class="other-charge-form__section-margin"
      >
        <!-- 普通上传组件（单一文件类型或无配置时使用） -->
        <FileUploader
          v-model:file-list="fileList"
          title="上传附件"
          :multiple="true"
          :user-type="config.fileTypes && config.fileTypes.length > 0 ? config.fileTypes[0].userType : '其他收费'"
          @file-added="onFileAdded"
          @file-removed="onFileRemoved"
        />
      </CardContainer>

      <!-- 应收金额展示 -->
      <CardContainer class="other-charge-form__summary">
        <div class="other-charge-form__total-content">
          <p class="other-charge-form__total-label">
            应收金额：<span class="other-charge-form__total-value">¥ {{ totalAmount }}</span>
          </p>
          <p class="other-charge-form__total-count">
            收费项目：{{ chargeItems.length }} 项
          </p>
        </div>
      </CardContainer>

      <!-- 按钮区域 -->
      <div class="other-charge-form__buttons">
        <VanButton
          plain
          type="default"
          class="other-charge-form__cancel-btn"
          @click="cancelOperation"
        >
          取消
        </VanButton>
        <VanButton
          type="primary"
          native-type="submit"
          class="other-charge-form__confirm-btn"
          :disabled="chargeItems.length === 0"
        >
          确认收费
        </VanButton>
      </div>
    </form>

    <!-- 添加费用项弹窗 -->
    <OtherChargeItemModal
      v-model:show="showAddItemModal"
      :is-work-order="props.isWorkOrder"
      :work-order-data="props.workOrderData"
      :charge-types="chargeTypeConfig"
      @add="addChargeItem"
    />
    <!-- 添加材料组 -->
    <OtherChargeGroupModal
      v-model:show="showAddGroupModal"
      :work-order-data="props.workOrderData || []"
      :service-name="props.serviceName"
      @add="addChargeItem"
    />
    <!-- 收据弹窗 -->
    <ReceiptModal ref="printRef" @close="emit('closeOperation')" />
    <!-- 二维码支付弹窗 -->
    <CodePayment
      v-if="showQrCodePayment"
      v-model:show="showQrCodePayment"
      :payment="paymentMethod"
      :collection="totalAmount"
      :form-data="{}"
      type="其他收费"
      :user="props.user"
      @payment-success="handleQrCodePaymentSuccess"
      @payment-cancel="handleQrCodePaymentCancel"
    />
  </div>
</template>

<style scoped lang="less">
.other-charge-form {
  padding: 12px;

  &__info-box {
    display: flex;
    background: linear-gradient(to right, #ebf4ff, #e0f2fe);
    border-left: 4px solid #3b82f6;
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }

  &__info-icon {
    font-size: 20px;
    color: #3b82f6;
    margin-top: 3px;
    margin-right: 12px;
  }

  &__info-content {
    flex: 1;
  }

  &__info-text {
    margin: 0 0 4px 0;
    font-size: 14px;
    color: #1e40af;
    font-weight: 500;
  }

  &__info-user {
    margin: 0;
    font-size: 14px;
    color: #2563eb;
  }

  &__user-name {
    font-weight: 600;
  }

  &__container {
    margin-bottom: 16px;
  }

  &__main-content {
    background-color: #f9fafb;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
    padding: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    margin-bottom: 16px;
  }

  &__two-columns {
    display: grid;
    grid-template-columns: 1fr;
    gap: 16px;
    margin-bottom: 16px;

    @media (min-width: 640px) {
      grid-template-columns: 1fr 1fr;
    }
  }

  &__field {
    margin-bottom: 16px;
  }

  &__label {
    display: block;
    font-size: 12px;
    font-weight: 500;
    color: #6b7280;
    margin-bottom: 4px;
  }

  &__amount-input,
  &__count-input {
    :deep(.van-field) {
      background-color: #f9fafb;
      border-radius: 6px;
    }
  }

  &__prefix,
  &__suffix {
    color: #6b7280;
    font-size: 14px;
  }

  &__total-content {
    width: 100%;
  }

  &__total-label {
    font-size: 16px;
    font-weight: 500;
    color: #4b5563;
    margin: 0 0 4px 0;
  }

  &__total-value {
    font-size: 20px;
    font-weight: 600;
    color: #2563eb;
  }

  &__total-count {
    font-size: 14px;
    color: #6b7280;
    margin: 0;
  }

  &__buttons {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  &__cancel-btn {
    border-color: #d1d5db;
    color: #4b5563;
  }

  &__confirm-btn {
    background-color: #2563eb;
  }

  &__file-uploader {
    margin-bottom: 16px;
  }

  &__section-margin {
    margin-bottom: 16px;
  }

  &__summary {
    background: linear-gradient(to right, #ebf4ff, #e0f2fe);
    border: 1px solid #bfdbfe;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }
}
</style>
