<template>
  <div class="form-wrap">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="团队管理" name="teamManage">
        <el-form
          class="search-box"
          ref="form"
          :model="form"
          :inline="true"
        >
          <div class="block-title">
            查询条件
          </div>
          <el-form-item
            label="团队名称"
            prop="name">
            <el-input v-model="form.name" clearable></el-input>
          </el-form-item>
          <el-form-item
            label="联系人"
            prop="contactName">
            <el-input v-model="form.contactName" clearable></el-input>
          </el-form-item>
          <el-form-item
            label="联系方式"
            prop="contactPhone">
            <el-input v-model="form.contactPhone" clearable></el-input>
          </el-form-item>
          <el-form-item
            label="备注"
            prop="remark">
            <el-input v-model="form.remark" clearable></el-input>
          </el-form-item>
          <div class="btn-wrap">
            <el-button
              @click="reset">
              重置
            </el-button>
            <el-button
              type="primary"
              @click="getList(true)">
              搜索
            </el-button>
            <el-button
              type="primary"
              @click="openAddDialog">
              新增团队
            </el-button>
            <el-button
              type="primary"
              @click="reportExport">
              导出
            </el-button>
          </div>
        </el-form>

        <div class="table-box">
          <el-table
            border
            v-loading="loading"
            :data="tableData">
            <el-table-column
              prop="name"
              label="团队名称">
            </el-table-column>
            <el-table-column
              prop="contactName"
              label="联系人">
            </el-table-column>
            <el-table-column
              prop="contactPhone"
              label="联系方式">
            </el-table-column>
            <el-table-column
              prop="balance"
              label="余额">
            </el-table-column>
            <el-table-column
              prop="creditLimit"
              label="授信额度">
            </el-table-column>
            <el-table-column
              prop="debtAmount"
              width="130">
              <template slot="header">
                当前总欠款
                <Tip msg="授信支付未还总额"></Tip>
              </template>
            </el-table-column>
            <el-table-column
              prop="debtNums"
              width="130">
              <template slot="header">
                当前总欠款单数
                <Tip msg="授信支付未还总数"></Tip>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              label="备注">
            </el-table-column>
            <el-table-column
              width="350px"
              label="操作">
              <template slot-scope="scope">
                <div v-if="hasPermission('team-money-manage')">
                  <el-link
                    type="primary"
                    @click="openRechargeDialog(scope.row)"
                  >
                    充值
                  </el-link>

                  <el-link
                    type="primary"
                    @click="openDeductDialog(scope.row)"
                  >
                    扣款
                  </el-link>

                  <el-link
                    type="primary"
                    @click="openRepaymentDialog(scope.row)"
                  >
                    还款
                  </el-link>

                  <el-link
                    type="primary"
                    @click="openAdjustDialog(scope.row)"
                  >
                    调整授信额度
                  </el-link>
                </div>
                <div>
                  <el-link
                    type="primary"
                    @click="gotoRecord(scope.row)"
                  >
                    账户记录
                  </el-link>

                  <el-link
                    type="primary"
                    @click="openEditDialog(scope.row)"
                  >
                    编辑
                  </el-link>

                  <el-link
                    type="primary"
                    @click="deleteGroup(scope.row)"
                  >
                    删除
                  </el-link>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page.sync="form.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="form.pageSize"
            @size-change="handleSizeChange"
            @current-change="getList()"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="账户记录" name="accountFlow">
        <TeamAccountFlow v-if="activeTab === 'accountFlow'" :teamId="selectedTeamId" :teamName="selectedTeamName" />
      </el-tab-pane>
    </el-tabs>

    <!-- 新增/编辑团队弹框 -->
    <ElDialog
      :title="`${currentItem.id ? '编辑' : '新增'}团队`"
      width="500px"
      v-model="dialogVisible"
    >
      <el-form
        inline
        :model="currentItem"
        ref="editForm"
        class="form-wrap"
        label-width="150px"
        style="margin-top: 20px">
        <el-form-item
          label="团队名称"
          verify
          prop="name">
          <el-input v-model="currentItem.name"></el-input>
        </el-form-item>
        <el-form-item
          label="联系人"
          prop="contactName">
          <el-input v-model="currentItem.contactName"></el-input>
        </el-form-item>
        <el-form-item
          label="联系方式"
          prop="contactPhone">
          <el-input v-model="currentItem.contactPhone"></el-input>
        </el-form-item>
        <el-form-item
          v-if="!currentItem.id"
          label="余额"
          prop="balance">
          <el-input-number v-model="currentItem.balance" :precision="2" :step="1" :controls="false" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="!currentItem.id"
          label="授信额度"
          prop="creditLimit">
          <el-input-number v-model="currentItem.creditLimit" :min="0" :precision="2" :step="100" :controls="false" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark">
          <el-input v-model="currentItem.remark"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 20px; float: right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmOptGroup">确定</el-button>
      </div>
    </ElDialog>

    <!-- 充值弹框 -->
    <ElDialog
      title="充值"
      width="500px"
      v-model="rechargeDialogVisible"
    >
      <el-form
        inline
        :model="moneyForm"
        ref="moneyForm"
        class="form-wrap"
        label-width="150px"
        style="margin-top: 20px">
        <el-form-item
          label="充值金额"
          verify
          prop="amount">
          <el-input-number v-model="moneyForm.amount" :min="undefined" :precision="2" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark">
          <el-input v-model="moneyForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 20px; float: right;">
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRecharge">确定</el-button>
      </div>
    </ElDialog>

    <!-- 扣款弹框 -->
    <ElDialog
      title="扣款"
      width="500px"
      v-model="deductDialogVisible"
    >
      <el-form
        inline
        :model="moneyForm"
        ref="deductForm"
        class="form-wrap"
        label-width="150px"
        style="margin-top: 20px">
        <el-form-item
          label="扣款金额"
          verify
          prop="amount">
          <el-input-number v-model="moneyForm.amount" :min="0.01" :precision="2" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark">
          <el-input v-model="moneyForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 20px; float: right;">
        <el-button @click="deductDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDeduct">确定</el-button>
      </div>
    </ElDialog>

    <!-- 调整授信额度弹框 -->
    <ElDialog
      title="调整授信额度"
      width="500px"
      v-model="adjustDialogVisible"
    >
      <el-form
        inline
        :model="adjustForm"
        ref="adjustForm"
        class="form-wrap"
        label-width="150px"
        style="margin-top: 20px">
        <el-form-item
          label="调整后额度"
          verify
          prop="amount">
          <el-input-number v-model="adjustForm.amount" :min="0" :precision="2" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark">
          <el-input v-model="adjustForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 20px; float: right;">
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdjust">确定</el-button>
      </div>
    </ElDialog>

    <!-- 还款弹框 -->
    <ElDialog
      title="还款"
      width="1300px"
      v-model="repaymentDialogVisible"
      @close="handleRepaymentClose"
    >
      <div class="dialog-body-scroll">
        <div class="transfer-container">
          <div class="transfer-left">
            <div class="transfer-header">
              欠款记录
              <el-button
                type="primary"
                size="small"
                :disabled="!leftCheckedList.length"
                @click="addToSelected"
                style="float: right;"
              >
                添加至已选 &gt;&gt;
              </el-button>
            </div>
            <el-table
                border
                ref="debtTableRef"
                :data="debtList"
                v-loading="debtLoading"
                @selection-change="onDebtSelectionChange"
                size="small"
              >
                <el-table-column type="selection" width="40" />
                <el-table-column prop="operateTime" label="操作时间" width="140" />
                <el-table-column prop="teamName" label="团队名称" width="110" show-overflow-tooltip />
                <el-table-column label="交易类型" width="120">
                  <template slot-scope="scope">
                    {{ formatTransactionType(scope.row.transactionType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="交易金额" width="100" />
                <el-table-column prop="remainingDebt" label="剩余欠款" width="100" />
                <el-table-column prop="balanceBefore" label="交易前余额" width="100" />
                <el-table-column prop="balanceAfter" label="交易后余额" width="100" />
                <el-table-column prop="debtAmountBefore" label="欠款调整前" width="100" />
                <el-table-column prop="debtAmountAfter" label="欠款调整后" width="100" />
                <el-table-column prop="creditLimitBefore" label="额度调整前" width="100" />
                <el-table-column prop="creditLimitAfter" label="额度调整后" width="100" />
                <el-table-column prop="ticketCheckNum" label="票总人数" width="80" />
                <el-table-column prop="price" label="订单总额" width="100" />
                <el-table-column prop="ticketCancelCheckNum" label="退票人数" width="80" />
                <el-table-column prop="cancelPrice" label="退票总额" width="100" />
                <el-table-column prop="operatorName" label="操作员" width="90" />
                <el-table-column prop="linkOrderId" label="关联订单" width="80">
                  <template slot-scope="scope">
                    <el-link
                      v-if="scope.row.linkOrderId"
                      type="primary"
                      @click="showOrderDetail(scope.row.linkOrderId)"
                    >
                      查看
                    </el-link>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
              </el-table>
            <el-pagination
              background
              small
              layout="total, prev, pager, next"
              :current-page="debtPageNum"
              :page-size="debtPageSize"
              @current-change="handleDebtPageChange"
              :total="debtTotal"
            >
            </el-pagination>
          </div>

          <div class="transfer-right">
            <div class="transfer-header">
              已选记录
              <el-button
                size="small"
                :disabled="!rightSelectedList.length"
                @click="clearSelected"
                style="float: right;"
              >
                清除已选
              </el-button>
            </div>
            <el-table
                border
                :data="rightSelectedList"
                size="small"
              >
                <el-table-column type="index" label="序号" width="50" />
                <el-table-column prop="createTime" label="创建时间" width="140" />
                <el-table-column prop="teamName" label="团队名称" width="110" show-overflow-tooltip />
                <el-table-column label="交易类型" width="120">
                  <template slot-scope="scope">
                    {{ formatTransactionType(scope.row.transactionType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="交易金额" width="100" />
                <el-table-column prop="remainingDebt" label="剩余欠款" width="100" />
                <el-table-column prop="balanceBefore" label="交易前余额" width="100" />
                <el-table-column prop="balanceAfter" label="交易后余额" width="100" />
                <el-table-column prop="debtAmountBefore" label="欠款调整前" width="100" />
                <el-table-column prop="debtAmountAfter" label="欠款调整后" width="100" />
                <el-table-column prop="creditLimitBefore" label="额度调整前" width="100" />
                <el-table-column prop="creditLimitAfter" label="额度调整后" width="100" />
                <el-table-column prop="ticketCheckNum" label="票总人数" width="80" />
                <el-table-column prop="price" label="订单总额" width="100" />
                <el-table-column prop="ticketCancelCheckNum" label="退票人数" width="80" />
                <el-table-column prop="cancelPrice" label="退票总额" width="100" />
                <el-table-column prop="operatorName" label="操作员" width="90" />
                <el-table-column prop="operateTime" label="操作时间" width="140" />
                <el-table-column prop="linkOrderId" label="关联订单" width="80">
                  <template slot-scope="scope">
                    <el-link
                      v-if="scope.row.linkOrderId"
                      type="primary"
                      @click="showOrderDetail(scope.row.linkOrderId)"
                    >
                      查看
                    </el-link>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
                <el-table-column label="操作" width="60" fixed="right">
                  <template slot-scope="scope">
                    <el-link type="danger" @click="removeSelectedItem(scope.row)">移除</el-link>
                  </template>
                </el-table-column>
              </el-table>
            <div class="transfer-total">
              还款总额：<span class="total-amount">¥ {{ totalRepaymentAmount }}</span>
            </div>
          </div>
        </div>

        <el-form class="form-wrap" label-width="80px" style="margin-top: 16px;">
          <el-form-item label="备注">
            <el-input v-model="repaymentForm.remark" placeholder="请输入还款备注" />
          </el-form-item>
        </el-form>
      </div>

      <div style="margin: 16px 0 0; float: right;">
        <el-button @click="repaymentDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!rightSelectedList.length" @click="confirmRepayment">确定还款</el-button>
      </div>
    </ElDialog>

    <OrderDetail ref="orderDetail"></OrderDetail>
  </div>
</template>

<script>
import { getTeamList, addTeam, updateTeam, deleteTeam, teamRecharge, teamDeduct, teamAdjust, getDebtList, teamRepayment } from '@/api/checker'
import ElDialog from '@/components/Dialog'

const TeamAccountFlow = () => import('./TeamAccountFlow.vue')

export default {
  data () {
    return {
      activeTab: 'teamManage',
      form: {
        name: '',
        pageNum: 1,
        pageSize: 10,
        contactName: '',
        contactPhone: '',
        remark: ''
      },
      loading: false,
      selectedTeamId: null,
      selectedTeamName: '',
      tableData: [],
      total: 0,
      dialogVisible: false,
      currentItem: {},
      rechargeDialogVisible: false,
      moneyForm: {
        teamId: null,
        amount: 0,
        remark: ''
      },
      deductDialogVisible: false,
      adjustDialogVisible: false,
      adjustForm: {
        teamId: null,
        amount: 0,
        remark: ''
      },
      repaymentDialogVisible: false,
      debtList: [],
      debtTotal: 0,
      debtPageNum: 1,
      debtPageSize: 10,
      debtLoading: false,
      leftCheckedList: [],
      rightSelectedList: [],
      repaymentForm: {
        teamId: null,
        remark: ''
      }
    }
  },
  computed: {
    scenicList () {
      return this.$store.state.app.scenicList
    },
    permissionList () {
      return this.$store.state.user.menuList || []
    },
    totalRepaymentAmount () {
      return this.rightSelectedList.reduce((sum, item) => sum + (item.remainingDebt || 0), 0)
    }
  },
  created () {
    this.getList()
  },
  components: {
    ElDialog,
    TeamAccountFlow
  },
  methods: {
    hasPermission (key) {
      return !!this.permissionList.some(item => item.code === key)
    },
    reset () {
      this.$refs.form.resetFields()
    },
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getList()
    },
    getList (goFirst) {
      let params = { ...this.form }

      goFirst && (params.pageNum = 1)
      this.loading = true
      getTeamList(params).then(res => {
        const list = res.data?.records || []
        this.total = res.data?.total || 0
        this.tableData = list
        this.loading = false
      })
    },
    openAddDialog () {
      this.currentItem = {
        id: '',
        name: '',
        contactName: '',
        contactPhone: '',
        balance: 0,
        creditLimit: 0,
        remark: ''
      }
      this.dialogVisible = true
    },
    openEditDialog (item) {
      this.currentItem = Object.assign({}, item)
      this.dialogVisible = true
    },
    deleteGroup (data) {
      this.$confirm('确定删除团队吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTeam(data.id).then(res => {
          this.$message.success('操作成功')
          this.getList()
        })
      }).catch(() => {})
    },
    confirmOptGroup () {
      const opt = this.currentItem.id ? updateTeam : addTeam
      opt(this.currentItem).then(res => {
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.getList()
      })
    },
    openRechargeDialog (row) {
      Object.assign(this.moneyForm, {
        teamId: row.id,
        amount: 0,
        remark: ''
      })
      this.rechargeDialogVisible = true
    },
    confirmRecharge () {
      teamRecharge(this.moneyForm).then(() => {
        this.$message.success('充值成功')
        this.rechargeDialogVisible = false
        this.getList()
      })
    },
    openDeductDialog (row) {
      Object.assign(this.moneyForm, {
        teamId: row.id,
        amount: 0,
        remark: ''
      })
      this.deductDialogVisible = true
    },
    confirmDeduct () {
      teamDeduct(this.moneyForm).then(() => {
        this.$message.success('扣款成功')
        this.deductDialogVisible = false
        this.getList()
      })
    },
    openAdjustDialog (row) {
      Object.assign(this.adjustForm, {
        teamId: row.id,
        amount: row.creditLimit || 0,
        remark: ''
      })
      this.adjustDialogVisible = true
    },
    confirmAdjust () {
      teamAdjust(this.adjustForm).then(() => {
        this.$message.success('调整授信额度成功')
        this.adjustDialogVisible = false
        this.getList()
      })
    },
    gotoRecord (row) {
      this.selectedTeamId = row.id
      this.selectedTeamName = row.name
      this.activeTab = 'accountFlow'
    },
    reportExport () {
      const params = {
        ...this.form,
        export: true
      }
      getTeamList(params).then(() => {
        this.$message.success('导出成功。')
        this.goToDownload()
      }).catch(() => {
        this.$message.error('导出失败。')
      })
    },
    openRepaymentDialog (row) {
      this.repaymentForm = {
        teamId: row.id,
        remark: ''
      }
      this.rightSelectedList = []
      this.leftCheckedList = []
      this.debtPageNum = 1
      this.debtList = []
      this.debtTotal = 0
      this.repaymentDialogVisible = true
      this.loadDebtList()
    },
    loadDebtList () {
      this.debtLoading = true
      const params = {
        id: 0,
        teamId: this.repaymentForm.teamId,
        pageNum: this.debtPageNum,
        pageSize: this.debtPageSize,
        export: false,
        exportDetail: false,
        removeSubtotal: false,
        remark: ''
      }
      getDebtList(params).then(res => {
        this.debtList = res.data?.records || []
        this.debtTotal = res.data?.total || 0
      }).finally(() => {
        this.debtLoading = false
      })
    },
    handleDebtPageChange (num) {
      this.debtPageNum = num
      this.loadDebtList()
    },
    onDebtSelectionChange (selection) {
      this.leftCheckedList = selection
    },
    formatTransactionType (type) {
      const map = {
        'RECHARGE': '充值',
        'DEDUCT': '扣款',
        'PREPAY_PAY': '预付款支付',
        'PREPAY_REFUND': '预付款退款',
        'CREDIT_PAY': '授信支付',
        'CREDIT_REFUND': '授信退款',
        'REPAYMENT': '还款',
        'ADJUST': '调整授信额度'
      }
      return map[type] || type || '-'
    },
    addToSelected () {
      const existingIds = this.rightSelectedList.map(item => item.id)
      const newItems = this.leftCheckedList.filter(item => !existingIds.includes(item.id))
      this.rightSelectedList = [...this.rightSelectedList, ...newItems]
      this.$message.success(`已添加 ${newItems.length} 条欠款记录`)
      this.$refs.debtTableRef && this.$refs.debtTableRef.clearSelection()
    },
    removeSelectedItem (row) {
      this.rightSelectedList = this.rightSelectedList.filter(item => item.id !== row.id)
    },
    clearSelected () {
      this.rightSelectedList = []
    },
    handleRepaymentClose () {
      this.$refs.debtTableRef && this.$refs.debtTableRef.clearSelection()
      this.leftCheckedList = []
    },
    async showOrderDetail (orderId) {
      const { getSingleOrder } = await import('@/api/order')
      const res = await getSingleOrder(orderId)
      this.$refs.orderDetail.show(res.data)
    },
    confirmRepayment () {
      if (!this.rightSelectedList.length) {
        this.$message.warning('请先选择欠款记录')
        return
      }
      const debtList = this.rightSelectedList.map(item => ({
        flowId: item.id,
        amount: item.remainingDebt
      }))
      const params = {
        teamId: this.repaymentForm.teamId,
        amount: this.totalRepaymentAmount,
        remark: this.repaymentForm.remark,
        debtList
      }
      teamRepayment(params).then(() => {
        this.$message.success('还款成功')
        this.repaymentDialogVisible = false
        this.getList()
      })
    }
  }
}
</script>

<style scoped>
.dialog-body-scroll {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 4px;
}
.transfer-container {
  display: block;
}
.transfer-left,
.transfer-right {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 16px;
}
.transfer-right {
  margin-bottom: 0;
}
.transfer-header {
  font-weight: bold;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
  color: #303133;
  overflow: hidden;
}
.transfer-total {
  margin-top: 12px;
  text-align: right;
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  padding: 8px 4px;
  border-top: 1px solid #ebeef5;
}
.total-amount {
  color: #f56c6c;
  font-size: 18px;
}
</style>
