<template>
  <div class="order-detail-card-container">
    <InfoCard title="基本信息" v-if="false">
      <div class="order-detail-card-content">
        <div class="order-detail-card-item" v-for="(item, index) in basicInfoItems" :key="index">
          {{ item.label }}：{{ getFilteredValue(orderData[item.key], item.filter) || '-' }}
        </div>
      </div>
    </InfoCard>
    <InfoCard title="产品信息">
      <div class="order-detail-card-content" v-if="false">
        <div class="order-detail-card-item" v-for="(item, index) in productInfoTotalItems" :key="index">
          <div v-if="item.key === 'pure_amount'">
            {{ item.label }}：￥{{ formatNumber(orderData[item.key]) || '-' }}
            <span class="red-chong" v-if="setRedPunchDisplay('合同金额')">（红冲过）</span>
          </div>
          <div v-else-if="item.key === 'final_price_total'">
            {{ item.label }}：￥{{ orderData[item.key] || '-' }}
            <span class="red-chong" v-if="setRedPunchDisplay('合同金额')">（红冲过）</span>
          </div>
          <div v-else-if="item.key === 'commission'">
            {{ item.label }}：￥{{ formatNumber(orderData[item.key]) || '0.00' }}
            <span class="red-chong" v-if="setRedPunchDisplay('销售费用')">（红冲过）</span>
          </div>
          <div v-else-if="item.key === 'rate_total'">
            {{ item.label }}：<span :class="{'red-chong': orderData[item.key] === '无法计算'}">{{ orderData[item.key] || '-' }}</span>
            <span class="red-chong" v-if="setRedPunchDisplay('折扣率')">（红冲过）</span>
          </div>
          <div v-else-if="item.key === 'zero_type'">
            <span v-if="shouldRenderItem(item)">
              {{ item.label }}：{{ getFilteredValue(orderData[item.key], item.filter) || '-' }}
            </span>
          </div>
          <div v-else>{{ item.label }}：{{ getFilteredValue(orderData[item.key], item.filter ) || '-' }}</div>
        </div>
      </div>
      <div class="order-detail-product-list">
        <div
            v-for="(product, index) in productData"
            :key="product.id"
        >
          <ProductCard
              style="margin-bottom: 20px"
              :title="setProductTitle(product, index)"
              :subtitle="product.auto !== 1 ? '该产品暂不支持系统自动开通权限，请联系运维开通': ''"
          >
            <div class="order-detail-product-content">
              <div class="grouped-items">
                <div
                    v-for="(item, index) in productInfoItems"
                    :key="index"
                    :class="`item-span-${item.span}`">
                  <div
                      class="order-detail-card-item"
                      v-if="shouldRenderItem(item, product)"
                  >
                    <div style="flex-direction: column;" v-if="item.key === 'linkedOrder'" class="linkedOrder">
                      <div>{{ item.label }}：</div>
                  <RelatedOrderTable class="detail-order-table" v-if="product.linkedOrder && Object.keys(product.linkedOrder).length" :table-data="product.options">
                  </RelatedOrderTable>
                      <span v-else>-</span>
                    </div>
                    <div v-else-if="item.key === 'subAccountCount'">
                      <span v-html="getValidityPeriodHtml(product, item)"></span>
                    </div>
                    <div v-else-if="item.key === 'mainAccountCount'">
                      <span v-html="getValidityPeriodHtml(product, item)"></span>
                    </div>
                    <div v-else-if="item.key ==='data_count'">
                      <span v-html="getValidityPeriodHtml(product, item)"></span>
                    </div>
                    <div v-else-if="item.key ==='productName'">
                      <span v-html="getValidityPeriodHtml(product, item)"></span>
                    </div>
                    <div v-else-if="item.key ==='rate'">
                      {{ item.label }}：
                  <span :class="{'no_open_root': product.original_price === 0}">{{ getFilteredValue(product[item.key], item.filter) || '-' }}</span>
                    <span class="red-chong" v-if="product.isRed">（红冲过）</span>
                    </div>
                <div v-else-if="item.key === 'final_price'">
                  {{ item.label }}：￥{{ getFilteredValue(product[item.key], item.filter) }}
                  <span class="red-chong" v-if="product.isRed">（红冲过）</span>
                </div>
                <div v-else-if="item.key === 'original_price'">
                  {{ item.label }}：
                  <span v-if="!product.original_price && product.product_type !== '阳光采购'" class="no_open_root">该产品暂无法计算标准售价</span>
                  <span v-else>￥{{ getFilteredValue(product[item.key], item.filter) || '-' }}</span>
                    </div>
                    <div v-else-if="item.key === 'validity_period'">
                      <span v-html="getValidityPeriodHtml(product, item)"></span>
                    </div>
                    <div v-else-if="item.key === 'supServiceIds'">
                      {{ item.label }}：{{ getFilteredValue(product[item.key], item.filter) || '-' }}
                    </div>
                    <div v-else-if="item.key === 'service_starttime'">
                      {{ item.label }}：
                      <span :class="{'no_open_root':!product.is_service_open}" >{{ product.is_service_open? (product.service_starttime || '-') : '暂未开通' }}</span>
                    </div>
                    <div v-else-if="item.key === 'service_endtime'">
                      {{ item.label }}：
                      <span :class="{'no_open_root': !product.is_service_open}" >{{ product.is_service_open ? (product.service_endtime || '-') : '暂未开通' }}</span>
                    </div>
                    <div v-else-if="item.key ==='phone'">
                      {{ item.label }}：{{ orderData.user_phone || '-' }}
                    </div>
                <div v-else-if="item.key === 'giftCount'">
                  {{ item.label }}：{{ product.filter.num || '-' }}个
                </div>
                <div v-else-if="item.key === 'sale_final_price'">
                  {{ item.label }}：￥{{ divided(product.filter.num, 100) }}
                </div>

                    <div v-else>{{ item.label }}：{{ getFilteredValue(product[item.key], item.filter) || '-' }}</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="order-detail-card-item" style="margin-left: 22px;">
              是否{{formType}}：
              <el-radio-group v-model="product.canSelect">
                <el-radio :label="true">{{formType}}</el-radio>
                <el-radio :label="false">暂不操作</el-radio>
              </el-radio-group>
            </div>
          </ProductCard>
          <div v-if="formType === '退款'">
            <el-form v-show="product.canSelect" :disabled="!product.canSelect" ref="pForm" class="product-form" :model="product.form" :rules="FormRules" label-width="80px">
              <el-form-item label="退款金额" prop="money">
                <el-input v-model="product.form.money" @blur="formatInputMoney(product.form)" placeholder="请输入退款金额"></el-input>
              </el-form-item>
              <el-form-item label="退款原因" prop="reason">
                <el-select v-model="product.form.reason" placeholder="请选择退款原因">
                  <el-option v-for="t in refundType" :key="t.v"  :label="t.v" :value="t.v"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="desc">
                <el-input type="textarea"   maxlength="200" v-model="product.form.desc"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="formType === '红冲'">
            <el-form v-show="product.canSelect" :disabled="!product.canSelect" ref="pForm" class="product-form" :model="product.form" :rules="FormRules2" label-width="80px">
              <el-form-item label="合同金额" prop="money">
                <el-input v-model="product.form.money" @blur="formatInputMoney(product.form)" placeholder="请输入合同金额"></el-input>
              </el-form-item>
