<template>
  <div class="wraper">
    <div class="search">
      <el-form :model="searchForm" size="small" :inline="true">
        <el-form-item label="域名">
          <el-input
            v-model="searchForm.domain"
            placeholder="请输入域名"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.companyName"
            placeholder="请输入客户名称"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="客户编码">
          <el-input
            v-model="searchForm.userMark"
            placeholder="请输入客户编码"
            clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="search">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="deleteSection">
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table" v-loading="loading">
      <el-table
        ref="table"
        :data="balanceList"
        border
        height="100%"
        width="100%"
        :highlight-current-row="true"
        @selection-change="handleSelectionChange"
        header-row-class-name="header-row-class-name">
        <el-table-column
          type="selection"
          width="55"
          header-align="center"
          align="center"></el-table-column>
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center"
          fixed="left"></el-table-column>
        <el-table-column
          label="域名"
          prop="domain"
          header-align="center"
          min-width="300"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-link
              :href="'https://' + scope.row.domain"
              target="_blank"
              type="primary">
              {{ scope.row.domain }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          label="公司名称"
          prop="companyName"
          align="center"
          width="200"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="客户编码"
          prop="userMark"
          align="center"
          width="150"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="折扣（%）"
          prop="discountRate"
          align="center"
          width="150"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="cell-flex">
              <span class="cell-left">{{ scope.row.discountRate }}</span>
              <span class="cell-right">
                <i
                  class="el-icon-edit-outline"
                  style="cursor: pointer; color: #e6a23c; font-size: 20px"
                  title="编辑"
                  @click="editDiscountRate(scope.row)" />
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="授信额度（元）"
          prop="lineCredit"
          align="center"
          width="150"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="cell-flex">
              <span class="cell-left">{{ scope.row.lineCredit }}</span>
              <span class="cell-right">
                <i
                  class="el-icon-edit-outline"
                  style="cursor: pointer; color: #e6a23c; font-size: 20px"
                  title="编辑"
                  @click="editLineCredit(scope.row)" />
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="余额（元）"
          prop="balance"
          align="center"
          width="150"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="消费金额（元）"
          prop="usedQuota"
          align="center"
          width="150"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
          width="200"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTime"
          align="center"
          width="200"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          header-align="center"
          width="100"
          fixed="right">
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-around;
                font-size: 20px;
              ">
              <i
                class="el-icon-coin"
                title="手动充值"
                @click="handleRecharge(scope.row)"
                style="cursor: pointer; color: #67c23a"></i>
              <i
                class="el-icon-document"
                title="操作日志"
                @click="handleLog(scope.row)"
                style="cursor: pointer; color: #1565c0"></i>
              <i
                class="el-icon-money"
                title="扣费明细"
                @click="handleChargerLog(scope.row)"
                style="cursor: pointer; color: #e6b800"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange"></el-pagination>
    </div>
    <!-- 编辑折扣 弹窗 -->
    <el-dialog
      title="修改折扣"
      :visible.sync="editDiscountVisible"
      width="700px"
      @submit.native.prevent
      :close-on-click-modal="false">
      <el-form
        :model="editDiscountForm"
        size="small"
        ref="editDiscountForm"
        label-width="150px"
        label-position="right">
        <el-form-item
          label="折扣（%）"
          type="number"
          prop="discountRate"
          :rules="[
            { required: 'true', message: '请输入折扣', trigger: 'blur' },
            {
              validator: validateDiscount,
              trigger: 'blur'
            },
            { validator: validateDiscountSame, trigger: 'blur' }
          ]">
          <el-input
            type="number"
            min="0"
            max="100"
            v-model="editDiscountForm.discountRate"
            size="small"
            placeholder="请输入折扣" />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
          :rules="[
            { required: 'true', message: '请输入备注', trigger: 'blur' },
            { max: 100, message: '不能超过100字', trigger: 'blur' }
          ]">
          <el-input
            type="textarea"
            class="textRemark"
            size="small"
            v-model="editDiscountForm.remark" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDiscountVisible = false" size="small">
          取消
        </el-button>
        <el-button @click="editDiscountSave" type="primary" size="small">
          保存
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑授信额度 弹窗 -->
    <el-dialog
      title="修改授信额度"
      :visible.sync="editLineCreditVisible"
      width="700px"
      @submit.native.prevent
      :close-on-click-modal="false">
      <el-form
        :model="editLineCreditForm"
        size="small"
        ref="editLineCreditForm"
        label-width="150px"
        label-position="right">
        <el-form-item
          label="授信额度（元）"
          type="number"
          prop="lineCredit"
          :rules="[
            { required: 'true', message: '请输入授信额度', trigger: 'blur' },
            { validator: validateBalance, trigger: 'blur' },
            { validator: validateLineCreditSame, trigger: 'blur' }
          ]">
          <el-input
            type="number"
            min="0"
            v-model="editLineCreditForm.lineCredit"
            size="small" />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
          :rules="[
            { required: 'true', message: '请输入备注', trigger: 'blur' },
            { max: 100, message: '不能超过100字', trigger: 'blur' }
          ]">
          <el-input
            type="textarea"
            class="textRemark"
            size="small"
            v-model="editLineCreditForm.remark" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editLineCreditVisible = false" size="small">
          取消
        </el-button>
        <el-button @click="editLineCreditSave" type="primary" size="small">
          保存
        </el-button>
      </span>
    </el-dialog>
    <!-- 手动充值 弹窗 -->
    <el-dialog
      title="手动充值"
      :visible.sync="rechargeVisible"
      :close-on-click-modal="false"
      @submit.native.prevent
      width="700px">
      <el-form
        :model="rechargeForm"
        size="small"
        ref="rechargeForm"
        label-width="150px"
        label-position="right">
        <el-form-item
          label="充值金额（元）"
          prop="balance"
          :rules="[
            {
              required: true,
              message: '请输入充值金额（元）',
              trigger: 'blur'
            },
            { validator: validateBalance, trigger: 'blur' }
          ]">
          <el-input
            type="number"
            min="0"
            v-model="rechargeForm.balance"
            size="small"
            placeholder="请输入充值金额（元）" />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
          :rules="[
            { required: 'true', message: '请输入备注', trigger: 'blur' },
            { max: 100, message: '不能超过100字', trigger: 'blur' }
          ]">
          <el-input
            type="textarea"
            class="textRemark"
            size="small"
            v-model="rechargeForm.remark" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="rechargeVisible = false" size="small">
          取消
        </el-button>
        <el-button @click="rechargeSave" type="primary" size="small">
          保存
        </el-button>
      </span>
    </el-dialog>
    <!-- 操作日志 弹窗 -->
    <el-dialog title="操作日志" :visible.sync="logVisible" width="900px">
      <ul style="color: #333; font-size: 14px; height: 600px; overflow: auto">
        <li
          v-for="(item, index) in logList"
          :key="index"
          style="padding-top: 10px">
          ({{ index + 1 }})
          {{
            item.createTime.replace('T', ' ') +
            '&nbsp; &nbsp;' +
            item.optUserAccount +
            '：' +
            item.description
          }}
        </li>
      </ul>
      <div class="pagination">
        <el-pagination
          layout="sizes, total, prev, pager, next, jumper"
          background
          :total="totalLog"
          :page-size="logPageSize"
          :current-page="currentLogPage"
          @size-change="logSizeChange"
          @current-change="onLogCurrentChange" />
      </div>
    </el-dialog>
    <!-- 扣费明细 弹窗 -->
    <el-dialog
      title="扣费明细"
      :visible.sync="recordsVisible"
      width="100%"
      class="recordsDialog">
      <div class="search">
        <el-form :model="searchRecordsForm" size="small" :inline="true">
          <el-form-item label="起始时间">
            <el-date-picker
              style="width: 360px"
              v-model="searchRecordsForm.daterange"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:ss:mm"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable></el-date-picker>
          </el-form-item>
          <el-form-item label="支付款项">
            <el-select
              style="width: 200px"
              v-model="searchRecordsForm.chargeType"
              clearable
              placeholder="请选择支付款项">
              <el-option
                v-for="(item, index) in chargeTypeMap"
                :key="index"
                :label="item"
                :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-select
              style="width: 200px"
              clearable
              v-model="searchRecordsForm.payMode"
              placeholder="请选择支付方式">
              <el-option
                v-for="(item, index) in payModeListMap"
                :key="index"
                :label="item"
                :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单号">
            <el-input
              v-model="searchRecordsForm.bizNo"
              placeholder="请输入订单号"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="交易流水号">
            <el-input
              v-model="searchRecordsForm.tradeNo"
              placeholder="请输入交易流水号"
              clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              @click="getChargerLog">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        ref="recordsTable"
        :data="chargerRecordsList"
        border
        height="40%"
        width="100%"
        :highlight-current-row="true"
        header-row-class-name="header-row-class-name">
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center"
          fixed="left"></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
          width="250"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.createTime.replace('T', ' ') }}
          </template>
        </el-table-column>
        <el-table-column
          label="交易流水号"
          prop="tradeNo"
          align="center"
          width="180"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="支付款项"
          prop="chargeType"
          align="center"
          width="150"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ getChargeTypeText(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="订单号"
          prop="bizNo"
          align="center"
          min-width="170"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div style="white-space: pre-wrap">{{ scope.row.bizNo }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="支付方式"
          prop="payMode"
          align="center"
          width="150"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.payMode == 1 ? '支付宝' : '额度' }}
          </template>
        </el-table-column>
        <el-table-column
          label="收取费用"
          prop="fees"
          align="center"
          width="150"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="扣前余额"
          prop="balanceBefore"
          align="center"
          width="150"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="扣后余额"
          prop="balanceAfter"
          align="center"
          width="150"
          :show-overflow-tooltip="true"></el-table-column>
      </el-table>
      <div class="pagination">
        <div class="total-amount">
          {{ '总消费金额：' + totalAmount + ' 元' }}
        </div>
        <el-pagination
          layout="sizes, total, prev, pager, next, jumper"
          background
          :total="totalRecords"
          :page-size="recordsPageSize"
          :current-page="currentRecordsPage"
          @size-change="recordsSizeChange"
          @current-change="onRecordsCurrentChange" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCostomerBalanceApi,
  editCustomerBalanceApi,
  customerBalanceRechargeApi,
  customerBalanceDelete,
  getLogListApi,
  getChargerRecordsApi,
  getChargerRecordsTotalApi
} from '@/common/api/user/user'

