<template>
  <el-dialog
    title="对冲耗卡"
    :visible.sync="visible"
    :close-on-click-modal="false"
    class="NCC-dialog NCC-dialog_center"
    lock-scroll
    width="1400px"
    @close="handleClose"
  >
    <div v-loading="loading">
      <el-form ref="elForm" :model="dataForm" size="small" label-width="120px" label-position="right">
        <!-- 基本信息 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="门店">
              <el-input v-model="dataForm.mdmc" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="会员">
              <el-input v-model="dataForm.hymc" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="耗卡时间">
              <el-date-picker
                v-model="dataForm.hksj"
                type="date"
                format="yyyy-MM-dd"
                value-format="timestamp"
                placeholder="请选择耗卡时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 费用信息 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="消费金额">
              <el-input v-model="dataForm.xfje" disabled>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手工费用">
              <el-input v-model="dataForm.sgfy" disabled>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否加班">
              <el-select v-model="dataForm.overtimeCoefficient" placeholder="请选择加班系数" clearable style="width: 100%">
                <el-option label="否" :value="0"></el-option>
                <el-option label="0.5" :value="0.5"></el-option>
                <el-option label="1" :value="1"></el-option>
                <el-option label="1.5" :value="1.5"></el-option>
                <el-option label="2" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 品项明细 -->
        <el-form-item label="品项明细">
          <el-table :data="dataForm.lqXhPxmxList" border size="small" style="width: 100%">
            <el-table-column prop="pxmc" label="品项名称" align="left">
              <template slot-scope="scope">
                <span>{{ scope.row.pxmc || '无' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pxjg" label="单价"  align="right">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.pxjg"
                  :precision="2"
                  :step="0.01"
                  :min="-999999"
                  :max="999999"
                  size="small"
                  style="width: 100%"
                  @change="calculatePxTotal(scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="projectNumber" label="次数"  align="right">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.projectNumber"
                  :precision="2"
                  :step="0.01"
                  :min="-999999"
                  :max="999999"
                  size="small"
                  style="width: 100%"
                  @change="calculatePxTotal(scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="总价"  align="right">
              <template slot-scope="scope">
                <span>{{ formatMoney(scope.row.totalPrice) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sourceType" label="来源类型"  align="center">
              <template slot-scope="scope">
                <el-tag size="small">{{ scope.row.sourceType || '无' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="deletePxRow(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 健康师和科技部老师业绩 -->
        <el-form-item
          v-for="(px, pxIndex) in dataForm.lqXhPxmxList"
          :key="pxIndex"
          :label="`品项${pxIndex + 1} - ${px.pxmc || '无'}`"
        >
          <el-card shadow="never" style="margin-bottom: 20px">
            <!-- 健康师业绩 -->
            <div style="margin-bottom: 20px">
              <div style="margin-bottom: 10px; font-weight: 600; color: #409EFF">
                <i class="el-icon-user"></i> 健康师业绩
              </div>
              <el-table
                :data="px.lqXhJksyjList"
                border
                size="mini"
                style="width: 100%"
                v-if="px.lqXhJksyjList && px.lqXhJksyjList.length > 0"
              >
                <el-table-column prop="jksxm" label="健康师"  align="left">
                  <template slot-scope="scope">
                    <span>{{ scope.row.jksxm || '无' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="jksyj" label="业绩" align="right">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.jksyj"
                      :precision="2"
                      :step="0.01"
                      :min="-999999"
                      :max="999999"
                      size="mini"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="kdpxNumber" label="次数"  align="right">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.kdpxNumber"
                      :precision="2"
                      :step="0.01"
                      :min="-999999"
                      :max="999999"
                      size="mini"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="laborCost" label="手工费"  align="right">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.laborCost"
                      :precision="2"
                      :step="0.01"
                      :min="-999999"
                      :max="999999"
                      size="mini"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      @click="deleteJks(pxIndex, scope.$index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-else style="padding: 10px; color: #909399; text-align: center">
                暂无健康师
              </div>
            </div>

            <!-- 科技部老师业绩 -->
            <div v-if="px.qt2 === '科美' || (px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0)">
              <div style="margin-bottom: 10px; font-weight: 600; color: #67C23A">
                <i class="el-icon-user-solid"></i> 科技部老师业绩
              </div>
              <el-table
                :data="px.lqXhKjbsyjList"
                border
                size="mini"
                style="width: 100%"
                v-if="px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0"
              >
                <el-table-column prop="kjblsxm" label="科技部老师"  align="left">
                  <template slot-scope="scope">
                    <span>{{ scope.row.kjblsxm || '无' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="kjblsyj" label="业绩"  align="right">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.kjblsyj"
                      :precision="2"
                      :step="0.01"
                      :min="-999999"
                      :max="999999"
                      size="mini"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="hdpxNumber" label="次数"  align="right">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.hdpxNumber"
                      :precision="2"
                      :step="0.01"
                      :min="-999999"
                      :max="999999"
                      size="mini"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="laborCost" label="手工费"  align="right">
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.laborCost"
                      :precision="2"
                      :step="0.01"
                      :min="-999999"
                      :max="999999"
                      size="mini"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      @click="deleteKjb(pxIndex, scope.$index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-else style="padding: 10px; color: #909399; text-align: center">
                暂无科技部老师
              </div>
            </div>
          </el-card>
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitHedge">提交对冲</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { previewDataInterface } from '@/api/systemData/dataInterface'

export default {
  name: 'HedgeDialog',
  data() {
    return {
      visible: false,
      loading: false,
      submitLoading: false,
      consumeId: null,
      dataForm: {
        id: '',
        md: '',
        mdbh: '',
        mdmc: '',
        hy: '',
        hyzh: '',
        hymc: '',
        gklx: '',
        xfje: '',
        sgfy: '',
        hksj: '',
        overtimeCoefficient: 0, // 加班系数，默认0
        lqXhPxmxList: []
      },
      mdOptions: []
    }
  },
  created() {
    this.loadOptions()
  },
  methods: {
    // 初始化弹窗
    init(consumeId) {
      this.consumeId = consumeId
      this.visible = true
      this.$nextTick(() => {
        if (this.consumeId) {
          this.getConsumeDetail(this.consumeId)
        } else {
          // 新建对冲时，耗卡时间默认取当前时间（时间戳，配合 value-format="timestamp"）
          this.dataForm.hksj = new Date().getTime()
        }
      })
    },
    // 获取耗卡详情
    async getConsumeDetail(id) {
      this.loading = true
      try {
        const res = await request({
          url: `/api/Extend/LqXhHyhk/${id}`,
          method: 'GET'
        })
        if (res.code === 200) {
          // 深拷贝数据，避免修改原数据
          const consumeData = JSON.parse(JSON.stringify(res.data))
          
          // 处理品项明细数据
          if (consumeData.lqXhPxmxList && consumeData.lqXhPxmxList.length > 0) {
            consumeData.lqXhPxmxList = consumeData.lqXhPxmxList.map(px => {
              // 参考 H5 版本：优先使用 originalProjectNumber，如果没有则使用 projectNumber
              const originalProjectNumber = parseFloat(px.originalProjectNumber) || parseFloat(px.projectNumber) || 0
              
              // 确保所有数值字段都存在，并保留所有原始字段
              const pxItem = {
                ...px,
                pxjg: parseFloat(px.pxjg) || 0,
                projectNumber: originalProjectNumber, // 使用原始项目次数
                originalProjectNumber: originalProjectNumber, // 保存原始次数
                totalPrice: (parseFloat(px.pxjg) || 0) * originalProjectNumber,
                // 保留品项的关键字段
                BillingItemId: px.BillingItemId || px.billingItemId || px.px,
                qt2: px.qt2 || '',
                memberId: px.memberId || consumeData.hy,
                sourceType: px.sourceType || '购买',
                // 对冲不考虑陪同，过滤掉陪同健康师（isAccompanied == 1）
                lqXhJksyjList: (px.lqXhJksyjList || [])
                  .filter(jks => !jks.isAccompanied || jks.isAccompanied === 0) // 过滤掉陪同健康师
                  .map(jks => {
                    // 参考 H5 版本：优先使用 originalKdpxNumber 和 originalLaborCost
                    const originalJksyj = parseFloat(jks.jksyj) || 0
                    const originalKdpxNumber = parseFloat(jks.originalKdpxNumber) || parseFloat(jks.kdpxNumber) || 0
                    const originalLaborCost = parseFloat(jks.originalLaborCost) || parseFloat(jks.laborCost) || 0
                    
                    return {
                      ...jks,
                      jksyj: originalJksyj,
                      originalJksyj: originalJksyj, // 保存原始业绩
                      kdpxNumber: originalKdpxNumber, // 使用原始次数
                      originalKdpxNumber: originalKdpxNumber, // 保存原始次数
                      laborCost: originalLaborCost, // 使用原始手工费
                      originalLaborCost: originalLaborCost // 保存原始手工费
                    }
                  }),
                lqXhKjbsyjList: (px.lqXhKjbsyjList || []).map(kjb => {
                  // 参考 H5 版本：优先使用 originalHdpxNumber 和 originalLaborCost
                  const originalKjblsyj = parseFloat(kjb.kjblsyj) || 0
                  const originalHdpxNumber = parseFloat(kjb.originalHdpxNumber) || parseFloat(kjb.hdpxNumber) || 0
                  const originalLaborCost = parseFloat(kjb.originalLaborCost) || parseFloat(kjb.laborCost) || 0
                  
                  return {
                    ...kjb,
                    kjblsyj: originalKjblsyj,
                    originalKjblsyj: originalKjblsyj, // 保存原始业绩
                    hdpxNumber: originalHdpxNumber, // 使用原始次数
                    originalHdpxNumber: originalHdpxNumber, // 保存原始次数
                    laborCost: originalLaborCost, // 使用原始手工费
                    originalLaborCost: originalLaborCost // 保存原始手工费
                  }
                })
              }
              return pxItem
            })
          }

          // 处理耗卡时间
          // if (consumeData.hksj) {
          //   // 如果是字符串，转换为时间戳
          //   if (typeof consumeData.hksj === 'string') {
          //     consumeData.hksj = new Date(consumeData.hksj).getTime()
          //   }
          // } else {
          //   // 默认使用当前时间
          //   consumeData.hksj = new Date().getTime()
          // }
          consumeData.hksj = new Date().getTime()
          this.dataForm = {
            id: '',
            md: consumeData.md || '',
            mdbh: consumeData.mdbh || '',
            mdmc: consumeData.mdmc || '',
            hy: consumeData.hy || '',
            hyzh: consumeData.hyzh || '',
            hymc: consumeData.hymc || '',
            gklx: consumeData.gklx || '',
            xfje: '0.00',
            sgfy: '0.00',
            hksj: consumeData.hksj,
            overtimeCoefficient: parseFloat(consumeData.overtimeCoefficient) || 0, // 读取加班系数
            lqXhPxmxList: consumeData.lqXhPxmxList || []
          }

          // 计算总金额
          this.calculateTotalAmounts()
          
          // 调试日志：检查科技部老师数据
          console.log('对冲数据加载完成:', {
            pxList: this.dataForm.lqXhPxmxList.map(px => ({
              pxmc: px.pxmc,
              qt2: px.qt2,
              hasKjb: px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0,
              kjbList: px.lqXhKjbsyjList
            }))
          })
        } else {
          this.$message.error(res.msg || '获取耗卡详情失败')
        }
      } catch (error) {
        console.error('获取耗卡详情失败:', error)
        this.$message.error('获取耗卡详情失败')
      } finally {
        this.loading = false
      }
    },
    // 加载选项数据
    loadOptions() {
      previewDataInterface('730960205902251269').then(res => {
        this.mdOptions = res.data || []
      })
    },
    // 计算品项总价
    calculatePxTotal(pxIndex) {
      const px = this.dataForm.lqXhPxmxList[pxIndex]
      if (px) {
        const newProjectNumber = parseFloat(px.projectNumber) || 0
        const originalProjectNumber = parseFloat(px.originalProjectNumber) || 1 // 避免除0
        
        // 计算比例
        const ratio = originalProjectNumber !== 0 ? newProjectNumber / originalProjectNumber : 0
        
        px.totalPrice = (parseFloat(px.pxjg) || 0) * newProjectNumber
        
        // 按比例重新计算健康师的业绩、次数、手工费（已过滤陪同健康师，无需再检查）
        if (px.lqXhJksyjList && px.lqXhJksyjList.length > 0) {
          px.lqXhJksyjList.forEach(jks => {
            // 按比例计算
            if (jks.originalJksyj !== undefined) {
              jks.jksyj = parseFloat((jks.originalJksyj * ratio).toFixed(2))
            }
            if (jks.originalKdpxNumber !== undefined) {
              jks.kdpxNumber = parseFloat((jks.originalKdpxNumber * ratio).toFixed(2))
            }
            if (jks.originalLaborCost !== undefined) {
              jks.laborCost = parseFloat((jks.originalLaborCost * ratio).toFixed(2))
            }
          })
        }
        
        // 按比例重新计算科技部老师的业绩、次数、手工费
        if (px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0) {
          px.lqXhKjbsyjList.forEach(kjb => {
            // 按比例计算
            if (kjb.originalKjblsyj !== undefined) {
              kjb.kjblsyj = parseFloat((kjb.originalKjblsyj * ratio).toFixed(2))
            }
            if (kjb.originalHdpxNumber !== undefined) {
              kjb.hdpxNumber = parseFloat((kjb.originalHdpxNumber * ratio).toFixed(2))
            }
            if (kjb.originalLaborCost !== undefined) {
              kjb.laborCost = parseFloat((kjb.originalLaborCost * ratio).toFixed(2))
            }
          })
        }
        
        this.calculateTotalAmounts()
      }
    },
    // 计算总消费金额和手工费用
    calculateTotalAmounts() {
      let totalXfje = 0
      let totalSgfy = 0

      this.dataForm.lqXhPxmxList.forEach(px => {
        if (px.pxjg && px.projectNumber) {
          totalXfje += parseFloat(px.pxjg) * parseFloat(px.projectNumber)
        }
        
        // 计算手工费：健康师手工费 + 科技部老师手工费
        if (px.lqXhJksyjList && px.lqXhJksyjList.length > 0) {
          px.lqXhJksyjList.forEach(jks => {
            totalSgfy += parseFloat(jks.laborCost) || 0
          })
        }
        if (px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0) {
          px.lqXhKjbsyjList.forEach(kjb => {
            totalSgfy += parseFloat(kjb.laborCost) || 0
          })
        }
      })

      this.dataForm.xfje = totalXfje.toFixed(2)
      this.dataForm.sgfy = totalSgfy.toFixed(2)
    },
    // 删除品项
    deletePxRow(pxIndex) {
      if (this.dataForm.lqXhPxmxList.length <= 1) {
        this.$message.warning('至少需要保留一个品项')
        return
      }
      this.$confirm('确定要删除该品项吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.dataForm.lqXhPxmxList.splice(pxIndex, 1)
          this.calculateTotalAmounts()
        })
        .catch(() => {})
    },
    // 删除健康师
    deleteJks(pxIndex, jksIndex) {
      const px = this.dataForm.lqXhPxmxList[pxIndex]
      if (px && px.lqXhJksyjList) {
        px.lqXhJksyjList.splice(jksIndex, 1)
        this.calculateTotalAmounts()
      }
    },
    // 删除科技部老师
    deleteKjb(pxIndex, kjbIndex) {
      const px = this.dataForm.lqXhPxmxList[pxIndex]
      if (px && px.lqXhKjbsyjList) {
        px.lqXhKjbsyjList.splice(kjbIndex, 1)
        this.calculateTotalAmounts()
      }
    },
    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return Number(amount).toFixed(2)
    },
    // 提交对冲
    async submitHedge() {
      // 验证表单
      if (!this.dataForm.lqXhPxmxList || this.dataForm.lqXhPxmxList.length === 0) {
        this.$message.warning('至少需要保留一个品项')
        return
      }

      if (!this.dataForm.hksj) {
        this.$message.warning('请选择耗卡时间')
        return
      }

      // 过滤掉空的品项
      const filteredPxList = this.dataForm.lqXhPxmxList
        .filter(px => px.px && px.pxmc)
        .map(px => ({
          billingItemId: px.BillingItemId || px.billingItemId || px.px,
          px: px.px,
          memberId: px.memberId || this.dataForm.hy,
          pxmc: px.pxmc,
          pxjg: parseFloat(px.pxjg) || 0,
          projectNumber: parseFloat(px.projectNumber) || 0,
          sourceType: px.sourceType || '购买',
          totalPrice: (parseFloat(px.pxjg) || 0) * (parseFloat(px.projectNumber) || 0),
          qt2: px.qt2 || '', // 保留品项类型
          // 对冲不考虑陪同，已过滤掉陪同健康师，提交时也不包含陪同相关字段
          lqXhJksyjList: (px.lqXhJksyjList || []).map(jks => ({
            jks: jks.jks,
            jksxm: jks.jksxm,
            jkszh: jks.jkszh || jks.jks,
            jksyj: parseFloat(jks.jksyj) || 0,
            jsjId: jks.jsjId || '',
            kdpxid: px.BillingItemId || px.billingItemId || px.px,
            laborCost: parseFloat(jks.laborCost) || 0,
            kdpxNumber: parseFloat(jks.kdpxNumber) || 0,
            isAccompanied: 0, // 对冲不考虑陪同，固定为0
            accompaniedProjectNumber: 0 // 对冲不考虑陪同，固定为0
          })),
          lqXhKjbsyjList: (px.lqXhKjbsyjList || []).map(kjb => ({
            kjbls: kjb.kjbls,
            kjblsxm: kjb.kjblsxm,
            kjblszh: kjb.kjblszh || kjb.kjbls,
            kjblsyj: parseFloat(kjb.kjblsyj) || 0,
            hkpxid: px.BillingItemId || px.billingItemId || px.px,
            laborCost: parseFloat(kjb.laborCost) || 0,
            hdpxNumber: parseFloat(kjb.hdpxNumber) || 0
          }))
        }))

      // 处理耗卡时间
      let hksjValue = new Date().toISOString()
      if (this.dataForm.hksj) {
        const date = new Date(this.dataForm.hksj)
        hksjValue = date.toISOString()
      }

      // 检查是否有科美品项
      const hasKemei = filteredPxList.some(px => px.qt2 === '科美')

        const formData = {
          md: this.dataForm.md,
          mdbh: this.dataForm.mdbh,
          mdmc: this.dataForm.mdmc,
          hy: this.dataForm.hy,
          hyzh: this.dataForm.hyzh,
          hymc: this.dataForm.hymc,
          gklx: this.dataForm.gklx,
          xfje: this.dataForm.xfje,
          sgfy: this.dataForm.sgfy,
          hksj: hksjValue,
          sfykjb: hasKemei ? '是' : '否',
          lqXhPxmxList: filteredPxList,
          signatureFile: '[]',
          overtimeCoefficient: parseFloat(this.dataForm.overtimeCoefficient) || 0 // 提交加班系数
        }

      console.log('对冲数据:', formData)

      this.submitLoading = true
      try {
        const result = await request({
          url: '/api/Extend/LqXhHyhk',
          method: 'POST',
          data: formData
        })

        if (result.code === 200) {
          this.$message.success('对冲成功！')
          this.handleClose()
          this.$emit('refresh')
        } else {
          this.$message.error(result.msg || '对冲失败，请重试')
        }
      } catch (error) {
        console.error('对冲失败:', error)
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.submitLoading = false
      }
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false
      this.dataForm = {
        id: '',
        md: '',
        mdbh: '',
        mdmc: '',
        hy: '',
        hyzh: '',
        hymc: '',
        gklx: '',
        xfje: '',
        sgfy: '',
        hksj: '',
        overtimeCoefficient: 0,
        lqXhPxmxList: []
      }
      this.consumeId = null
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
  padding: 20px 0;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>