<!--              <el-form-item label="佣金" prop="commission">-->
<!--                <el-input v-model="product.form.commission" @blur="formatInputMoney(product.form, 'commission')" placeholder="请输入佣金金额"></el-input>-->
<!--              </el-form-item>-->
              <el-form-item label="修正原因" prop="reason">
                <el-select v-model="product.form.reason" placeholder="请选择修正原因">
                  <el-option v-for="t in correctionType" :key="t.v"  :label="t.v" :value="t.v"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="desc" v-if="product.form.reason === '其他'">
                <el-input type="textarea" maxlength="200" v-model="product.form.desc" placeholder="请输入修正原因"></el-input>
              </el-form-item>
            </el-form>
          </div>

        </div>
      </div>
    </InfoCard>
    <InfoCard title="其他信息" v-if="false">
      <div class="order-detail-card-content">
        <div class="order-detail-card-item" v-for="(item, index) in otherInfoItems" :key="index">
          {{ item.label }}：{{ getFilteredValue(orderData[item.key], item.filter) || '-' }}
        </div>
      </div>
    </InfoCard>
       <ServiceList v-show="false" :buySubject="orderData.buy_subject" ref="serviceListRef"></ServiceList>
  </div>
</template>

<script>
import InfoCard from '../../ui/InfoCard.vue';
import ProductCard from '../../ui/ProductCard.vue';
import {buySubjectOptions, paymentTypeOptions} from '../../data/options.js';
import { div, calcDiscountRate, roundToTwoDecimals } from '@/utils/number/';
import TableCard from '../../ui/TableCard.vue';
import ServiceList from "@/views/create-order/components/product-info-submodule/ServiceList.vue";
import {showActivityCardRateModule} from "@/views/create-order/hooks/utils";
import RelatedOrderTable from '../product-info-submodule/RelatedOrderTable.vue';
import { dateFormatter } from '@/utils/globalFun'
import { maskPhone } from '@/utils/str/index'
import { findPaymentType } from '@/views/create-order/hooks/format'