export default {
  name: 'userBalance',
  data() {
    return {
      searchForm: {},
      rechargeForm: {},
      editDiscountForm: {},
      editLineCreditForm: {},
      searchRecordsForm: {},
      balanceList: [],
      logList: [],
      chargerRecordsList: [],
      selection: [],
      payModeListMap: {
        1: '支付宝',
        2: '额度'
      },
      chargeTypeMap: {
        1: 'POD(CN)',
        2: 'POD(US)',
        3: '一件定制'
      },
      currentRow: {},
      loading: false,
      totalAmount: 0,
      total: 0,
      currentPage: 1,
      pageSize: 50,
      editDiscountVisible: false,
      editLineCreditVisible: false,
      rechargeVisible: false,
      logVisible: false,
      totalLog: 0,
      logPageSize: 50,
      currentLogPage: 1,
      recordsVisible: false,
      totalRecords: 0,
      currentRecordsPage: 1,
      recordsPageSize: 50
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    search() {
      this.currentPage = 1
      this.getList()
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    // 列表分页
    onCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getList()
    },
    sizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
      this.getList()
    },
    // 扣费明细分页
    recordsSizeChange(pageSize) {
      this.recordsPageSize = pageSize
      this.currentRecordsPage = 1
      this.getChargerLog()
    },
    onRecordsCurrentChange(currentPage) {
      this.currentRecordsPage = currentPage
      this.getChargerLog()
    },
    // 操作日志分页
    logSizeChange(pageSize) {
      this.logPageSize = pageSize
      this.currentLogPage = 1
      this.getLogs()
    },
    onLogCurrentChange(currentPage) {
      this.currentLogPage = currentPage
      this.getLogs()
    },

    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const res = await getCostomerBalanceApi({
          ...this.searchForm,
          currentPage: this.currentPage,
          pageSize: this.pageSize
        })
        this.balanceList = res.data.records
        this.total = res.data.total
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    // 编辑折扣
    async editDiscountRate(row) {
      this.currentRow = row
      this.editDiscountForm = JSON.parse(JSON.stringify(row))
      this.editDiscountVisible = true
    },
    // 编辑折扣提交
    async editDiscountSave() {
      this.$refs.editDiscountForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        try {
          await editCustomerBalanceApi({ ...this.editDiscountForm })
        } catch (e) {
          console.log(e)
        } finally {
          this.editDiscountVisible = false
          this.currentPage = 1
          this.editDiscountForm = {}
          await this.getList()
        }
      })
    },
    // 编辑授信额度
    async editLineCredit(row) {
      this.currentRow = row
      this.editLineCreditForm = JSON.parse(JSON.stringify(row))
      this.editLineCreditVisible = true
    },
    // 编辑授信额度提交
    async editLineCreditSave() {
      this.$refs.editLineCreditForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        try {
          await editCustomerBalanceApi({ ...this.editLineCreditForm })
        } catch (e) {
          console.log(e)
        } finally {
          this.editLineCreditVisible = false
          this.currentPage = 1
          this.editLineCreditForm = {}
          await this.getList()
        }
      })
    },
    // 手动充值弹窗
    async handleRecharge(row) {
      this.rechargeForm = {}
      this.rechargeForm.id = row.id
      this.rechargeVisible = true
    },
    // 手动充值提交
    async rechargeSave() {
      this.$refs.rechargeForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        try {
          await customerBalanceRechargeApi({ ...this.rechargeForm })
        } catch (e) {
          console.log(e)
        } finally {
          this.rechargeVisible = false
          this.rechargeForm = {}
          this.currentPage = 1
          await this.getList()
        }
      })
    },
    // 批量删除
    async deleteSection(v) {
      if (this.selection.length === 0) {
        this.$message.error('请至少选择一条记录')
        return
      }

      let ids = []
      ids = this.selection.map((item) => item.id)
      ids = ids.join()
      const warning = this.$loading({
        background: 'rgba(0, 0, 0, 0.3)'
      })

      try {
        await customerBalanceDelete(ids)
      } catch (e) {
        console.error(e)
      } finally {
        warning.close()
        this.currentPage = 1
        this.getList()
      }
    },
    // 金额校验
    validateBalance(rule, value, callback) {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else if (Number(value) < 0) {
        callback(new Error('金额不能小于0'))
      } else {
        callback()
      }
    },
    validateLineCreditSame(rule, value, callback) {
      if (this.currentRow.lineCredit === value) {
        callback(new Error('授信额度未修改'))
      } else {
        callback()
      }
    },
    // 折扣校验
    validateDiscount(rule, value, callback) {
      if (value === '' || value === null || value === undefined) {
        callback()
      } else if (Number(value) < 0 || Number(value) > 100) {
        callback(new Error('折扣需要介于0到100之间'))
      } else {
        callback()
      }
    },
    validateDiscountSame(rule, value, callback) {
      if (this.currentRow.discountRate === value) {
        callback(new Error('折扣未修改'))
      } else {
        callback()
      }
    },
    // 查看操作日志
    handleLog(row) {
      this.currentRow = row
      this.getLogs()
    },
    async getLogs() {
      try {
        const res = await getLogListApi({
          customerBalanceId: this.currentRow.id,
          pageSize: this.logPageSize,
          currentPage: this.currentLogPage
        })
        this.logList = res.data.records
        if (this.logList.length) {
          this.logVisible = true
          this.totalLog = res.data.total
        } else {
          this.$message.warning('暂无数据')
        }
      } catch (e) {
        console.log(e)
      }
    },
    handleChargerLog(row) {
      this.currentRow = row
      this.getChargerLog()
    },
    getChargeTypeText(type) {
      return this.chargeTypeMap[type]
    },
    // 分页查看扣费明细
    async getChargerLog() {
      try {
        const data = {
          pageSize: this.recordsPageSize,
          currentPage: this.currentRecordsPage,
          namespace: this.currentRow.namespace,
          ...this.searchRecordsForm
        }
        if (this.searchRecordsForm.daterange?.length) {
          data.createTimeStart = this.searchRecordsForm.daterange[0]
          data.createTimeEnd = this.searchRecordsForm.daterange[1]
        }
        const [res, totalRes] = await Promise.all([
          getChargerRecordsApi(data),
          getChargerRecordsTotalApi(data)
        ])
        this.chargerRecordsList = res.data.records

        if (this.chargerRecordsList.length) {
          this.totalRecords = res.data.total
          this.totalAmount = totalRes.data.feesSum
          this.chargerRecordsList.forEach((item) => {
            item.bizNo = item.bizNo.replaceAll(',', '\n')
          })
          this.recordsVisible = true
        } else {
          this.$message.warning('暂无数据')
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wraper {
  height: 100%;
  overflow: hidden;
  background: #fff;
  border-radius: 5px;
  padding: 10px;
  display: flex;
  flex-direction: column;

  &::v-deep {
    .el-table .el-table__cell {
      padding: 6px 0;
    }

    .el-input__inner {
      padding: 0 4px;
    }

    .el-input--small .el-input__inner {
      height: 30px;
      line-height: 30px;
    }

    .el-dialog__footer {
      text-align: center;

      .el-button--small {
        padding: 9px 50px;
      }
    }

    .el-dialog__body {
      padding: 10px 20px;
    }

    .el-range-editor--small .el-range-separator {
      line-height: 31px;
    }

    .header-row-class-name th {
      background-color: #f8f8f9;
    }

    .el-input-group__append {
      padding-left: 0;
    }

    .el-icon-time:before {
      content: '';
    }
  }

  .cell-flex {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0 8px;

    .cell-left,
    .cell-right {
      display: flex;
      justify-content: center;
    }

    .cell-left {
      width: 80%;
    }

    .cell-right {
      width: 20%;
    }
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center; /* 让el-pagination居中 */
  position: relative;
  min-height: 50px; /* 根据实际高度调整 */
}

.recordsDialog {
  margin: 0px;

  .total-amount {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    color: #333;
  }

  &::v-deep {
    .el-dialog {
      height: 100vh !important;
      display: flex;
      flex-direction: column;
      margin: 0 auto;
      margin-top: 0vh !important;
    }
    .el-dialog__body {
      flex: 1 1 0%;
      display: flex;
      flex-direction: column;
      padding: 10px 20px;
      overflow: hidden;
    }

    .table-area {
      flex: 1 1 0%;
      min-height: 0;
      overflow: auto;
      display: flex;
      flex-direction: column;
    }

    .el-table {
      flex: 1 1 0%;
      min-height: 0;
      /* 让table内容区出现滚动条 */
    }

    .el-table .el-table__cell {
      padding: 6px 0;
    }
  }
}
.table {
  flex: 1;
  overflow: hidden;
}
</style>
