<template>
  <div class="xcharge-wrapper">
    <!-- 标题 -->
    <x-title :title="config.title || '结算-收费方式'" :dot="true" />
    <!-- 分割线 -->
    <div class="top-divider"></div>

    <!-- 顶部金额信息区（表单行风格，宽度固定，每行4个） -->
    <a-row :gutter="0" class="amount-info">
      <a-col v-for="item in config.amountFields" :key="item.field" :span="6" class="form-row">
        <label class="form-label">{{ item.label }}</label>
        <a-input
          v-model="data[item.field]"
          :value="data[item.field]"
          :disabled="item.disabled"
          class="form-input"
        />
      </a-col>
    </a-row>

    <!-- 支付方式选择区和支付详情容器 -->
    <div class="payment-container">
      <!-- 支付方式选择区 -->
      <div class="payment-methods">
        <div
          v-for="method in config.paymentMethods"
          :key="method.key"
          :class="['payment-option', {
            active: isMixedPaymentEnabled ? selectedMethods.includes(method.key) : selectedMethod === method.key
          }]"
          @click="isMixedPaymentEnabled ? toggleMethod(method.key) : selectMethod(method.key)"
        >
          <!-- 图标区域 -->
          <div class="payment-icon" :class="{ multiple: getMethodIcons(method).length > 1 }">
            <template v-if="getMethodIcons(method).length">
              <img
                v-for="(src, idx) in getMethodIcons(method)"
                :key="idx"
                :src="src"
                :alt="method.label"
                class="icon-image"
              />
            </template>
            <div v-else class="icon-placeholder">{{ method.label.charAt(0) }}</div>
          </div>
          <!-- 标签区域 -->
          <div class="payment-label">{{ method.label }}</div>
          <!-- 选中指示器 -->
          <div v-if="isMixedPaymentEnabled && selectedMethods.includes(method.key)" class="selected-indicator">✓</div>
        </div>
      </div>

      <!-- 支付详情（同一行展示，仅在混合支付手动模式且选择方式>1时出现） -->
      <div v-if="isMixedPaymentManualMode && selectedMethods.length > 1" class="mixed-payment-section simple">
        <div class="payment-operation-row">
          <a-row :gutter="0" class="amount-info">
            <a-col v-for="method in selectedMethods" :key="method" :span="6" class="form-row">
              <label class="form-label">{{ getAmountLabel(method) }}</label>
              <a-input
                v-model="paymentAmounts[method]"
                type="number"
                placeholder="请输入金额"
                class="form-input"
                @change="updatePaymentAmount(method, $event)"
              />
            </a-col>
          </a-row>
        </div>
      </div>
    </div>

    <!-- 底部金额和操作区（表单行风格，宽度固定） -->
    <a-row :gutter="0" class="bottom-info">
      <a-col v-for="item in config.bottomFields" :key="item.field" :span="6" class="form-row">
        <label class="form-label">{{ item.label }}</label>
        <a-input
          v-model="data[item.field]"
          :disabled="item.disabled"
          class="form-input"
          @change="bottomFieldsChange($event,item)"
        />
      </a-col>
    </a-row>
    <a-row class="actions-row" justify="center">
      <a-button
        v-for="btn in config.actionButtons"
        :key="btn.key"
        @click="handleAction(btn.key)"
        :icon="btn.icon"
        style="margin: 0 8px"
      >
        {{ btn.label }}
      </a-button>
    </a-row>
  </div>
</template>

<script>
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'
import XTitle from '../XTitle/XTitle.vue'

