<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.djmdName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开单会员">
              <el-input v-model="dataForm.kdhyc" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开单日期">
              <el-date-picker
                v-model="dataForm.kdrq"
                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.zdyj" 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.sfyj" disabled>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 品项明细 -->
        <el-form-item label="品项明细">
          <el-table :data="dataForm.lqKdPxmxList" 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.lqKdPxmxList"
          :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.lqKdJksyjList"
                border
                size="mini"
                style="width: 100%"
                v-if="px.lqKdJksyjList && px.lqKdJksyjList.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 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.lqKdKjbsyjList && px.lqKdKjbsyjList.length > 0">
              <div style="margin-bottom: 10px; font-weight: 600; color: #67C23A">
                <i class="el-icon-user-solid"></i> 科技部老师业绩
              </div>
              <el-table
                :data="px.lqKdKjbsyjList"
                border
                size="mini"
                style="width: 100%"
              >
                <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 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>
          </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,
      billingId: null,
      dataForm: {
        id: '',
        djmd: '',
        djmdName: '',
        kdhy: '',
        kdhyc: '',
        kdhysjh: '',
        kdrq: '',
        gjlx: '',
        jsj: '',
        hgjg: '',
        fkyy: '',
        zdyj: '',
        sfyj: '',
        jj: '',
        bz: '',
        activityId: '',
        appointmentId: '',
        lqKdPxmxList: []
      },
      djmdOptions: []
    }
  },
  created() {
    this.loadOptions()
  },
  methods: {
    // 初始化弹窗
    init(billingId) {
      this.billingId = billingId
      this.visible = true
      this.$nextTick(() => {
        if (this.billingId) {
          this.getBillingDetail(this.billingId)
        } else {
          // 新建对冲时，开单日期默认取当前时间（时间戳，配合 value-format="timestamp"）
          this.dataForm.kdrq = new Date().getTime()
        }
      })
    },
    // 获取开单详情
    async getBillingDetail(id) {
      this.loading = true
      try {
        const res = await request({
          url: `/api/Extend/LqKdKdjlb/${id}`,
          method: 'GET'
        })
        if (res.code === 200) {
          // 深拷贝数据，避免修改原数据
          const billingData = JSON.parse(JSON.stringify(res.data))
          
          // 处理品项明细数据
          if (billingData.lqKdPxmxList && billingData.lqKdPxmxList.length > 0) {
            billingData.lqKdPxmxList = billingData.lqKdPxmxList.map(px => {
              // 保存原始项目次数
              const 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,
                memberId: px.memberId || billingData.kdhy,
                sourceType: px.sourceType || '购买',
                // 处理健康师业绩
                lqKdJksyjList: (px.lqKdJksyjList || []).map(jks => {
                  const originalJksyj = parseFloat(jks.jksyj) || 0
                  
                  return {
                    ...jks,
                    jksyj: originalJksyj,
                    originalJksyj: originalJksyj // 保存原始业绩
                  }
                }),
                // 处理科技部老师业绩
                lqKdKjbsyjList: (px.lqKdKjbsyjList || []).map(kjb => {
                  const originalKjblsyj = parseFloat(kjb.kjblsyj) || 0
                  
                  return {
                    ...kjb,
                    kjblsyj: originalKjblsyj,
                    originalKjblsyj: originalKjblsyj // 保存原始业绩
                  }
                })
              }
              return pxItem
            })
          }

          // 处理开单日期
          billingData.kdrq = new Date().getTime()
          
          // 获取门店名称
          const djmdName = this.getStoreName(billingData.djmd)
          
          this.dataForm = {
            id: '',
            djmd: billingData.djmd || '',
            djmdName: djmdName || '',
            kdhy: billingData.kdhy || '',
            kdhyc: billingData.kdhyc || '',
            kdhysjh: billingData.kdhysjh || '',
            kdrq: billingData.kdrq,
            gjlx: billingData.gjlx || '',
            jsj: billingData.jsj || '',
            hgjg: billingData.hgjg || '',
            fkyy: billingData.fkyy || '',
            zdyj: '0.00',
            sfyj: '0.00',
            jj: billingData.jj || '',
            bz: billingData.bz || '',
            activityId: billingData.activityId || '',
            appointmentId: billingData.appointmentId || '',
            lqKdPxmxList: billingData.lqKdPxmxList || []
          }

          // 计算总金额
          this.calculateTotalAmounts()
        } else {
          this.$message.error(res.msg || '获取开单详情失败')
        }
      } catch (error) {
        console.error('获取开单详情失败:', error)
        this.$message.error('获取开单详情失败')
      } finally {
        this.loading = false
      }
    },
    // 加载选项数据
    loadOptions() {
      previewDataInterface('730960205902251269').then(res => {
        this.djmdOptions = res.data || []
      })
    },
    // 获取门店名称
    getStoreName(storeId) {
      const store = this.djmdOptions.find(item => item.id === storeId)
      return store ? store.fullName : ''
    },
    // 计算品项总价
    calculatePxTotal(pxIndex) {
      const px = this.dataForm.lqKdPxmxList[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.lqKdJksyjList && px.lqKdJksyjList.length > 0) {
          px.lqKdJksyjList.forEach(jks => {
            // 按比例计算
            if (jks.originalJksyj !== undefined) {
              jks.jksyj = parseFloat((jks.originalJksyj * ratio).toFixed(2))
            }
          })
        }
        
        // 按比例重新计算科技部老师的业绩
        if (px.lqKdKjbsyjList && px.lqKdKjbsyjList.length > 0) {
          px.lqKdKjbsyjList.forEach(kjb => {
            // 按比例计算
            if (kjb.originalKjblsyj !== undefined) {
              kjb.kjblsyj = parseFloat((kjb.originalKjblsyj * ratio).toFixed(2))
            }
          })
        }
        
        this.calculateTotalAmounts()
      }
    },
    // 计算总金额
    calculateTotalAmounts() {
      let totalZdyj = 0
      let totalSfyj = 0

      this.dataForm.lqKdPxmxList.forEach(px => {
        if (px.pxjg && px.projectNumber) {
          totalZdyj += parseFloat(px.pxjg) * parseFloat(px.projectNumber)
        }
        
        // 计算实付业绩：健康师业绩 + 科技部老师业绩
        if (px.lqKdJksyjList && px.lqKdJksyjList.length > 0) {
          px.lqKdJksyjList.forEach(jks => {
            totalSfyj += parseFloat(jks.jksyj) || 0
          })
        }
        if (px.lqKdKjbsyjList && px.lqKdKjbsyjList.length > 0) {
          px.lqKdKjbsyjList.forEach(kjb => {
            totalSfyj += parseFloat(kjb.kjblsyj) || 0
          })
        }
      })

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

      if (!this.dataForm.kdrq) {
        this.$message.warning('请选择开单日期')
        return
      }

      // 过滤掉空的品项
      const filteredPxList = this.dataForm.lqKdPxmxList
        .filter(px => px.px && px.pxmc)
        .map(px => ({
          billingItemId: px.BillingItemId || px.billingItemId || px.px,
          px: px.px,
          memberId: px.memberId || this.dataForm.kdhy,
          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),
          actualPrice: (parseFloat(px.pxjg) || 0) * (parseFloat(px.projectNumber) || 0),
          lqKdJksyjList: (px.lqKdJksyjList || []).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
          })),
          lqKdKjbsyjList: (px.lqKdKjbsyjList || []).map(kjb => ({
            kjbls: kjb.kjbls,
            kjblsxm: kjb.kjblsxm,
            kjblszh: kjb.kjblszh || kjb.kjbls,
            kjblsyj: parseFloat(kjb.kjblsyj) || 0,
            kdpxid: px.BillingItemId || px.billingItemId || px.px
          }))
        }))

      // 处理开单日期
      let kdrqValue = new Date().toISOString()
      if (this.dataForm.kdrq) {
        const date = new Date(this.dataForm.kdrq)
        kdrqValue = date.toISOString()
      }

      const formData = {
        activityId: this.dataForm.activityId || '',
        djmd: this.dataForm.djmd,
        jsj: this.dataForm.jsj,
        kdrq: kdrqValue,
        gjlx: this.dataForm.gjlx,
        kdhysjh: this.dataForm.kdhysjh,
        kdhyc: this.dataForm.kdhyc,
        kdhy: this.dataForm.kdhy,
        zdyj: this.dataForm.zdyj,
        sfyj: this.dataForm.sfyj,
        qk: 0, // 对冲开单欠款为0
        fkfs: '对冲', // 付款方式为对冲
        hgjg: this.dataForm.hgjg || '',
        fkyy: this.dataForm.fkyy || '',
        sfskdd: '否', // 对冲开单不是首开订单
        jj: this.dataForm.jj || '',
        bz: this.dataForm.bz || '',
        lqKdPxmxList: filteredPxList,
        scwj: [], // 对冲开单不需要收据文件
        f_FileUrl: '[]', // 对冲开单不需要方案其他文件
        lqKdKdjlbDeductList: [], // 对冲开单不需要储扣明细
        hyqz: [] // 对冲开单不需要会员签字
      }
      
      // 如果有预约ID，则添加
      if (this.dataForm.appointmentId) {
        formData.appointmentId = this.dataForm.appointmentId
      }

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

      this.submitLoading = true
      try {
        const result = await request({
          url: '/api/Extend/LqKdKdjlb',
          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: '',
        djmd: '',
        djmdName: '',
        kdhy: '',
        kdhyc: '',
        kdhysjh: '',
        kdrq: '',
        gjlx: '',
        jsj: '',
        hgjg: '',
        fkyy: '',
        zdyj: '',
        sfyj: '',
        jj: '',
        bz: '',
        activityId: '',
        appointmentId: '',
        lqKdPxmxList: []
      }
      this.billingId = null
    }
  }
}
</script>

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

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