export default {
  name: 'SelectOrderDetailCard',
  components: {
    ServiceList,
    InfoCard,
    ProductCard,
    RelatedOrderTable,
    TableCard
  },
  props: {
    orderDetail: {
      type: Object,
      default: () => {}
    },
    formType: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      basicInfoItems: [
        { label: '创建人', key: 'create_person' },
        { label: '创建时间', key: 'create_time' },
        { label: '最近更新人', key: 'last_update_person' },
        { label: '最近更新时间', key: 'autoUpdate' },
        { label: '订单审核状态', key: 'audit_status', filter: 'orderCoursed' },
        { label: '订单状态', key: 'order_status', filter: 'orderStatus' }
      ],
      otherInfoItems: [
        { label: '约定支付方式', key: 'pay_way' },
        { label: '下单渠道', key: 'order_channel_new' },
        { label: '付款户名', key: 'payment_user'},
        { label: '订单备注', key: 'remark' },
      ],
      productInfoTotalItems: [
        { label: '合同金额合计', key: 'final_price_total' },
        { label: '标准售价合计', key: 'original_price_total'},
        { label: '折扣率', key: 'rate_total' },
        { label: '销售费用', key: 'commission'},
        { label: '净合同金额合计', key: 'pure_amount'},
        { label: '0元订单类型', key: 'zero_type', condition: () => this.orderData.final_price_total === '0.00' },
      ],
      productInfoItems: [
        { label: '活动产品', key: 'activityName', span: 1, condition: (product) => product.activityName },
        { label: '付费类型', key: 'service_type', filter: 'orderServiceType', span: 3},
        { label: '升级内容', key: 'supServiceIds', span: 3, condition: (product) => product.service_type === 3 },
        { label: '产品规格', key: 'productName', span: 3},
        { label: '报告份数', key: 'reportNumber', span: 1, condition: (product) => this.reportType.includes(product.product_type)},
        { label: '剑鱼币个数', key: 'coinCount', span: 1, condition: (product) => product.product_type && product.product_type === '剑鱼币'},
        { label: '购买产品', key: 'buyProductName', span: 1, condition: (product) => product.product_type && product.product_type === '结构化数据'},
        { label: '服务列表', key: 'bigServiceNamesPro', span: 1, condition: (product) => product.productName && product.productName.includes('自定义') &&  product.product_code === 'dyh001'},
        { label: '数据条数', key: 'data_count', span: 1, condition: (product) => product.data_count && product.data_count !== '-'},
        { label: '有效周期', key: 'validity_period', span: 1},
        { label: '合同金额', key: 'final_price', span: 3},
        { label: '标准售价', key: 'original_price', span: 3},
        { label: '折扣率', key: 'rate', span: 3},
        { label: '子账号数量', key: 'subAccountCount', span: 1, condition: (product) => product.filter.buyAccountCount || product.filter.giftAccountCount },
        { label: '主账号数量', key: 'mainAccountCount', span: 1 },
        { label: '关联订单', key: 'linkedOrder', span: 1},
        { label: '邮箱地址', key: 'email', span: 1, condition: (product) => product.product_type === '数据报告' },
        { label: '赠品数量', key: 'giftCount', span: 1, condition: (product) => {
          return product.tactics === '2' && product.filter.num && product.product_type !== '销售费用'
        } },
        { label: '销售费用', key: 'sale_final_price', span: 1, condition: (product) => {
          return product.tactics === '2' && product.product_type === '销售费用'
        }},
        { label: '补充说明', key: 'supExplanation', span: 1, condition: (product) => product.supExplanation && product.supExplanation !== '-' },
        { label: '开通权益手机号', key: 'phone', span: 3},
        { label: '服务开始时间', key: 'service_starttime', span: 3},
        { label: '服务结束时间', key: 'service_endtime', span: 3}
      ],
      orderData: {},
      productData: [],
      FormRules: {
        reason: [
          { required: true, message: '请选择退款原因', trigger: 'blur' },
        ],
        money: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
        ],
      },
      FormRules2: {
        reason: [
          { required: true, message: '请选择红冲原因', trigger: 'blur' },
        ],
        money: [
          { required: true, message: '请输入合同金额', trigger: 'blur' },
        ],
      },
      refundType: [
        { v: '个人垫付退款', n: '个人垫付退款' },
        { v: '产品购买错误', n: '产品购买错误' },
        { v: '客户不满意', n: '客户不满意' },
        { v: '活动免单', n: '活动免单' },
        { v: '测试', n: '测试' },
        { v: '其他', n: '其他' }
      ],
      correctionType: [
        { v: '录入错误', n: '录入错误' },
        { v: '客户不再支付', n: '客户不再支付' },
        { v: '其他', n: '其他' }
      ],
      linkOrderColumns: [
        {
          prop: 'name',
          label: '产品类型及规格',
          width: 154,
          render (row) {
            if(row.name === 'VIP订阅') {
              return '超级订阅'
            } else {
              return row.name ? row.name : '-'
            }
          }
        },
        {
          prop: 'empowerCount',
          label: '账号数量',
          width: 80
        },
        {
          prop: 'serviceEndTime',
          label: '到期时间',
          width: 102
        },
        {
          prop: 'buySubject',
          label: '购买主体',
          width: 80,
          render (row) {
            return buySubjectOptions.find(item => item.value === row.buySubject)?.label || '-'

          }
        },
        {
          prop:'order_code',
          label: '订单编号',
          width: 154
        },
        {
          prop:'service_type',
          label: '付费类型',
          width: 80
        },
        {
          prop:'create_time',
          label: '创建时间',
          width: 102
        }
      ],
      parsedFilter: {}
    }
  },
  watch: {
    orderDetail: {
      handler(newVal) {
        this.beforeInit(newVal);
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    reportType() {
      return ['数据报告', '业主采购分析报告下载包', '企业中标分析报告下载包', '市场分析定制报告下载包', '采购单位画像包', '附件下载包', '投标企业信用报告']
    } 
  },
  mounted() {
    this.beforeInit();
  },
  methods: {

    formatInputMoney (f, key = 'money') {
      f[key] = this.formatNumber((f[key] || 0) * 100)
    },
    async getProductForm () {
      let vCount = 0
      let vCountSuccess = 0
      for (let i = 0; i < this.$refs.pForm.length; i++) {
        const v = this.$refs.pForm[i]
        if (!v.disabled) {
          vCount++
          await v.validate().then(() => {
            vCountSuccess++
          })
        } else {
          v.resetFields()
        }
      }

      if (vCount === vCountSuccess && vCountSuccess >= 1) {
          return this.productData.filter(v => v.canSelect)
      } else {
        return []
      }
    },
    initItemForm () {
      let result = {}
      switch (this.formType) {
        case '退款': {
          result = {
            money: '',
            reason: '',
            desc: ''
          }
          break
        }
        case '红冲': {
          result = {
            money: '',
            reason: '',
            commission: '',
            desc: ''
          }
          break
        }
      }
      return result
    },
    beforeInit() {
      this.$nextTick(() => {
        this.init();
      })
    },
    async init() {
      this.orderData = this.orderDetail?.orderData || {};
      let productData = this.orderDetail?.productData || [];
      const { _productArr } = this.orderDetail || {}

      if(productData.length > 0) {
        // 使用 Promise.all 来并行处理每个 product 的异步操作
        productData = await Promise.all(
            productData.map(async (product, index) => {
              product.canSelect = index === 0
              product.form = this.initItemForm()
              try {
                const parsedFilter = this.parseProductFilter(product);
                const serviceIds = parsedFilter.serviceIds || [];
                const supServiceIdsOrigin = parsedFilter.supServiceIds || [];
                const bigServiceNames = product.bigServiceNames || '';
                // 等待异步方法完成
                const supServiceIds = this.buildSupServiceIds(parsedFilter || []);
                const bigServiceNamesPro = product.product_type === '大会员' ? await this.buildBigServiceNames(serviceIds, supServiceIdsOrigin, bigServiceNames) : '';
                const rate = this.calculateDiscountRate(product);
                const validityPeriod = this.calculateValidityPeriod(
                parsedFilter,
                  product
                );
                const supExplanation = parsedFilter.supExplanation
                const dataCount = this.buildDataCount(product, parsedFilter);
                const reportNumber = this.buildReportNumber(product, parsedFilter);
                const coinCount = this.buildCoinCount(product, parsedFilter);
                const buyProductName = this.buildBuyProductName(product, parsedFilter);
                const subAccountCount = this.buildSubAccountCount(product, parsedFilter);
                const mainAccountCount = '1个';
                // const linkedOrder = this.processLinkedOrder(product);
                const finalPrice = this.formatNumber(product.final_price);
                let originalPrice = this.formatNumber(product.original_price);
                const linkedOrder = product.linkedOrder || {}; // 关联订单信息
                const { buySubject, empowerCount, name, serviceStartTime, serviceEndTime, provinceCount, productCode, orderArr } = linkedOrder || {}

                const options = [{
                  buySubject,
                  comboId: 0, // 套餐id
                  empowerCount, // 人数
                  name,
                  phone: this.orderData.personPhone, // 开通权益手机号
                  provinceCount, // 订阅省份
                  serviceStartTime, // 服务开始时间
                  serviceEndTime, // 结束时间
                  serviceList: [],
                  linkedOrder: orderArr,
                  vipExist: false, //当前服务是否在有限期内
                  productCode
                }]
                const item = options[0]
                const arr = []
                if (Array.isArray(item.linkedOrder) && item.linkedOrder.length > 0) {
                  item.linkedOrder.forEach(t => {
                    arr.push({
                      ...item,
                      linkedId: item.linkedId,
                      _linkedId: `${item.linkedId}-${t.order_code}`,
                      linkedOrderSplit: t,
                    })
                  })
                } else {
                  // 关联订单只有1个的情况
                  arr.push({
                    ...item,
                    _linkedId: item.linkedId + '',
                  })
                }
                const associationOrder = arr.map(t => {
                  return {
                    ...t,
                    ...this.sortTableText(t),
                  }
                })
                const productName = this.buildProductName(product, parsedFilter)
                const email = product.product_type === '数据报告' ? parsedFilter.email : '';
                const newProduct = {
                    ...product,
                    filter: parsedFilter,
                    rate,
                    productName,
                    reportNumber,
                    coinCount,
                    buyProductName,
                    validity_period: validityPeriod,
                    data_count: dataCount,
                    subAccountCount,
                    mainAccountCount,
                    linkedOrder,
                    supServiceIds,
                    bigServiceNamesPro,
                    email,
                    final_price: finalPrice,
                    sale_final_price: finalPrice,
                    original_price: originalPrice,
                    supExplanation,
                    ..._productArr[index] || {},
                    options: associationOrder
                  };

                newProduct._a = showActivityCardRateModule(_productArr, newProduct)

                return newProduct
              } catch (error) {
                console.error('产品信息初始化失败:', error);
                return product;
              }
        })
        );
      }

      this.setTotalAmounts(productData);
      this.productData = productData;
    },
    sortTableText(service) {
      const order = service.linkedOrderSplit || {}
      return {
        // productTypeText: service.name || '-',
        empowerCountText: service.empowerCount ? `${service.empowerCount}个` : '-',
        serviceEndTimeText: service.serviceEndTime ? service.serviceEndTime : '-',
        buySubjectText: service.buySubject === 1 ? '个人' : '企业',
        phone: service.phone,
        short_phone: maskPhone(service.phone),
        order_code: order.order_code || '-',
        service_type: order.service_type || '-',
        service_type_text: findPaymentType(order.service_type)?.label || '-',
        create_time: order.create_time || '-',
        productCode: service.productCode || ''
      }
    },
    // 权限开通
    openPermissionActivation() {
      this.$refs.newDetailModel.permissionActivationShow = true;
    },
    isShowPermission (product) {
      const { auto, attribute } = product
      const { return_status } = this.orderData?.return_status || 0
      // 仅当该产品类型支持系统自动开通权限，且产品属性为会员服务或资源包，且“回款状态”为“全额回款”才展示，否则不展示；
      return auto === 1 && (attribute === 1 || attribute === 2) && return_status === 1
    },
    // 设置红冲标识显示字段
    setRedPunchDisplay(product) {
      const { isUpCommission, isUpEnt, isUpCash } = this.orderDetail?.redPunchData || {};
      const RETURN_BOOL = {
        '合同金额': isUpCash,
        '销售费用': isUpCommission,
        '签约主体': isUpEnt,
        '折扣率': isUpCash
      }
      return RETURN_BOOL[product] || false;
    },
    buildProductName(product, parsedFilter) {
      const { product_type: type, productName: defaultName } = product;
      const { finalAreaCount, report_name: reportName, addAreaCount, area_count: areaCount, s_name: sName } = parsedFilter || {};

      let result = defaultName;

      if (type === '数据报告') {
        result = reportName || defaultName;
      } else if (type === 'VIP订阅' || type === '省份订阅包') {
        const count = addAreaCount || 0;
        const suffix = count > 0 ? `<span style="color:#f74e29">（此次增购${count}个省）</span>` : '';
        // 1购买2续费3升级4试用
        const serviceType = product.service_type;
        const final = finalAreaCount > 0 ? `${finalAreaCount}个省` : '全国';
        if(serviceType == 1) {
          result = type === '省份订阅包' ? `${final}${suffix}` : final;
        } else if (serviceType == 2) {
          result = final;
        } else if(serviceType == 3) {
          result = `${final}${suffix}`
        }

      } else if (type === '物业|采购意向+最新采购') {
        const count = areaCount || 0;
        result = count ? `${count}个省` : '全国';
      } else if (type === '中标必听课') {
        result = sName || defaultName;
      }

      return result;
    },
    buildSupServiceIds(parfilter) {
      const { supServiceIds, buyAccountCount, giftAccountCount } = parfilter
      const upgradeContent = []
      if (supServiceIds && supServiceIds.length > 0) {
        upgradeContent.push('补充权益')
      }
      if(buyAccountCount || giftAccountCount) {
        upgradeContent.push('增购子账号')
      }
      return upgradeContent.length ? upgradeContent.join('、') : '-'
    },
    buildBigServiceNames(serviceIds, supServiceIds, bigServiceNames) {
      return new Promise((resolve) => {
        if (!serviceIds || serviceIds.length === 0) {
          resolve('');
          return;
        }

        // 避免修改原始数组，创建新的整型数组
        const numericServiceIds = serviceIds.map(id => parseInt(id));
        let sameValues = [], differentValues = [];
        const hasBigServiceNames = bigServiceNames ? `、${bigServiceNames}` : ''
        this.$nextTick(() => {
          try {
            const serviceListRef = this.$refs.serviceListRef;
            if (!serviceListRef || typeof serviceListRef.calcAlreadyBuyServiceNamesArr !== 'function') {
              resolve('');
              return;
            }
            if(supServiceIds && supServiceIds.length > 0) {
              // 比较supServiceIds和serviceIds相同的值，并返回相同的值组成的数组，不同的值也返回一个数组

              // 已购服务
              // 不同的值组成的数组
              differentValues = serviceIds.filter(value => !supServiceIds.includes(value));
              const differentValuesArr = differentValues.map(id => parseInt(id));
              if(differentValuesArr.length === 0) {
                console.warn('differentValuesArr为空')
              }
              const baseServiceIdsArr = serviceListRef.calcAlreadyBuyServiceNamesArr(differentValuesArr);
              const baseServiceData = Array.isArray(baseServiceIdsArr)? baseServiceIdsArr.join('、') : ''
              // 补充服务
              // 相同的值组成的数组
              sameValues = supServiceIds.filter(value => serviceIds.includes(value));
              if (sameValues.length && sameValues.includes(4) && sameValues.includes(19)) {
                // 同时有4和19时，去掉 4
                sameValues = sameValues.filter(value => value !== 4);
              }
              const supServiceIdsArr = sameValues.map(id => parseInt(id));
              if(supServiceIdsArr.length === 0) {
                console.warn('supServiceIdsArr为空') 
              }
              const resSupServiceIdsArr = serviceListRef.calcAlreadyBuyServiceNamesArr(supServiceIdsArr);
              // 如果resSupServiceData中包含基础服务+企业管理，需要去掉, buy_subject为1时，去掉企业管理
              const baseServiceIndex = resSupServiceIdsArr.findIndex(item =>
                item === (this.orderData.buy_subject === 2 ? '基础服务+企业管理' : '基础服务')
              );
              if (baseServiceIndex !== -1) {
                resSupServiceIdsArr.splice(baseServiceIndex, 1);
              }
              const resSupServiceData = Array.isArray(resSupServiceIdsArr)? resSupServiceIdsArr.join('、') : '';

              // 如果有补充服务，就拼接，如果没有补充服务，就不拼接，直接返回原已购服务名连接字符串
              const supplement = resSupServiceData ? `【补充服务】：${resSupServiceData}` : ''
              // 最终服务字符串：补充服务名称;原已购服务名称
              const serviceStr = `${supplement};【原已购服务】：${baseServiceData}${hasBigServiceNames}`
              resolve(serviceStr);
            } else {
              if(numericServiceIds.length === 0) {
                console.warn('numericServiceIds为空')
              }
            const res = serviceListRef.calcAlreadyBuyServiceNamesArr(numericServiceIds);
            const serviceData = Array.isArray(res) ? res.join('、') + hasBigServiceNames : '';
            resolve(serviceData);
            }
          } catch (error) {
            console.error('Error calculating service names:', error);
            resolve('');
          }
        });
      });
    },
    parseProductFilter(product) {
      let parsedFilter = {};
      if (typeof product.filter === 'string') {
        try {
          parsedFilter = JSON.parse(product.filter || '{}');
        } catch {
          parsedFilter = {};
        }
      } else {
        parsedFilter = product.filter || {};
      }
      return parsedFilter;
    },

    // 计算折扣率
    calculateDiscountRate(product) {
      let rate = '无法计算';
      if (product.original_price && Number(product.original_price) >= 0) {
        rate = (calcDiscountRate(product.final_price, product.original_price)) + '%';
      }
      return rate;
    },

    // 构造子账号数量字符串。
    buildSubAccountCount(product, filter) {
      const buyCount = Number(filter?.buyAccountCount) || 0;
      const giftCount = Number(filter?.giftAccountCount) || 0;
      if (buyCount || giftCount) {
        const countTotal = buyCount + giftCount;
        return `付费${buyCount}个，赠送${giftCount}个，合计：<span class="color_main">${countTotal}</span>个`;
      }
      return '';
    },
    // 处理关联订单数据。
    // processLinkedOrder(product) {
    //   if (product.linkedOrder && Object.keys(product.linkedOrder).length > 0) {
    //     const orderList = [product.linkedOrder];
    //     return this.flattenLinkOrderList(orderList);
    //   }
    //   return [];
    // },

    // 设置合同金额合计和标准售价合计，以及计算折扣率总和。
    setTotalAmounts(productData) {
      this.orderData = this.orderDetail.orderData || {};
      const totalFinalPrice = this.isBackstageOrder ? (this.formatNumber(this.orderData.pay_money) || '0.00') : (this.formatNumber(this.orderData.order_money) || '0.00')
      let totalOriginalPrice = productData.reduce((acc, cur) => acc + Number(cur.original_price), 0).toFixed(2);
      const totalDiscountRate = div(totalFinalPrice, totalOriginalPrice) * 100
      const rateTotal = totalDiscountRate ? (div(totalFinalPrice, totalOriginalPrice) * 100).toFixed(2) + '%' : '0%'
      // 无标准售价产品，标准售价合计展示为无法计算
      let noOriginalPriceProductBool = false
      productData.forEach(product => {
        if(!product.original_price) {
          noOriginalPriceProductBool = true
        } 
      })
      const originalPriceTotal = !noOriginalPriceProductBool
      if(originalPriceTotal) {
        totalOriginalPrice = this.isBackstageOrder ? this.formatNumber(this.orderData.order_money || '0.00') : this.formatNumber(this.orderData.original_price || '0.00')
      }
      this.orderData = {
        ...this.orderData,
        final_price_total: totalFinalPrice,
        original_price_total: originalPriceTotal ? '￥' + totalOriginalPrice : '无法计算',
        rate_total: originalPriceTotal && Number(totalOriginalPrice) ? rateTotal : '无法计算'
      }
    },
    // flattenLinkOrderList(linkOrderList) {
    //   const result = [];
    //   if (!linkOrderList || linkOrderList.length === 0) return result;
    //   linkOrderList.forEach(item => {
    //     const { orderArr, ...rest } = item; // 拆分 orderArr 和其他字段
    //     if (!orderArr || orderArr.length === 0) return;
    //     orderArr.forEach(order => {
    //       result.push({
    //         ...rest,           // 非 orderArr 的字段（如 name, empowerCount 等）
    //         ...order          // orderArr 中的字段（如 order_code, service_type 等）
    //       });
    //     });
    //   });
    //   return result;
    // },

    shouldRenderItem(item, product) {
      if (item.condition && typeof item.condition === 'function') {
        const conditionResult = item.condition(product)
        if(!conditionResult) {
          // item.span = 0
        }
        return conditionResult
      }
      return true;
    },
    buildDataCount(product, parsedFilter) {
      const { pNum, give_cycle } = parsedFilter;
      const totalNums = Number(pNum) + (Number(give_cycle) || 0);
      const { product_type } = product;
      const includeProductType = ['数据流量包', '历史数据', '结构化数据']
      if(includeProductType.includes(product_type) && totalNums) {
        return `付费${pNum || 0}条，赠送${give_cycle || 0}条，合计<span class="color_main">${totalNums}</span>条`; 
      } else {
        return '';
      }
    },
    buildReportNumber(product, parsedFilter) {
      const { num } = parsedFilter;
      const { product_type } = product;
      const includeProductType = this.reportType
      if(includeProductType.includes(product_type) && num) {
        return `${num || 0}份`;
      } else {
        if(product_type === '投标企业信用报告') {
          return '1份';
        } else {
          return '';
        }
      }
    },
    buildCoinCount(product, parsedFilter) {
      const { num } = parsedFilter;
      const { product_type } = product;
      const includeProductType = ['剑鱼币']
      if(includeProductType.includes(product_type) && num) {
        return `${num || 0}个`;
      } else {
        return '';
      }
    },
    buildBuyProductName(product, parsedFilter) {
      const { product: buy_product } = parsedFilter;
      const { product_type } = product;
      const includeProductType = ['结构化数据']
      if(includeProductType.includes(product_type) && buy_product) {
        return buy_product || '-'; 
      } else {
        return '';
      }
    },
    divided(a, b) {
      return div(a, b)
    },
    calculateValidityPeriod(parsedFilter, product) {
      const { buy_cycle, buy_type, give_cycle, give_type, validYear, activity_give_cycle, activity_give_type } = parsedFilter;
      const { product_type, returned_open } = product;
      const returned_opens = returned_open === 1 ? '（全额回款当日开通）' : '';
      if (product_type === '数据流量包') {
        // 数据流量包默认2年
        return `${validYear || 2}年${returned_opens}`;
      }

      const TIME_MAP = {
        '1': '日',
        '2': '月',
        '3': '年',
        '4': '季度'
      };

      // 安全地将字符串转为整数，默认为 0
      const parseCycle = (cycle) => {
        const num = parseInt(cycle);
        return isNaN(num) ? 0 : num;
      };

      // 处理单个周期，返回文本和总天数
      const processCycle = (cycle, type) => {
        const textValue = TIME_MAP[type] || '';
        const value = parseCycle(cycle);

        let days = 0;
        let text = '';

        if (textValue.includes('日')) {
          days += value;
          text = `${value}日`;
        } else if (textValue.includes('月')) {
          days += value * 30;
          text = `${value}个月`;
        } else if (textValue.includes('季度')) {
          days += value * 90;
          text = `${value}季度`;
        } else if (textValue.includes('年')) {
          days += value * 365;
          text = `${value}年`;
        }
        return { days, text };
      };

      // 计算购买和赠送部分
      const buyResult = processCycle(buy_cycle, buy_type);
      const giveResult = processCycle(give_cycle, give_type);

      // 总天数
      let totalDays = buyResult.days + giveResult.days;

      // 活动赠送时长
      let activityGiveResult = ''
      if (activity_give_cycle) {
        activityGiveResult = processCycle(activity_give_cycle, activity_give_type);
        totalDays += activityGiveResult.days;
      }
      if (totalDays <= 0) return '-';
      let totalText = '';
      if(buy_type === 1) {
        totalText = `${totalDays}日`;
      } else if(buy_type === 3) {
        if(totalDays % 365 === 0) {
          totalText = `${Math.floor(totalDays / 365)}年`;
        } else {
          // 获取年份
          const year = Math.floor(totalDays / 365);
          // 获取不够一年的天数
          const lessYearDays = totalDays % 365;
          if(lessYearDays % 30 === 0) {
            totalText = `${year ? year + '年' : ''}${Math.floor(lessYearDays / 30)}个月`; 
          } else {
            totalText = `${year ? year + '年' : ''}${lessYearDays % 30}日`;
          }
        }
      } else {
        if(totalDays % 30 === 0) {
          totalText = `${Math.floor(totalDays / 30)}个月`;
        } else {
          // 如果天数小于30天，则不显示月，只显示天
          const isHas30Days = totalDays / 30 < 1;
          totalText = `${isHas30Days ? totalDays % 30 : Math.floor(totalDays / 30)}个月${totalDays % 30}日`;
          if(isHas30Days) {
            totalText = `${totalDays % 30}日`;
          } else {
            totalText = `${Math.floor(totalDays / 30)}个月${totalDays % 30}日`;
          }
        }
      }
      let giveResultText = giveResult.text ? `赠送${giveResult.text}，` : '';
      if(activityGiveResult) {
        giveResultText = giveResult.text ? `销售赠${giveResult.text}，` : '';
        return `付费${buyResult.text}，活动赠${activityGiveResult.text}，${giveResultText}合计<span class="color_main">${totalText}</span>${returned_opens}`; 
      }
      // 如果是赠送类产品，则只显示赠送时长和合计时长, 不显示付费时长
      if(product.tactics === '2') {
        return `${giveResultText}合计<span class="color_main">${totalText}</span>${returned_opens}`
      }
      return `付费${buyResult.text}，${giveResultText}合计<span class="color_main">${totalText}</span>${returned_opens}`;
    },

    getValidityPeriodHtml(product, item) {
      const label = item.label;
      const value = product[item.key] || '-';
      return `${label}：${value}`;
    },

    // 替代过滤器的通用方法
    getFilteredValue(value, filterName) {
      // 判断value是否是数字，或者是字符串数字
      if (typeof value === 'number' || /^\d+$/.test(value)) {
        if(!value && filterName !== 'orderServiceType') return '0.00'
      }
      if (!filterName) return value || '-';
      return this[filterName](value);
    },
    setProductTitle(product, index) {
      const tactics = product.tactics === '2' ? '【赠送】' : '【售卖】';
      if(product.product_type === 'VIP订阅') {
        return `${index + 1}.${tactics}超级订阅`;
      }
      return `${index + 1}.${tactics}${product.product_type}`;
    },
    // 格式化数字，保留两位小数
    formatNumber(num, x = 2) {
      if(!num) return 0.00
      const newnum = Number(num) / 100;
      return roundToTwoDecimals(newnum, x)
    },
    orderCoursed(val) {
        if (val == 0) {
            return '待提交'
        } else if (val == 1) {
            return '待一审'
        } else if (val == 2) {
            return '待二审'
        } else if (val == 4) {
            return '待三审'
        } else if (val == 3) {
            return '已通过'
        } else if (val == -2 || val == -3 || val == -4) {
            return '已退回'
        }
    },
    orderServiceType(val) {
      const matchedOption = paymentTypeOptions.find(option => option.value === val);
      return matchedOption ? matchedOption.label : val; // 如果未找到匹配项，返回原始值
    },
    orderStatus(val) {
        if (!val || val == 0) {
            return '未完成'
        } else if (val == 1) {
            return '已完成'
        } else if (val == -1) {
            return '逻辑删除'
        } else if (val == -2) {
            return '已取消'
        } else if (val == -3) {
            return '已退款'
        } else if (val == -3) {
            return '已退款'
        }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex <= 3) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail-card-container {
  background: #F2F2F4;

  .product-form {
    padding: 16px 8px;
    ::v-deep {
      .el-form-item__label {
        font-size: 14px;
        line-height: 22px;
        color: #1d1d1d;
      }
    }
  }
  ::v-deep {
    .info-card-header {
      display: none;
    }
    .info-card {
      margin-bottom: 16px;
      padding: 0;
    }
  }
  .order-detail-card-content {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 6px;
  }
  .order-detail-product-actions-btn {
    padding: 4px 17px;
    background: $color_main;
    font-size: 14px;
    line-height: 22px;
    color: $white;
    border-radius: 4px;
    border: none;
    cursor: pointer;
  }
  .grouped-items {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
    .item-span-1 {
      width: 100%;
    }

    .item-span-3 {
      min-width: 255px;
    }
  }
  .order-detail-product-content {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 6px;
    padding: 0 24px;
  }
  .order-detail-card-item {
    min-width: 255px;
    margin-right: 32px;
    margin-bottom: 10px;
    font-size: 14px;
    line-height: 22px;
    color: $gray_10;
    .linkedOrder {
      display: flex;
      align-items: flex-start;
    }
  }
  .red-chong {
    color: $red_light;
  }
  .no_open_root {
    color: $red_light;
  }
  ::v-deep {
    .color_main {
      color: #2ABED1;
    }
  }
  .activity-product-container {
    padding: 14px 20px;
    border-radius: 8px;
    border: 1px solid $main;
    background-color: rgba($main, 0.08);
    .desc-detail-info-list  {
      margin-top: 8px;
    }
    ::v-deep {
      .desc-label {
      font-size: 14px;
      line-height: 22px;
        color: #686868;
    }
      .desc-value  {
        font-size: 14px;
        line-height: 22px;
        color: #1D1D1D;
      }
    }
  }
  .detail-order-table {
    &.relate-order-table {
      width: 100%;
    }
  }
}
</style>