export default {
  name: 'XCharge',
  components: {
    XTitle
  },
  props: {
    queryParamsName: {
      type: String,
      default: ''
    },
    parameter: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      config: {
        title: '', // 标题配置
        amountFields: [],
        paymentMethods: [],
        bottomFields: [],
        actionButtons: [], // 操作按钮
        enableMixedPayment: false, // 默认关闭混合支付
        mixedPaymentMode: 'manual' // 混合支付模式：'manual'手动输入，'auto'自动模式
      },
      data: {},
      selectedMethod: '', // 保持向后兼容
      selectedMethods: [], // 新增：支持多选支付方式
      paymentAmounts: {}, // 各支付方式的金额
      // 事件名配置（可通过配置覆盖）
      eventNames: {
        method: 'method', // 单选支付方式变更事件
        methods: 'methods', // 多选支付方式变更事件
        totalPaymentAmount: 'totalPaymentAmount', // 总支付金额变更事件
        action: 'action', // 操作按钮点击事件
        paymentAmountChange: 'paymentAmountChange' // 新增：单个支付方式金额变更事件
      },
      hasInitialized: false // 是否已初始化
    }
  },
  emits: ['init'],
  computed: {
    // 安全访问混合支付配置
    isMixedPaymentEnabled () {
      return this.config && this.config.enableMixedPayment === true
    },
    // 是否为混合支付自动模式
    isMixedPaymentAutoMode () {
      return this.isMixedPaymentEnabled && this.config.mixedPaymentMode === 'auto'
    },
    // 是否为混合支付手动模式
    isMixedPaymentManualMode () {
      return this.isMixedPaymentEnabled && this.config.mixedPaymentMode === 'manual'
    },
    // 预计算：金额标签映射（仅基于 paymentMethods 配置）
    amountLabelMap () {
      const map = {}
      const methods = Array.isArray(this.config.paymentMethods) ? this.config.paymentMethods : []
      // 先用 methods 构建默认与自定义
      methods.forEach(m => {
        const key = m && m.key
        const label = m && m.label
        if (!key) return
        map[key] = `${label || key}金额`
      })
      return map
    }
  },
  created () {
    const hasParam = this.parameter && Object.keys(this.parameter).length > 0
    // 始终加载组件配置；仅当有参数时，getConfig 内部才会拉取数据
    this.getConfig(this.queryParamsName, this.parameter || {})
    if (hasParam) this.hasInitialized = true
  },
  methods: {
    // -------- 金额精度工具：使用「分」进行运算，避免浮点精度问题 --------
    // 解析金额为分（整数）；非法输入按 0 处理
    parseAmountToCents (value) {
      if (value === null || value === undefined || value === '') return 0
      // 允许字符串或数字，移除非数字与小数点字符
      const str = String(value).replace(/[^0-9.-]/g, '')
      if (str === '' || str === '-' || isNaN(Number(str))) return 0
      // 四舍五入到分
      return Math.round(Number(str) * 100)
    },
    // 将分格式化为金额（保留两位小数）
    formatCentsToAmount (cents) {
      const v = Number(cents) / 100
      // 使用 toFixed 返回字符串，再转为数字，避免 0.30000000000004
      return Number(v.toFixed(2))
    },
    // 规范化金额：返回保留两位小数的数字
    normalizeAmount (value) {
      return this.formatCentsToAmount(this.parseAmountToCents(value))
    },
    // 解析多图标：支持 method.icons 数组；否则回退到单个 icon
    getMethodIcons (method) {
      if (!method) return []
      const icons = Array.isArray(method.icons) ? method.icons : (method.icon ? [method.icon] : [])
      const resolved = icons.map(n => {
        if (!n || typeof n !== 'string') return ''
        if (n.startsWith('/') || n.startsWith('http')) return n
        const baseName = n.replace(/\.(png|jpg|jpeg|webp|svg)$/i, '')
        // 仅使用 @vue2-client 资源解析
        try { return require('@vue2-client/assets/img/paymentMethod/' + baseName + '.png') } catch (e) {}
        try { return require('@vue2-client/assets/img/paymentMethod/' + baseName + '.jpg') } catch (e) {}
        try { return require('@vue2-client/assets/img/paymentMethod/' + baseName + '.jpeg') } catch (e) {}
        try { return require('@vue2-client/assets/img/paymentMethod/' + baseName + '.webp') } catch (e) {}
        try { return require('@vue2-client/assets/img/paymentMethod/' + baseName + '.svg') } catch (e) {}
        return ''
      }).filter(Boolean)
      return resolved
    },
    // 同步 data 中的 selectedMethods / paymentAmounts 到本地状态；并补回缺失的 data 字段
    hydrateFromData () {
      const incomingMethods = Array.isArray(this.data && this.data.selectedMethods) ? this.data.selectedMethods : undefined
      const incomingAmounts = this.data && this.data.paymentAmounts && typeof this.data.paymentAmounts === 'object' ? this.data.paymentAmounts : undefined

      if (incomingMethods) {
        this.selectedMethods = [...incomingMethods]
        this.selectedMethod = this.selectedMethods[0] || ''
      } else {
        this.data.selectedMethods = [...this.selectedMethods]
        this.data.selectedMethod = this.selectedMethod
      }

      if (incomingAmounts) {
        // 用 $set 逐项写入，保持响应式
        Object.keys(incomingAmounts).forEach(k => this.$set(this.paymentAmounts, k, incomingAmounts[k]))
      } else if (!this.data.paymentAmounts) {
        this.$set(this.data, 'paymentAmounts', { ...this.paymentAmounts })
      }

      // 根据 amounts 回算合计
      this.calculateTotalPayment()
    },
    selectMethod (value) {
      this.selectedMethod = value
      this.data.selectedMethod = value
      // 单一模式下初始化对应的支付数据
      if (!this.isMixedPaymentEnabled && value) {
        if (!this.paymentAmounts[value]) this.initPaymentData(value)
      }
      // 同步到数据模型，单一模式下也记录 selectedMethods 便于父层读取
      this.data.selectedMethods = this.isMixedPaymentEnabled ? [...this.selectedMethods] : (value ? [value] : [])
      this.$emit(this.eventNames.method, value)
    },
    // 新增：切换支付方式选择（支持多选）
    toggleMethod (methodKey) {
      const index = this.selectedMethods.indexOf(methodKey)
      if (index > -1) {
        // 如果已选中，则移除
        this.selectedMethods.splice(index, 1)
        this.removePaymentData(methodKey)
      } else {
        // 如果未选中，则添加
        this.selectedMethods.push(methodKey)
        this.initPaymentData(methodKey)
      }

      // 更新选中状态
      this.selectedMethod = this.selectedMethods.length > 0 ? this.selectedMethods[0] : ''
      this.data.selectedMethod = this.selectedMethod
      this.data.selectedMethods = [...this.selectedMethods]

      this.$emit(this.eventNames.methods, this.selectedMethods)
      this.$emit(this.eventNames.method, this.selectedMethod) // 保持向后兼容
    },
    // 新增：移除支付方式
    removeMethod (methodKey) {
      const index = this.selectedMethods.indexOf(methodKey)
      if (index > -1) {
        this.selectedMethods.splice(index, 1)
        this.removePaymentData(methodKey)
        // 同步所选方式到数据模型
        this.data.selectedMethods = [...this.selectedMethods]
        this.selectedMethod = this.selectedMethods[0] || ''
        this.data.selectedMethod = this.selectedMethod
        this.$emit(this.eventNames.methods, this.selectedMethods)
      }
    },
    // 新增：初始化支付数据（可传入初始金额，默认空字符串）
    initPaymentData (methodKey, initialValue = '') {
      this.$set(this.paymentAmounts, methodKey, initialValue)
      if (!this.data.paymentAmounts || typeof this.data.paymentAmounts !== 'object') this.$set(this.data, 'paymentAmounts', {})
      this.$set(this.data.paymentAmounts, methodKey, initialValue)
    },
    // 新增：移除支付数据
    removePaymentData (methodKey) {
      this.$delete(this.paymentAmounts, methodKey)
      if (this.data && this.data.paymentAmounts) this.$delete(this.data.paymentAmounts, methodKey)
    },
    // 新增：获取支付方式标签
    getMethodLabel (methodKey) {
      const method = this.config.paymentMethods.find(m => m.key === methodKey)
      return method ? method.label : methodKey
    },
    // 获取支付金额字段标签（优先使用映射，否则回退为“{label}金额”）
    getAmountLabel (methodKey) {
      const mapped = (this.config.paymentAmountLabels && this.config.paymentAmountLabels[methodKey]) || ''
      if (mapped) return mapped
      const method = this.config.paymentMethods.find(m => m.key === methodKey)
      return `${method ? method.label : methodKey}金额`
    },
    // 新增：更新支付金额
    updatePaymentAmount (methodKey, event) {
      const amount = this.normalizeAmount(event && event.target ? event.target.value : event)
      this.$set(this.paymentAmounts, methodKey, amount)
      if (!this.data.paymentAmounts || typeof this.data.paymentAmounts !== 'object') this.$set(this.data, 'paymentAmounts', {})
      this.$set(this.data.paymentAmounts, methodKey, amount)
      this.calculateTotalPayment()
      // 单个方式金额变更事件，向父组件上抛
      this.$emit(this.eventNames.paymentAmountChange, { method: methodKey, amount })
    },
    // 新增：计算总支付金额
    calculateTotalPayment () {
      const totalCents = Object.values(this.paymentAmounts).reduce((sumCents, amount) => {
        return sumCents + this.parseAmountToCents(amount)
      }, 0)
      const total = this.formatCentsToAmount(totalCents)
      this.data.totalPaymentAmount = total
      this.$emit(this.eventNames.totalPaymentAmount, total)
    },
    // 新增：设置支付金额（由外部调用）
    setPaymentAmounts (amounts) {
      if (!this.isMixedPaymentEnabled || !amounts || typeof amounts !== 'object') return
      // 更新本地状态
      Object.keys(amounts).forEach(method => {
        const normalized = this.normalizeAmount(amounts[method])
        this.$set(this.paymentAmounts, method, normalized)
      })
      // 更新数据模型
      if (!this.data.paymentAmounts || typeof this.data.paymentAmounts !== 'object') {
        this.$set(this.data, 'paymentAmounts', {})
      }
      Object.keys(amounts).forEach(method => {
        const normalized = this.normalizeAmount(amounts[method])
        this.$set(this.data.paymentAmounts, method, normalized)
      })
      this.calculateTotalPayment()
    },
    getConfig (configName, param) {
      if (configName) {
        console.log('configName', configName)
        getConfigByName(configName, 'af-his', res => {
          console.log('res', res)
          // 检查是否有错误
          if (res && res.ERROR) {
            console.warn('配置获取失败:', res.ERROR)
            return
          }
          this.config = {
            title: res.title || '', // 标题配置
            amountFields: res.amountFields || [],
            paymentMethods: res.paymentMethods || [],
            bottomFields: res.bottomFields || [],
            actionButtons: res.actionButtons || [],
            enableMixedPayment: res.enableMixedPayment === true,
            mixedPaymentMode: res.mixedPaymentMode || 'manual' // 默认手动模式
          }
          // 事件名覆盖（fronImport风格）
          if (res.eventNames && typeof res.eventNames === 'object') {
            this.eventNames = { ...this.eventNames, ...res.eventNames }
          }
          // 处理默认选中项（支持 paymentMethods[].default === true）
          const methods = Array.isArray(this.config.paymentMethods) ? this.config.paymentMethods : []
          const defaultMethods = methods.filter(m => m && m.default === true)

          if (this.isMixedPaymentEnabled) {
            // 混合支付：默认选中全部 default=true 的方式；若没有默认，则保留现有逻辑选择第一个
            if (defaultMethods.length > 0) {
              this.selectedMethods = defaultMethods.map(m => m.key).filter(Boolean)
            } else if (methods.length > 0) {
              this.selectedMethods = [methods[0].key]
            } else {
              this.selectedMethods = []
            }
            // 初始化金额为 0
            this.selectedMethods.forEach(k => this.initPaymentData(k, 0))
            this.selectedMethod = this.selectedMethods[0] || ''
            // 同步到数据模型
            this.data.selectedMethods = [...this.selectedMethods]
          } else {
            // 单一支付：若存在默认项，选中第一个默认；否则选中第一个
            if (defaultMethods.length > 0) {
              this.selectedMethod = defaultMethods[0] && defaultMethods[0].key || ''
            } else {
              this.selectedMethod = methods[0] && methods[0].key || ''
            }
            if (this.selectedMethod) this.initPaymentData(this.selectedMethod, 0)
            // 同步到数据模型，单一模式下也记录 selectedMethods
            this.data.selectedMethods = this.selectedMethod ? [this.selectedMethod] : []
          }

          // 初始化数据：仅当传入了有效 param 时才拉取数据
          const hasParam = param && Object.keys(param || {}).length > 0
          if (hasParam && res.dataSourceConfig) {
            runLogic(res.dataSourceConfig, param, 'af-his').then(resData => {
              // 合并数据，避免覆盖 selectedMethods / paymentAmounts 等本地状态
              this.data = { ...this.data, ...resData }
              // 让本地状态与 data 保持一致
              this.hydrateFromData()
            }).catch(error => {
              console.warn('数据获取失败（保持现有数据）:', error)
            })
          }
        })
      }
    },
    refreshList (param) {
      this.getConfig(this.queryParamsName, param)
    },
    async init (conditionData) {
      if (conditionData.data) {
        // 合并初始化数据，避免覆盖 selectedMethods / paymentAmounts 等本地状态
        this.data = { ...this.data, ...conditionData.data }
        this.hydrateFromData()
      }
      if (conditionData.params) {
        await this.getConfig(this.queryParamsName, conditionData.params)
      }
      this.hasInitialized = true
    },
    // 使用默认数据
    useDefaultData () {
      this.data = {
        f_amount: 0,
        f_insurance_amount: 0,
        f_self_amount: 0,
        f_balance: 0,
        out_of_pocket_amount: 0,
        biscount_amount: 0,
        billing_amount: 0,
        received: 0,
        change: 0
      }
    },
    handleAction (key) {
      console.warn('选择的的方法 ====》' + key)
      console.warn('页面数据 ====》' + JSON.stringify(this.data))
      console.warn('选择的支付方式 ====》' + this.selectedMethod)

      if (this.isMixedPaymentEnabled) {
        console.warn('混合支付方式 ====》' + JSON.stringify(this.selectedMethods))
        console.warn('支付详情 ====》' + JSON.stringify({ amounts: this.paymentAmounts }))
      }

      const actionData = {
        key,
        data: this.data,
        method: this.selectedMethod,
        // 统一返回支付详情，单一模式时 selectedMethods 仅含一个
        mixedPayment: {
          selectedMethods: this.isMixedPaymentEnabled ? this.selectedMethods : (this.selectedMethod ? [this.selectedMethod] : []),
          paymentAmounts: this.paymentAmounts,
          totalPaymentAmount: this.data.totalPaymentAmount || 0
        }
      }

      this.$emit(this.eventNames.action, actionData)
    },
    bottomFieldsChange (e, item) {
      // 统一抛出到底部字段变更事件到父级组件
      this.$emit('bottomFieldChange', {
        event: e,
        item: item,
        field: item.field,
        value: e && e.target ? e.target.value : undefined
      })

      // 保持原有的自定义事件逻辑（向后兼容）
      if (item.changeEventName && this.$listeners[item.changeEventName]) this.$emit(item.changeEventName, e, item)
    }
  },
  watch: {
    configName (val) {
      this.getConfig()
    }
  }
}
</script>

