<template>
  <div id="team-recharge" class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="head-container">
      <el-date-picker
        v-model="searchParams.time"
        type="datetime"
        size="small"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择日期时间"
      />
      <el-input v-model="searchParams.search_name" type="text" size="small" placeholder="请输入代理名称/手机号" style="display: inline-block; width: 240px;" @keyup.enter.native="searchParams.page_index = 1 ; getRechargeList()" />
      <el-button type="primary" size="small" @click="searchParams.page_index = 1 ; getRechargeList()">搜索</el-button>
      <!-- <el-button type="primary" size="small" icon="el-icon-upload2" @click="exportShowStyle">导入</el-button> -->
      <el-button type="primary" size="small" icon="el-icon-upload2" @click="dialog_import = true">导入</el-button>
      <!-- <el-upload
        action=""
        :show-file-list="false"
        :http-request="handleImport"
      >
        <el-button size="small" type="primary" icon="el-icon-upload2">导入</el-button>
      </el-upload> -->
      <el-button type="primary" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
    </div>

    <div class="all_team_money">
      <p>代理余额 总计</p>
      <p class="big">{{ parseMoney(rechargeTotal) }}</p>
    </div>

    <el-table
      :data="sortRechargeList"
      border
      stripe
      class="tableBorder"
      :header-cell-style="{ background: '#f8fbfc' }"
    >
      <el-table-column prop="nickname" label="代理昵称" />
      <el-table-column prop="realname" label="代理姓名" />
      <el-table-column prop="mobile" label="代理手机号" />
      <el-table-column prop="money" label="资金余额">
        <template slot-scope="{ row: { user_pay , money} }">
          <span v-if="oldSearchTime">{{ (user_pay.length && user_pay[0].user_money) > 0 ? parseMoney(user_pay[0].user_money) : 0 }}</span>
          <span v-else>{{ parseMoney(money) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="text" @click="tableDetail(row)">查看明细</el-button>
          <el-button type="text" @click="handleRecharge(row)">充值</el-button>
          <el-button type="text" @click="recharge_type = false; handleRecharge(row)">扣款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination :total="tableTotal" :limit="searchParams.page_size" :page="searchParams.page_index" @pagination="changePagination" @update:limit="changePagination" />
    <!-- 明细 -->
    <el-dialog title="资金明细" :visible.sync="dialog_detail" width="80%" top="5vh" :before-close="resetDetail">
      <div style="display: flex;justify-content: space-between;flex-direction: column;">
        <div class="detail_head">
          <p><label>代理名称</label>: {{ recharge_detail.info && recharge_detail.info.nickname }}</p>
          <p><label>代理级别</label>: {{ levelStatus(recharge_detail.info && recharge_detail.info.level).name }}</p>
          <p><label>总金额</label>: {{ parseMoney(recharge_detail.info && recharge_detail.info.money) }}</p>
        </div>

        <div>
          <el-date-picker v-model="search_detail.time" value-format="yyyy-MM-dd" size="small" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
          <el-button type="primary" size="small" @click="handleDeatilSearch">搜索</el-button>
        </div>

        <div class="detail_team_money">
          <div class="all_team_money">
            <p class="big">{{ parseMoney(recharge_detail.incomeMoney ? recharge_detail.incomeMoney.toFixed(2) : 0) }}</p>
            <p>充值</p>
          </div>
          <div class="all_team_money">
            <p class="big">{{ parseMoney(recharge_detail.spendingMoney ? recharge_detail.spendingMoney.toFixed(2) : 0) }}</p>
            <p>扣款</p>
          </div>
        </div>
        <el-table border stripe class="tableBorder" :header-cell-style="{ background: '#f8fbfc' }" :data="recharge_detail && recharge_detail.list">
          <el-table-column prop="pay_num" label="支付流水号" />
          <el-table-column prop="created_at" label="支付时间" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="type" label="摘要">
            <template slot-scope="{ row }">
              <span>{{ rechargeType(row.type) }}</span>
              <span v-if="row.type === 0 && row.style">【{{ row.style }}】</span>
            </template>
          </el-table-column>
          <el-table-column prop="pay_money" label="支付金额">
            <template slot-scope="{ row }">{{ parseMoney(row.pay_money) }}</template>
          </el-table-column>
          <el-table-column prop="user_money" label="当前余额">
            <template slot-scope="{ row }">{{ parseMoney(row.user_money) }}</template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination :total="search_detail.total" :limit="search_detail.page_size" :page="search_detail.page_index" @pagination="changeDeatilPagination" @update:limit="changeDeatilPagination" />
      </div>
    </el-dialog>
    <!-- 充值 / 扣款 -->
    <el-dialog
      :title="recharge_type ? '充值' : '扣款'"
      :visible.sync="dialog_recharge"
      :before-close="resetAccess"
      :hide-required-asterisk="true"
      width="90%"
    >
      <el-form ref="accessForm" label-width="90px" :model="accessform" :rules="accessRule">
        <el-form-item label="昵称:">
          <el-input v-model="accessform.user_name" type="text" disabled />
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input v-model="accessform.user_mobile" type="text" disabled />
        </el-form-item>
        <el-form-item :label="recharge_type ? '充值金额:' : '扣款金额:'" prop="money">
          <el-input v-model="accessform.money" type="text" />
        </el-form-item>
        <el-form-item v-if="recharge_type" label="转账方式:" prop="style">
          <el-select v-if="handStyle && styleList.length > 0" v-model="accessform.style" placeholder="请选择转账方式" style="width:100%">
            <el-option v-for="item in styleList" :key="item.id" :label="item.title" :value="item.title">
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px" @click.capture.stop="submitDeleteStyle(item.id)">删除</span>
            </el-option>
          </el-select>
          <el-input v-else v-model="accessform.style" type="text" style="width: 400px">
            <i slot="append" class="el-icon-plus add" @click="submitSaveStyle">保存</i>
          </el-input>
          <br>
          <span v-if="handStyle && styleList.length > 0" class="handCompony" @click="handStyle = false">手动填写</span>
          <span v-else-if="!handStyle && styleList.length > 0" class="handCompony" @click="handStyle = true">选择转账方式</span>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="accessform.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="resetAccess">取消</el-button>
          <el-button v-if="recharge_type" type="primary" size="small" @click="handleSave">充值</el-button>
          <el-button v-else type="primary" size="small" @click="handleWithhold">扣款</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog title="导入数据" :visible.sync="dialog_import">
      <div class="upload-main" style="height:400px">
        <!-- <el-form label-width="80px" style="display:flex;justify-content:center">
          <el-form-item v-if="recharge_type" label="转账方式">
            <el-select v-if="handStyle && styleList.length > 0" v-model="machStyle" placeholder="请选择转账方式" style="width: 400px">
              <el-option v-for="item in styleList" :key="item.id" :label="item.title" :value="item.title">
                <span style="float: left">{{ item.title }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px" @click.capture.stop="submitDeleteStyle(item.id)">删除</span>
              </el-option>
            </el-select>
            <el-input v-else v-model="machStyle" type="text" style="width: 400px">
              <i slot="append" class="el-icon-plus add" @click="submitSaveStyle">保存</i>
            </el-input>
            <br>
            <span v-if="handStyle && styleList.length > 0" class="handCompony" @click="handStyle = false">手动填写</span>
            <span v-else-if="!handStyle && styleList.length > 0" class="handCompony" @click="handStyle = true">选择转账方式</span>
          </el-form-item>
        </el-form> -->
        <div class="upload-container">
          <el-button type="text" class="download" @click="exportModel">下载模板</el-button>
          <el-upload action="" :show-file-list="false" :http-request="handleImport">
            <div>
              <div style="position:relative">
                <el-input v-model="import_name" type="text" class="input">
                  <i slot="append" class="el-icon-upload2" />
                </el-input>
                <i class="block" />
              </div>
            </div>
          </el-upload>
        </div>
        <div class="upload-container">
          <el-button size="small" @click="resetImport">取消</el-button>
          <el-button size="small" type="primary" @click="submitImport">导入</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// api
import { list as rechargeList, detail, save, withhold, toImport, getStyle, saveStyle, deleteStyle } from '@/api/team/recharge'
// 金额
import { parseMoney } from '@/utils/index'
// 等级
import { levelStatus } from '@/filters/common'
// 时间
import { formatter } from '@/filters/index'
// 导入
import XLSX from 'xlsx'
export default {
  data() {
    return {
      loadingFull: false,
      dialog_detail: false,
      dialog_recharge: false,
      recharge_type: true,
      searchParams: {
        page_size: 10,
        page_index: 1,
        search_name: '',
        time: ''
      },
      rechargeList: [],
      rechargeTotal: 0,
      tableTotal: 0,
      recharge_detail: {},
      search_detail: {
        time: '',
        id: '',
        page_size: 10,
        page_index: 1,
        total: 0
      },
      accessform: {
        user_id: '',
        user_name: '',
        user_mobile: '',
        money: '',
        remark: '',
        style: ''
      },
      accessRule: {
        money: [
          { required: true, message: '请填写金额', trigger: 'blur' }
        ],
        style: [
          { required: true, message: '请选择或填写转账方式', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请填写备注', trigger: 'blur' }
        ]
      },
      dialog_import: false,
      import_name: '',
      import_file: null,
      handStyle: true,
      styleList: [],
      machStyle: '',
      oldSearchTime: ''
    }
  },
  computed: {
    sortRechargeList() {
      return this.rechargeList.slice((this.searchParams.page_index - 1) * this.searchParams.page_size, this.searchParams.page_index * this.searchParams.page_size)
    }
  },
  created() {
    this.parseMoney = parseMoney
    this.levelStatus = levelStatus
    this.getRechargeList()
  },
  methods: {
    // 获取列表
    async getRechargeList() {
      this.loadingFull = true
      this.searchParams.time = this.searchParams.time || ''
      this.oldSearchTime = this.searchParams.time
      await rechargeList(this.searchParams).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.rechargeList = res.data.list.info.sort((a, b) => {
            return this.oldSearchTime
              ? (b.user_pay.length && b.user_pay[0].user_money
                ? b.user_pay[0].user_money : 0) -
              (a.user_pay.length && a.user_pay[0].user_money
                ? a.user_pay[0].user_money : 0)
              : b.money - a.money
          })
          this.rechargeTotal = res.data.list.totalMoney
          this.tableTotal = res.data.total
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      // this.getRechargeList()
    },
    // 查看明细
    async rechargeDetail(cb) {
      const { id, time, page_size, page_index } = this.search_detail
      let start_time, end_time
      if (!time || time.length < 2) {
        start_time = end_time = ''
      } else {
        [start_time, end_time] = time
      }
      this.loadingFull = true
      await detail({
        id,
        start_time,
        end_time,
        page_size,
        page_index
      }).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.recharge_detail = res.data
          this.search_detail.total = res.data.total
          cb && cb()
        } else {
          this.$message.error(res.message || '查看明细失败')
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    tableDetail(row) {
      this.search_detail.id = row.id
      this.rechargeDetail(() => {
        this.dialog_detail = true
      })
    },
    // 详情明显
    changeDeatilPagination(data) {
      const { page, limit } = data
      this.search_detail.page_size = limit
      this.search_detail.page_index = page
      this.rechargeDetail()
    },
    // 详情类型
    rechargeType(type) {
      let out
      switch (type) {
        case 1:
          out = '支付'
          break
        case 2:
          out = '退回'
          break
        case 3:
          out = '扣款'
          break
        default:
          out = '后台充值'
      }
      return out
    },
    // 重置详情
    resetDetail() {
      this.search_detail = {
        id: '',
        time: '',
        page_index: 1,
        page_size: 10,
        total: 0
      }
      this.recharge_detail = {}
      this.dialog_detail = false
    },
    // 显示充值/扣款
    handleRecharge(row) {
      this.getStyle(() => {
        this.accessform.user_id = row.id
        this.accessform.user_name = row.nickname
        this.accessform.user_mobile = row.mobile
        this.dialog_recharge = true
      })
    },
    // 导出
    exportShowStyle() {
      this.getStyle(() => {
        this.dialog_import = true
      })
    },
    // 重置充值/扣款
    resetAccess() {
      this.accessform = {
        user_id: '',
        user_name: '',
        user_mobile: '',
        money: '',
        remark: ''
      }
      this.recharge_type = true
      this.dialog_recharge = false
    },
    // 明细搜索
    handleDeatilSearch() {
      this.search_detail.page_index = 1
      this.search_detail.page_size = 10
      this.rechargeDetail()
    },
    // 充值
    handleSave() {
      this.$refs.accessForm.validate((valid) => {
        if (valid) {
          this.loadingFull = true
          const { user_id, money, remark, style } = this.accessform
          save({
            user_id, money, remark, style
          }).then(res => {
            this.loadingFull = false
            if (res.code === 200) {
              this.resetAccess()
              this.getRechargeList()
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }
          }).catch(e => {
            this.loadingFull = false
          })
        } else {
          return false
        }
      })
    },
    // 扣款
    handleWithhold() {
      this.$refs.accessForm.validate((valid) => {
        if (valid) {
          this.loadingFull = true
          const { user_id, money, remark } = this.accessform
          withhold({
            user_id, money, remark
          }).then(res => {
            this.loadingFull = false
            if (res.code === 200) {
              this.resetAccess()
              this.getRechargeList()
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }
          }).catch(e => {
            this.loadingFull = false
          })
        } else {
          return false
        }
      })
    },
    // 导出
    async handleExport() {
      this.loadingFull = true
      // await toExport({
      //   search_name: this.searchParams.search_name
      // }).then(res => {
      //   this.loadingFull = false
      //   if (res.code === 200) {
      const exportList = this.rechargeList
      if (exportList.length < 1) {
        this.$message.wraning('没有数据可导出')
        return false
      }
      const header = ['代理昵称', '手机号', '账户等级', '账户余额']
      const _k = ['nickname', 'mobile', 'level', 'surplus_money']
      const _v = exportList.map(v => _k.map(j => {
        if (j === 'level') {
          v.level = v.level === 3 ? '代理公司' : (v.level === 2 ? '销售经理' : '销售主管')
        }
        v['surplus_money'] = this.oldSearchTime ? ((v.user_pay.length > 0 && v.user_pay[0].user_money) > 0 ? v.user_pay[0].user_money : 0) : v.money
        return v[j]
      }))
          import('@/vendor/Export2Excel').then(excel => {
            excel.export_json_to_excel({
              header,
              data: _v,
              filename: `${formatter(new Date(), 'yyyy-MM-dd')}资金`,
              bookType: 'xlsx'
            })
          })
          this.loadingFull = false
      //   } else {
      //     this.$message.error(res.message)
      //   }
      // }).catch(e => {
      //   this.loadingFull = false
      // })
    },
    // 导入
    handleImport(params) {
      const file = params.file
      if (!file) return
      this.import_name = file.name
      this.import_file = file
    },
    // 提交导入
    submitImport() {
      // if (!this.machStyle) {
      //   this.$message.error('请选择转账方式')
      //   return false
      // }
      if (!this.import_file) {
        this.$message.error('请上传导入文件')
        return false
      }
      const _this = this
      const reader = new FileReader()
      reader.onload = async({ target: { result }}) => {
        const workbook = XLSX.read(result, { type: 'array' })
        const list = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        _this.loadingFull = true
        toImport({
          // style: this.machStyle,
          data: list
        }).then(res => {
          _this.loadingFull = false
          if (res.code === 200) {
            this.resetImport()
            this.getRechargeList()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        }).catch(e => {
          _this.loadingFull = false
        })
      }
      reader.readAsArrayBuffer(this.import_file)
    },
    // 重置导入
    resetImport() {
      this.import_name = ''
      this.import_file = null
      // this.machStyle = ''
      // this.styleList = []
      this.dialog_import = false
    },
    // 下载模板
    exportModel() {
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: ['代理名称', '手机号', '金额', '转账方式', '备注'],
          data: [],
          filename: '导入资金模板',
          bookType: 'xlsx'
        })
      })
    },
    // 获取转账方式
    async getStyle(cb) {
      await getStyle().then(res => {
        if (res.code === 200) {
          this.styleList = res.data
        }
        cb && cb()
      }).catch(e => {
        this.styleList = []
        cb && cb()
      })
    },
    // 保存转账方式
    submitSaveStyle() {
      if (!this.accessform.style) {
        this.$message.error('请输入转账方式')
        return false
      }
      this.loadingFull = true
      saveStyle({
        title: this.accessform.style
      }).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.getStyle()
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    // 删除
    submitDeleteStyle(id) {
      this.loadingFull = true
      deleteStyle({
        id
      }).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.getStyle()
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.loadingFull = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .tableBorder{
    margin: 20px 0;
  }

  .detail_head {
    display: flex;
    justify-content: flex-start;
    align-content: flex-start;
    margin-bottom: 20px;

    p{
      margin: 0;
      margin-right: 30px;

      label {
        color: #96a6b6!important;
        font-weight: 500;
      }
    }
  }

  .detail_team_money {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-content: center;

    .all_team_money:nth-of-type(1) {
      background: #03a9f3 !important;
      margin-right: 15px;
    }
    .all_team_money:nth-of-type(2) {
      background: #9675ce !important;
    }
  }

  .all_team_money {
    background: #fb7884;
    width: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    font-size: 14px;
    color: #ffffff;
    padding: 25px 0;
    margin-top: 10px;

    p {
      margin: 0;
      text-align: center;
    }

    .big{
      font-size: 28px;
    }

    p:nth-of-type(1) {
      margin-bottom: 10px;
    }
  }

  .upload-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;

    .download {
      width: 72px;
      text-align: right;
      margin-right: 12px;
    }

    .input {
      width: 400px;

      .el-input__inner {
        border: none !important;
      }
    }

    .block {
      position: absolute;
      top: 0px;
      bottom: 0px;
      left: 0;
      right: 0;
      z-index: 99;
      border: 1px solid #DCDFE6;
    }

    .block:hover{
      border-color: #409EFF;
    }
  }

  .upload-main {
    display: flex;
    justify-content: center;
    flex-direction: column;
  }
  .handCompony {
    font-size: 12px;
    color: #409EFF;
    cursor: pointer;
  }
</style>

<style lang="scss">
  #team-recharge {
    .el-input-group__append {
        cursor: pointer;
        &:hover {
          background: #13C19F;
          color: #fff;
        }
      }
  }
</style>
