<template>
  <div class="boxNav">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-date-picker
      v-model="searchParams.year"
      type="year"
      placeholder="选择年"
      value-format="yyyy"
    />
    <el-date-picker
      v-model="searchParams.month"
      type="month"
      placeholder="选择月"
      value-format="M"
    />
    <el-input v-model="searchParams.search_name" placeholder="输入代理昵称、手机号搜索" style="display: inline-block; width: 240px;" clearable @keydown.native.enter="toSearch" @clear="toSearch" />
    <el-button type="primary" @click="toSearch">搜索</el-button>
    <el-button type="primary" @click="manual">生成金额</el-button>
    <el-button type="primary" @click="SendReward">发送通知</el-button>
    <el-button type="primary" @click="visibleImport = true">导入奖励发放信息</el-button>
    <el-button type="primary" @click="GetExpress">导出</el-button>
    <el-table
      :data="list"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
      style="margin: 20px 0;"
    >
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        :index="
          (index) => searchParams.page_size * (searchParams.page_index - 1) + index + 1
        "
      />
      <el-table-column
        prop="headimgurl"
        label="头像"
        align="center"
        width="60"
      >
        <template slot-scope="{ row }">
          <el-image :src="row.user && row.user.headimgurl" fit="contain" class="hoverImg" />
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="代理公司昵称" align="center" width="130">
        <template slot-scope="{ row }">
          <el-button type="text" @click="getOtherInfo(row.user&&row.user.id)">{{ row.user&&row.user.nickname }}</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="mobile" label="手机号" align="center">
        <template slot-scope="{ row }">
          {{ row.user&&row.user.mobile }}
        </template>
      </el-table-column> -->
      <el-table-column
        prop="hard"
        label="精装版(套)"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.hard || '0' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="gao"
        label="高腰版(件)"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.gao || '0' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="old_new"
        label="纯老版(件)"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.old_new || '0' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="youth"
        label="青春版(件)"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.youth || '0' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="simple"
        label="简约版(件)"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.simple || '0' }}
        </template>
      </el-table-column>
      <el-table-column prop="money" label="订货总金额" align="center" width="110">
        <template slot-scope="{ row }">
          {{ getThousands(row.money,1) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="money_between"
        label="所在区间"
        align="center"
        width="130"
      />
      <el-table-column
        prop="scale"
        label="业绩奖励比例"
        align="center"
        width="100"
      />
      <el-table-column prop="reward_money" label="业绩奖励金额" align="center" width="100">
        <template slot-scope="{ row }">
          {{ getThousands(row.reward_money,1) }}
        </template>
      </el-table-column>
      <el-table-column prop="real_money" label="实发金额" align="center" width="100">
        <template slot-scope="{ row }">
          {{ getThousands(row.real_money,1) }}
        </template>
      </el-table-column>
      <el-table-column prop="reward_money" label="多发金额" align="center" width="100">
        <template slot-scope="{ row }">
          <span v-show="row.real_money" :class=" row.money_balance !== '0.00' ?'red':'green'">{{ row.money_balance }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="time"
        label="发放时间"
        align="center"
        width="160"
      />
      <el-table-column
        prop="send_way"
        label="发放方式"
        align="center"
      />
      <el-table-column
        prop="send_status"
        label="是否通知"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-tag :type="row.send_status ? 'success' : 'warning'">{{ row.send_status ? '通知': '未通知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="account_name"
        label="收款人银行账户姓名"
        align="center"
        width="100"
      />
      <el-table-column
        prop="account_number"
        label="收款人银行账号"
        align="center"
        width="150"
      />
      <el-table-column
        prop="account_bank"
        label="收款人银行开户行"
        align="center"
        width="130"
      />
      <el-table-column prop="remark" label="备注" align="center" width="100" :show-overflow-tooltip="true">
        <template slot-scope="{ row }">{{ row.remark }}</template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
      >
        <template slot-scope="{ row }">
          <!-- <el-button size="text" @click="SendReward(row)">发送通知</el-button> -->
          <el-button type="text" size="mini" @click="editMoney(row)">修改金额</el-button>
          <el-button type="text" size="mini" @click="getDetail(row)">订货详情</el-button>
          <el-button type="text" size="mini" @click="getLog(row)">发放日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="prev, pager, next" :current-page="searchParams.page_index" :page-size="10" :total="total" @current-change="pageChange" />
    <el-dialog title="详情" width="40%" :visible.sync="showDetail">
      <el-table
        :data="detailInfo"
        :header-cell-style="{ background: '#f8fbfc' }"
        class="tableBorder"
        border
        stripe
        style="margin: 20px 0;"
      >
        <el-table-column
          prop="good_name"
          label="商品名称"
          align="center"
          width="200"
        />
        <el-table-column
          prop="unit"
          label="单位"
          align="center"
          width="80"
        />
        <el-table-column
          prop="num"
          label="数量"
          align="center"
        />
        <el-table-column
          prop="price"
          label="单价"
          align="center"
        />
        <el-table-column prop="money" label="金额" align="center">
          <template slot-scope="{ row }">
            {{ getThousands(row.money,1) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="导入奖励发放信息" :visible.sync="visibleImport" :before-close="resetImport" width="500px">
      <div class="upload-main" style="height:400px">
        <div class="upload-container">
          <el-button type="span" class="download" @click="exportInfo">下载模板</el-button>
          <el-upload action="" :show-file-list="false" :http-request="handleImport" accept=".xlsx, .xls">
            <div>
              <div style="position:relative">
                <el-input v-model="import_name" type="span" class="input" style="width: 300px">
                  <i slot="append" class="el-icon-upload2" />
                </el-input>
                <i class="block" />
              </div>
            </div>
          </el-upload>
        </div>
        <div class="upload-container">
          <p style="color: red">单次最多上传5000条</p>
        </div>
        <div class="upload-container">
          <el-button size="small" style="margin-right:10px" @click="resetImport">取消</el-button>
          <el-button size="small" type="primary" @click="importTemp">导入</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="修改奖励"
      :visible.sync="showEdit"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form ref="courseForm" label-width="120px" :model="form">
        <el-form-item label="订货金额：">
          {{ getThousands(form.money, 1) }}
        </el-form-item><el-form-item label="奖励比例：">
          {{ form.scale }}
        </el-form-item>
        <el-form-item label="奖励金额：">
          {{ getThousands(form.reward_money, 1) }}
        </el-form-item>
        <el-form-item label="实发金额：">
          {{ getThousands(form.real_money, 1) }}
        </el-form-item>
        <el-form-item label="多发：">
          <span v-show="form.real_money" :class=" form.money_balance !== '0.00' ?'red':'green'">{{ Number(form.money_balance) }}</span>
          <!-- <span v-show="form.real_money" :class="Number(form.real_money || '0') - Number(form.reward_money) !== 0 ?'red':'green'">{{ getThousands(Number(form.real_money || '0') - Number(form.reward_money),1) }}</span> -->
        </el-form-item>
        <el-form-item label="调整方式：">
          <span v-if="form.money_balance">{{ form.money_balance.indexOf('-') === -1 ? '扣除' : '补发' }}</span>
        </el-form-item>
        <el-form-item label="发放/扣除途径:" required>
          <el-radio-group v-model="form.send_way" size="small">
            <el-radio label="银行卡">银行卡</el-radio>
            <el-radio label="微信">微信</el-radio>
            <el-radio label="支付宝">支付宝</el-radio>
          </el-radio-group>
          <div />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="showEdit = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-drawer
      title="发放日志"
      :visible.sync="showLog"
    >
      <el-card v-for="(item, index) in logs" :key="index" style="margin: 20px" class="box-card">
        <div slot="header" class="clearfix">
          <span class="title">{{ item.time }}</span>
        </div>
        <div class="text item">
          发放金额：<span class="red">{{ getThousands(item.money, 1) }}</span>
        </div>
        <div class="text item">
          发放方式：{{ item.send_way }}
        </div>
        <div class="text item">
          发放类型：{{ item.type }}
        </div>
        <div class="text item">
          备注：{{ item.remark }}
        </div>
      </el-card>
    </el-drawer>
    <!-- 查看代理详情 -->
    <el-drawer
      :title="`${memberInfo.realname} - ${levelStatus(memberInfo.level).name}`"
      :visible.sync="visible.memberInfo"
      direction="rtl"
      :size="isH?'80%' : '600px'"
    >
      <MemberInfo
        :info="memberInfo"
        :team-type="true"
        :show-num="true"
        @getOtherInfo="changeOtherInfo"
      />
    </el-drawer>
  </div>
</template>

<script>
import { CrownRewardMoneyList, ReckonMonthMoney, UploadExcel, ExportExcel, SendRewardInfo, UpdateInfo } from '@/api/money'
import { getOtherInfo } from '@/api/user'
import { levelStatus } from '@/filters/common'
// 公共方法
import {
  getThousands
} from '@/filters/common'
// 组件
import MemberInfo from './components/MemberInfo'
const infoForm = {
  '手机号': '',
  '年': '',
  '月': '',
  '实发金额': '',
  '账户名': '',
  '账户号': '',
  '开户行': '',
  '发放方式': '',
  '发放时间': '',
  '备注': ''
}
export default {
  name: 'PageIndex',
  components: {
    MemberInfo
  },
  data() {
    return {
      showEdit: false,
      form: {},
      showLog: false,
      show: '',
      logs: [],
      import_name: '',
      import_file: '',
      visibleImport: false,
      dialogUploadImg: false,
      dialogSteps: false,
      dialogSignature: false,
      dialogExpress: false,
      downloadLoading: false,
      uploadForm: {
        id: '',
        img: ''
      },
      url: '',
      loadingFull: false,
      addForm: {
        id: '',
        express_number: '',
        express_name: '',
        express_code: ''
      },
      expressList: [],
      searchParams: {
        page_index: 1,
        page_size: 10,
        month: '',
        year: '',
        search_name: ''
      },
      detailInfo: [], // 详情
      showDetail: false, // 是否显示详情dialog
      signatureForm: {},
      stepsForm: {},
      isH: false,
      list: [],
      total: 0,
      memberInfo: {
        realname: '',
        level: ''
      },
      visible: {
        memberInfo: false
      }
    }
  },
  created() {
    this.searchParams.year = new Date().getFullYear().toString()
    const month = (new Date().getMonth()).toString()
    this.searchParams.month = month
    this.getList()
  },
  methods: {
    editMoney(row) {
      if (row.money_balance === '0.00') {
        this.$message.error('该代理公司的发放金额正常')
        return
      } else {
        this.form = JSON.parse(JSON.stringify(row))
        this.showEdit = true
      }
    },
    submit() {
      const { id, send_way, money_balance } = this.form
      const money = money_balance.replace('-', '')
      if (!send_way) {
        this.$message.error('请选择发放/扣除途径')
        return
      }
      this.loadingFull = true
      UpdateInfo({ id, money, send_way }).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.$message.success('操作成功')
          this.showEdit = false
          this.getList()
        } else {
          this.$message.error(res.message || '操作失败')
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    // 发放日志
    getLog(row) {
      if (row.log) {
        this.logs = JSON.parse(row.log)
        this.showLog = true
        console.log(this.logs)
      } else {
        this.$message.error('暂无发放日志')
      }
    },
    // 下载模板
    exportInfo() {
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(infoForm),
          data: [],
          filename: '奖励发放信息上传模板',
          bookType: 'xlsx'
        })
      })
    },
    // 导入信息
    importTemp() {
      if (!this.import_file) {
        this.$message.error('请上传导入文件')
        return false
      }
      const formdata = new FormData()
      formdata.append('file', this.import_file)
      this.loadingFull = true
      try {
        this.$request(UploadExcel(formdata), () => {
          this.loadingFull = false
          this.getList()
          this.$message.success('上传成功')
          this.resetImport()
        })
      } catch (e) {
        this.loadingFull = false
        this.$message.error(e.message || '上传失败')
      } finally {
        this.loadingFull = false
      }
    },
    // 导入
    handleImport(params) {
      const file = params.file
      if (!file) return
      this.import_name = file.name
      this.import_file = file
    },
    // 重置
    resetImport() {
      this.import_name = ''
      this.import_file = null
      this.visibleImport = false
    },
    // 发送通知
    SendReward() {
      const { month, year } = this.searchParams
      if (!month || !year) {
        this.$message.error('请选择年份和月份')
        return
      }
      this.$confirm('确定要发送通知吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingFull = true
        SendRewardInfo({ month, year }).then(res => {
          this.loadingFull = false
          if (res.code === 200) {
            this.$message.success('发送通知成功')
            this.getList()
          } else {
            this.$message.error(res.message || '发送通知失败')
          }
        }).catch(() => {
          this.loadingFull = false
        })
      }).catch(() => {})
    },
    // 生成金额
    manual() {
      const { month, year } = this.searchParams
      if (!month || !year) {
        this.$message.error('请选择年份和月份')
        return
      }
      this.$confirm('确定生成金额吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingFull = true
        ReckonMonthMoney({ month, year }).then(res => {
          this.loadingFull = false
          if (res.code === 200) {
            this.$message.success('生成金额成功')
            this.getList()
          } else {
            this.$message.error(res.message || '生成金额失败')
          }
        }).catch(() => {
          this.loadingFull = false
        })
      }).catch(() => {})
    },
    // 获取详情
    getDetail(row) {
      this.detailInfo = row.detail
      this.showDetail = true
    },
    // 销售级别
    levelStatus(level) {
      return levelStatus(level)
    },
    // 千分位
    getThousands(data, isDecimals) {
      return getThousands(data, isDecimals)
    },
    // 搜索
    toSearch() {
      this.searchParams.page_index = 1
      this.getList()
    },
    // 代理详情
    changeOtherInfo(id) {
      this.getOtherInfo(id, (data) => {
        this.getSendList()
      })
    },
    // 查看代理详情
    handleSeeMemberInfo(row) {
      this.memberInfo = row
      this.visible.memberInfo = true
    },
    // 获取上级销售或邀请人信息
    async getOtherInfo(id, cb) {
      if (!id) {
        this.$message.error('获取用户id失败')
        return false
      }
      this.loadingFull = true
      try {
        const res = await getOtherInfo({ id })
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          this.handleSeeMemberInfo(data)
          cb && cb(data)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取邀请人或上级销售信息失败:${e}`)
      }
      this.loadingFull = false
    },
    // 导出
    async GetExpress() {
      this.loadingFull = true
      await ExportExcel(this.searchParams).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          if (res.data && res.data.length > 0) {
            import('@/vendor/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: Object.keys(res.data[0]),
                data: res.data.map(listItem => Object.keys(res.data[0]).map(j => listItem[j])),
                filename: `${this.searchParams.year + '-' + (this.searchParams.month > 9 ? this.searchParams.month : '0' + this.searchParams.month)}代理公司业绩奖励`,
                bookType: 'xlsx'
              })
            })
          } else {
            this.$message.error('没有可导出数据')
          }
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    pageChange(page) { // 换页
      this.searchParams.page_index = page
      this.getList()
    },
    // 获取列表
    getList() {
      this.loadingFull = true
      CrownRewardMoneyList(this.searchParams).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          console.log(res)
          this.list = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error(res.message || '获取列表失败')
        }
      }).catch(() => {
        this.loadingFull = false
        this.$message.error('获取列表失败')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .box-card {
    width: 480px;
    .text {
      font-size: 15px;
    }
    .item {
      margin-bottom: 18px;
    }
    .clearfix:before, .clearfix:after {
      display: table;
      content: "";
    }
    .clearfix:after {
      clear: both
    }
    .red  {
      color: #f23434;
    }
    .title {
      font-weight: bold;font-size: 16px;
    }
  }
.red {
  color: #F56C6C;
}
.green {
  color: #67C23A;
}
.el-pagination {
  margin: 8px;
  text-align: center;
}
.boxNav {
  padding: 20px;
}
.tag {
    padding: 2px;
    font-size: 12px;
    line-height: 1;
    border-radius: 2px;
    font-family: simsun;
    color: #fff;
    display: inline;
    cursor: pointer;
    margin: 0 2px 0 0;
  }
.return-tag {
    color: #8c7ee4;
    border: 1px solid rgba(140,123,231,.4);
    display: inline-block;
  }
.time {
  font-size: 10px;
  margin-top: 5px;
  display: inline-block;
  color: #9DA0A2;
}
.bold {
  font-size: 18px;
  // font-weight: bold;
}
.thumbUrld {
  display: block;
  width: 100px;
  height: 100px;
}
.thumbUrl{
    display: block;
    width: 145px;
    height: 145px;
    margin-bottom: 15px;
    margin-right: 15px;
  }
  .upload-main {
    display: flex;
    justify-content: center;
    flex-direction: column;
  }
  .upload-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;

    .download {
      width: 100px;
      span-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;
    }
  }
</style>