<style scoped>
.xcharge-wrapper {
  background: #fff;
  padding: 12px;
  border-radius: 8px;
}

.charge-title {
  margin-bottom: 16px;
}

.amount-info {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  row-gap: 16px;
}

/* 顶部分割线 */
.top-divider {
  height: 2px;
  opacity: 1;
  background: #0057FE;
  margin-top: 8px;
  margin-bottom: 12px;
}

.form-row {
  display: flex;
  align-items: center;
}

.form-label {
  width: 100px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
  text-align: center;
  letter-spacing: 1px;
  flex-shrink: 0;
}

.form-input {
  width: 200px;
  height: 30px;
  font-size: 16px;
  border-radius: 8px;
  border: 1.5px solid #dcdfe6;
  background: #fff;
  color: #333;
  padding-left: 12px;
}

.form-input[disabled] {
  color: #999;
  background: #f5f5f5;
}

/* 支付容器 */
.payment-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 10px;
  height: 464px;
  padding: 112px 31px 0px;
}

.payment-methods {
  display: flex;
  justify-content: space-around;
  margin: 0 0 16px 0;
  gap: 20px;
}

.payment-option {
  width: 220px;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1.5px solid #e4e7ed;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.payment-option:hover {
  background: #0057FE;
  border-color: #0057FE;
  box-shadow: 0 2px 8px rgba(0, 87, 254, 0.2);
}

.payment-option.active {
  background: #587EDF;
  border-color: #587EDF;
  color: #fff;
}

.payment-option:hover .payment-label {
  color: #fff;
}

.payment-icon {
  position: relative;
  width: 65px;
  height: 65px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-icon.multiple {
  gap: 12px;
}

.icon-image {
  width: 65px;
  height: 65px;
  object-fit: contain;
  border-radius: 8px;
}

.icon-placeholder {
  width: 100%;
  height: 100%;
  background: #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  color: #666;
}

/* 移除徽章样式：模板已不再使用 */

.payment-label {
  font-size: 36px;
  font-weight: 500;
  text-align: center;
  color: #333;
}

.payment-option.active .payment-label {
  color: #fff;
}

.selected-indicator {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #52c41a;
  color: #fff;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}

.mixed-payment-section {
  margin: 0;
  padding: 0;
  margin-top: 40px;
  background: transparent;
  border: none;
}

.mixed-payment-section.simple {
  padding: 0;
  background: transparent;
  border: none;
}

.mixed-payment-section.simple .payment-operation-row {
  border: none;
  background: transparent;
  padding: 0;
  margin: 0;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.payment-operation-row {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
}

.payment-method-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.method-name {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
}

.remove-btn {
  color: #ff4d4f;
  padding: 0;
  height: auto;
}

.remove-btn:hover {
  color: #ff7875;
}

.payment-fields {
  margin-top: 12px;
}

/* 支付详情采用与顶部相同的栅格布局，故移除横向内联容器样式 */

.inline-field {
  display: inline-flex;
  align-items: center;
  column-gap: 16px;
  white-space: nowrap;
}

.payment-inline .form-label {
  width: auto;
  font-size: 16px;
}

.pay-shortcut {
  font-size: 16px;
  color: #888;
}

.bottom-info {
  margin-top: 24px;
  display: flex;
  flex-wrap: wrap;
  row-gap: 16px;
}

.actions-row {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

.actions-row .ant-btn {
  margin: 0 8px;
  background: #444;
  color: #fff;
  border-radius: 6px;
  border: none;
  font-size: 16px;
  font-weight: 500;
  height: 38px;
  min-width: 90px;
}

</style>
